diff --git a/tsserver/cs/diagnosticMessages.generated.json b/tsserver/cs/diagnosticMessages.generated.json index 1f126cf7..fe4fc282 100644 --- a/tsserver/cs/diagnosticMessages.generated.json +++ b/tsserver/cs/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Typ this je k dispozici jenom v nestatických členech třídy nebo rozhraní.", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Soubor tsconfig.json je už v {0} definovaný.", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Člen řazené kolekce členů nemůže být volitelný a zbytek.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Typ řazené kolekce členů není možné indexovat zápornou hodnotou.", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Výraz potvrzení typu se na levé straně výrazu umocnění nepovoluje. Zvažte možnost uzavření výrazu do závorek.", "A_type_literal_property_cannot_have_an_initializer_1247": "Vlastnost literálu typu nemůže mít inicializátor.", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Import, při kterém se importují jen typy, může určovat výchozí import nebo pojmenované vazby, ale ne obojí.", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "Přidat kontrolní výraz jednoznačného přiřazení k vlastnosti {0}", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Přidat kontrolní výrazy jednoznačného přiřazení do všech neinicializovaných vlastností", "Add_export_to_make_this_file_into_a_module_95097": "Přidat export {}, aby se tento soubor převedl na modul", + "Add_extends_constraint_2211": "Přidejte omezení extends.", + "Add_extends_constraint_to_all_type_parameters_2212": "Přidat omezení extends ke všem parametrům typu", "Add_import_from_0_90057": "Přidat import z {0}", "Add_index_signature_for_property_0_90017": "Přidat signaturu indexu pro vlastnost {0}", "Add_initializer_to_property_0_95019": "Přidat inicializační výraz k vlastnosti {0}", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "V parametru signatury indexu nemůže být anotace typu.", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Typ parametru signatury indexu nemůže být typ literálu nebo obecný typ. Místo toho zvažte použití namapovaného typu objektu.", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Typ parametru signatury indexu musí být řetězec, číslo, symbol nebo typ literálu šablony.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Po výrazu vytvoření instance nemůže následovat přístup k vlastnosti.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Rozhraní může rozšířit jenom identifikátor nebo kvalifikovaný název s volitelnými argumenty typu.", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Rozhraní může rozšiřovat jen typ objektu nebo průsečík typů objektů se staticky známými členy.", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "Rozhraní nemůže rozšířit primitivní typ, jako je {0}; rozhraní může rozšířit jenom pojmenované typy a třídy.", "An_interface_property_cannot_have_an_initializer_1246": "Vlastnost rozhraní nemůže mít inicializátor.", "An_iterator_must_have_a_next_method_2489": "Iterátor musí mít metodu next().", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Při použití direktivy pragma @jsx s fragmenty JSX se vyžaduje direktiva pragma @jsxFrag.", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Třída {0} nesprávně implementuje třídu {1}. Nechtěli jste rozšířit třídu {1} a dědit její členy jako podtřídu?", "Class_0_incorrectly_implements_interface_1_2420": "Třída {0} nesprávně implementuje rozhraní {1}.", "Class_0_used_before_its_declaration_2449": "Třída {0} se používá dříve, než se deklaruje.", + "Class_constructor_may_not_be_a_generator_1360": "Konstruktor třídy nemůže být generátor.", + "Class_constructor_may_not_be_an_accessor_1341": "Konstruktor třídy nemůže být přístupový objekt.", "Class_declaration_cannot_implement_overload_list_for_0_2813": "Deklarace třídy nemůže implementovat seznam přetížení pro {0}.", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Deklarace tříd nemůžou mít více než jednu značku ‚@augments‘ nebo ‚@extends‘.", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Dekorátory tříd se nedají použít se statickým privátním identifikátorem. Zvažte možnost odebrat experimentální dekorátor.", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "Soubor {0} se nenašel.", "File_Management_6245": "Správa souborů", "File_change_detected_Starting_incremental_compilation_6032": "Zjistila se změna souboru. Spouští se přírůstková kompilace...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "Soubor je modul CommonJS, protože {0} nemá pole type", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "Soubor je modul CommonJS, protože {0} má pole type, jehož hodnota není module", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "Soubor je modul CommonJS, protože se nenašel package.json", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "Soubor je modul ECMAScript, protože {0} má pole type s hodnotou module", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Soubor je modul CommonJS; může být převeden na modul ES.", "File_is_default_library_for_target_specified_here_1426": "Soubor je výchozí knihovna pro cíl, který se zadal na tomto místě.", "File_is_entry_point_of_type_library_specified_here_1419": "Soubor je vstupní bod knihovny typů, která se zadala na tomto místě.", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Očekává se identifikátor. {0} je rezervované slovo, které se tady nedá použít.", "Identifier_expected_1003": "Očekával se identifikátor.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Očekává se identifikátor. __esModule je při transformaci modulů ECMAScript rezervované jako označení exportu.", + "Identifier_or_string_literal_expected_1478": "Očekává se identifikátor nebo řetězcový literál.", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Pokud balíček ‚{0}‘ ve skutečnosti zveřejňuje tento modul, zvažte možnost poslat žádost o přijetí změn, aby se připojila adresa ‚https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}‘", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Pokud balíček {0} skutečně zpřístupňuje tento modul, zkuste přidat nový soubor deklarace (.d.ts), který obsahuje declare module {1};", "Ignore_this_error_message_90019": "Ignorovat tuto chybovou zprávu", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "Neplatný specifikátor importu {0} nemá žádná možná řešení.", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Neplatný název modulu v rozšíření. Modul {0} se převede na netypový modul v {1}, který se nedá rozšířit.", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "V rozšíření je neplatný název modulu, modul {0} se nedá najít.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Neplatný volitelný řetěz z nového výrazu. Chtěli jste volat {0}()?", "Invalid_reference_directive_syntax_1084": "Neplatná syntaxe direktivy reference", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Neplatné použití „{0}“. Nelze jej použít uvnitř statického bloku třídy.", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Neplatné použití {0}. Moduly jsou automaticky ve striktním režimu.", @@ -893,6 +906,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_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}.", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "Člen {0} má implicitně typ {1}, ale je možné, že lepší typ by se vyvodil z použití.", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Projekt {0} nejde sestavit, protože jeho závislost {1} obsahuje chyby.", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Projekt {0} nejde sestavit, protože se nesestavila jeho závislost {1}.", "Project_0_is_being_forcibly_rebuilt_6388": "Projekt {0} se nuceně vytváří znovu.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "{0} projektu je zastaralý, protože soubor buildinfo {1} indikuje, že se některé změny nevygenerovaly.", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Projekt {0} je zastaralý, protože jeho závislost {1} je zastaralá.", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Projekt {0} je zastaralý, protože nejstarší výstup {1} je starší než nejnovější vstup {2}.", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "Projekt {0} je zastaralý, protože výstup {1} je starší než vstup {2}.", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Projekt {0} je zastaralý, protože výstupní soubor {1} neexistuje.", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "Projekt {0} je zastaralý, protože jeho výstup se vygeneroval pomocí verze {1}, která se liší od aktuální verze {2}.", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "Projekt {0} je zastaralý, protože se změnil výstup jeho závislosti {1}.", "Project_0_is_up_to_date_6361": "Projekt {0} je aktuální.", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Projekt {0} je aktuální, protože nejnovější vstup {1} je starší než nejstarší výstup {2}.", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "Projekt {0} je aktuální, protože nejnovější vstup {1} je starší než výstup {2}.", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "Projekt {0} je aktuální, ale musí aktualizovat časová razítka výstupních souborů, které jsou starší než vstupní soubory.", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Projekt {0} je aktualizovaný soubory .d.ts z jeho závislostí.", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odkazy projektu nemůžou tvořit cyklický graf. Zjistil se cyklus: {0}", "Projects_6255": "Projekty", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Požadované parametry typu nemůžou být až za volitelnými parametry typu.", "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}.", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Režimy řešení se podporují pouze v případě, že hodnota moduleResolution je node16 nebo nodenext.", "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_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}.", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Pokud se v příkazu k exportu používá „export type“, nemůžete v pojmenovaném exportu použít modifikátor „type“.", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "Pokud se v příkazu k importu používá „import type“, nemůžete v pojmenovaném importu použít modifikátor „type“.", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "Typ deklarace funkce musí odpovídat její signatuře.", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "Tento typ výrazu se nedá pojmenovat bez kontrolního výrazu resolution-mode, což je nestabilní funkce. K potlačení této chyby použijte noční vydání TypeScript. Pokuste se o update pomocí „npm install -D typescript@next'.“.", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "Uzel tohoto typu nejde serializovat, protože nejde serializovat jeho vlastnost {0}.", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Typ vrácený metodou {0}() asynchronního iterátoru musí být příslib pro typ s vlastností value.", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Typ vrácený metodou {0}() iterátoru musí obsahovat vlastnost value.", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Příkaz with není podporovaný. Všechny symboly s blokem with budou typu any.", "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_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_0_since_the_types_1_and_2_have_no_overlap_2367": "Tato podmínka vždy vrátí {0}, protože typy {1} a {2} se nijak nepřekrývají.", "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?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Tato syntaxe vyžaduje importovanou podpůrnou aplikaci, ale modul {0} se nenašel.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Tato syntaxe vyžaduje importovanou pomocnou rutinu s názvem {1}, která v {0} neexistuje. Zvažte možnost upgradovat verzi {0}.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Tato syntaxe vyžaduje importovanou pomocnou rutinu s názvem {1} a parametry {2}, která není kompatibilní s tou v {0}. Zvažte upgrade verze {0}.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Tento parametr typu může potřebovat omezení extends {0}.", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Toto použití importu není platné. Volání import() se dají zapsat, ale musí mít závorky a nemůžou mít typové argumenty.", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Výrazy await nejvyšší úrovně se povolují jen v případě, že možnost module je nastavená na es2022, esnext, system, node16 nebo nodenext a možnost target je nastavená na es2017 nebo vyšší.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Deklarace nejvyšší úrovně v souborech .d.ts musí začínat modifikátorem declare, nebo export.", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Knihovna typů, na kterou se odkazuje přes {0} ze souboru {1} s packageId {2}", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Typ operandu await musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Typ hodnoty počítané vlastnosti je {0} a nedá se přiřadit do typu {1}.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "Typ instance členské proměnné {0} nemůže odkazovat na identifikátor {1} deklarovaný v konstruktoru.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterovaných elementů yield* musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Typ vlastnosti {0} cyklicky odkazuje sám na sebe v mapovaném typu {1}.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu yield v asynchronním generátoru musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== Direktiva odkazu na typ {0} se nepřeložila. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Direktiva odkazu na typ {0} se úspěšně přeložila na {1}, primární: {2}. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== Direktiva odkazu na typ {0} se úspěšně přeložila na {1} s ID balíčku {2}, primární: {3}. ========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Typy se v deklaracích exportu v souborech JavaScriptu nemůžou vyskytovat.", "Types_have_separate_declarations_of_a_private_property_0_2442": "Typy mají samostatné deklarace privátní vlastnosti {0}.", "Types_of_construct_signatures_are_incompatible_2419": "Typy signatur konstruktorů nejsou kompatibilní.", "Types_of_parameters_0_and_1_are_incompatible_2328": "Typy parametrů {0} a {1} jsou nekompatibilní.", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "Režimy sledování a sestavování", "Watch_input_files_6005": "Sledovat vstupní soubory", "Watch_option_0_requires_a_value_of_type_1_5080": "Možnost sledování {0} vyžaduje hodnotu typu {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Pro {0} můžeme napsat typ jenom tak, že sem přidáme typ pro celý parametr.", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Při přiřazování funkcí zkontrolujte a zajistěte, aby parametry a vrácené hodnoty měly kompatibilní podtypy.", "When_type_checking_take_into_account_null_and_undefined_6699": "Při kontrole typů berte v potaz i hodnoty „null“ a „undefined“.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Určuje, jestli se místo vymazání obrazovky má zachovat zastaralý výstup konzoly v režimu sledování.", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Uzavřít následující kód, který by měl být literál objektu, do závorek", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Informace o všech možnostech kompilátoru najdete na {0}", "You_cannot_rename_a_module_via_a_global_import_8031": "Přes globální import se modul nedá přejmenovat.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Nelze přejmenovat elementy definované ve složce node_modules.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Nelze přejmenovat elementy definované v jiné složce node_modules.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nejde přejmenovat elementy definované ve standardní knihovně TypeScriptu.", "You_cannot_rename_this_element_8000": "Tento element nejde přejmenovat.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Objekt {0} přijímá málo argumentů k tomu, aby se dal použít jako dekoratér. Nechtěli jste ho nejprve volat a napsat @{0}()?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "Signatury indexu {0} jsou nekompatibilní.", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "{0} Typ indexu {1} se nedá přiřadit k {2} typu indexu {3}.", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "{0} je primitivum, ale {1} je obálkový objekt. Pokud je to možné, použijte raději {0}.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "{0} je typ a nedá se importovat do javascriptových souborů. V poznámce typu JSDoc použijte {1}.", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "Hodnota {0} je typ a musí být importována pomocí importu, který se bude zadávat jenom v případě, že jsou povolené parametry preserveValueImports a isolatedModules.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "{0} je nepoužívané přejmenování {1}. Chtěli jste ji použít jako poznámku typu?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "{0} se dá přiřadit k omezení typu {1}, ale pro {1} se dala vytvořit instance s jiným podtypem omezení {2}.", + "_0_is_automatically_exported_here_18044": "{0} se sem automaticky exportuje.", "_0_is_declared_but_its_value_is_never_read_6133": "Deklaruje se {0}, ale jeho hodnota se vůbec nečte.", "_0_is_declared_but_never_used_6196": "{0} se nadeklarovalo, ale nepoužilo.", "_0_is_declared_here_2728": "{0} je deklarované tady.", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "jeden z:", "one_or_more_Colon_6901": "1 nebo více:", "options_6024": "možnosti", + "or_JSX_element_expected_1145": "Očekával se element { nebo JSX.", "or_expected_1144": "Očekává se znak { nebo ;.", "package_json_does_not_have_a_0_field_6100": "Soubor package.json neobsahuje pole {0}.", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "package.json nemá položku typesVersions, která by odpovídala verzi {0}.", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modifikátor readonly se může objevit jenom v deklaraci vlastnosti nebo signatuře indexu.", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "Modifikátor typu readonly se povoluje jen pro typy literálů pole a řazené kolekce členů.", "require_call_may_be_converted_to_an_import_80005": "Volání require se dá převést na import.", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Kontrolní výrazy resolution-mode se podporují jenom tehdy, kdy je moduleResolution node16 nebo nodenext", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "Kontrolní výrazy resolution-mode jsou nestabilní. K potlačení této chyby použijte noční vydání TypeScript. Pokuste se o update pomocí „npm install -D typescript@next'.“.", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "resolution-mode se dá nastavit pouze pro importy type-only.", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "resolution-mode je jediný platný klíč pro kontrolní výrazy importu typů.", "resolution_mode_should_be_either_require_or_import_1453": "resolution-mode by měl být buď require, nebo import.", diff --git a/tsserver/de/diagnosticMessages.generated.json b/tsserver/de/diagnosticMessages.generated.json index 7ff4ec4f..5e4c0191 100644 --- a/tsserver/de/diagnosticMessages.generated.json +++ b/tsserver/de/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Ein this-Typ ist nur in einem nicht statischen Member einer Klasse oder Schnittstelle verfügbar.", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Eine Datei \"tsconfig.json\" ist bereits definiert unter: \"{0}\".", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Ein Tupelelement kann nicht gleichzeitig als \"optional\" und als \"rest\" festgelegt werden.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Ein Tupeltyp kann nicht mit einem negativen Wert indiziert werden.", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Typassertionsausdrücke sind in der linken Seite von Potenzierungsausdrücken nicht zulässig. Erwägen Sie, den Ausdruck in Klammern zu setzen.", "A_type_literal_property_cannot_have_an_initializer_1247": "Typliteraleigenschaften können keinen Initialisierer aufweisen.", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Ein reiner Typenimport kann einen Standardimport oder benannte Bindungen angeben, aber nicht beides.", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "Definitive Zuweisungsassertion zu Eigenschaft \"{0}\" hinzufügen", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Allen nicht initialisierten Eigenschaften definitive Zuweisungsassertionen hinzufügen", "Add_export_to_make_this_file_into_a_module_95097": "\"export {}\" hinzufügen, um diese Datei in ein Modul umzuwandeln", + "Add_extends_constraint_2211": "\"extends\"-Einschränkung hinzufügen", + "Add_extends_constraint_to_all_type_parameters_2212": "\"extends\"-Einschränkung zu allen Typparametern hinzufügen", "Add_import_from_0_90057": "Import aus \"{0}\" hinzufügen", "Add_index_signature_for_property_0_90017": "Indexsignatur für die Eigenschaft \"{0}\" hinzufügen", "Add_initializer_to_property_0_95019": "Initialisierer zu Eigenschaft \"{0}\" hinzufügen", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "Ein Indexsignaturparameter muss eine Typanmerkung besitzen.", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Ein Indexsignaturparametertyp darf kein Literaltyp oder generischer Typ sein. Erwägen Sie stattdessen die Verwendung eines zugeordneten Objekttyps.", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Ein Parametertyp für die Indexsignatur muss \"string\", \"number\", \"symbol\" oder ein Vorlagenliteraltyp sein.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Auf einen Instanziierungsausdruck kann kein Eigenschaftenzugriff folgen.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Eine Schnittstelle kann nur einen Bezeichner/\"qualified-name\" mit optionalen Typargumenten erweitern.", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Eine Schnittstelle kann nur einen Objekttyp oder eine Schnittmenge von Objekttypen mit statisch bekannten Membern erweitern.", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "Eine Schnittstelle kann einen primitiven Typ wie „{0}“ nicht erweitern; eine Schnittstelle kann nur benannte Typen und Klassen erweitern", "An_interface_property_cannot_have_an_initializer_1246": "Schnittstelleneigenschaften können keinen Initialisierer aufweisen.", "An_iterator_must_have_a_next_method_2489": "Ein Iterator muss eine Methode \"next()\" besitzen.", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Bei Verwendung eines @jsx-Pragmas mit JSX-Fragmenten wird ein @jsxFrag-Pragma benötigt.", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Die Klasse \"{0}\" implementiert fälschlicherweise die Klasse \"{1}\". Wollten Sie \"{1}\" erweitern und ihre Member als Unterklasse vererben?", "Class_0_incorrectly_implements_interface_1_2420": "Die Klasse \"{0}\" implementiert fälschlicherweise die Schnittstelle \"{1}\".", "Class_0_used_before_its_declaration_2449": "Klasse \"{0}\", die vor der Deklaration verwendet wurde.", + "Class_constructor_may_not_be_a_generator_1360": "Der Klassenkonstruktor darf kein Generator sein.", + "Class_constructor_may_not_be_an_accessor_1341": "Der Klassenkonstruktor darf kein Accessor sein.", "Class_declaration_cannot_implement_overload_list_for_0_2813": "Die Klassendeklaration kann die Überladungsliste für \"{0}\" nicht implementieren.", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Klassendeklarationen dürfen maximal ein \"@augments\"- oder \"@extends\"-Tag aufweisen.", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Decorator-Elemente von Klassen können nicht mit einem statischen privaten Bezeichner verwendet werden. Erwägen Sie, das experimentelle Decorator-Element zu entfernen.", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "Die Datei \"{0}\" wurde nicht gefunden.", "File_Management_6245": "Dateiverwaltung", "File_change_detected_Starting_incremental_compilation_6032": "Es wurde eine Dateiänderung erkannt. Die inkrementelle Kompilierung wird gestartet...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "Die Datei ist ein CommonJS-Modul, da '{0}' nicht das Feld „Typ“ aufweist", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "Die Datei ist ein CommonJS-Modul, da '{0}' das Feld „Typ“ aufweist, dessen Wert nicht „Modul“ ist", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "Die Datei ist ein CommonJS-Modul, da „package.json“ nicht gefunden wurde", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "Die Datei ist ein ECMAScript-Modul, da '{0}' das Feld „Typ“ mit dem Wert „Modul“ aufweist.", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Die Datei ist ein CommonJS-Modul und kann möglicherweise in ein ES-Modul konvertiert werden.", "File_is_default_library_for_target_specified_here_1426": "Die Datei ist die Standardbibliothek für das hier angegebene Ziel.", "File_is_entry_point_of_type_library_specified_here_1419": "Die Datei ist ein Einstiegspunkt der hier angegebenen Typbibliothek.", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Bezeichner erwartet. \"{0}\" ist ein reserviertes Wort, das hier nicht verwendet werden kann.", "Identifier_expected_1003": "Es wurde ein Bezeichner erwartet.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Bezeichner erwartet. \"__esModule\" ist als exportierter Marker für die Umwandlung von ECMAScript-Modulen reserviert.", + "Identifier_or_string_literal_expected_1478": "Bezeichner oder Zeichenfolgenliteral erwartet.", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Wenn das Paket \"{0}\" dieses Modul tatsächlich verfügbar macht, erwägen Sie, einen Pull Request zum Ändern von https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1} zu senden.", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Wenn das Paket \"{0}\" dieses Modul tatsächlich verfügbar macht, versuchen Sie, eine neue Deklarationsdatei (.d.ts) hinzuzufügen, die Declare-Modul \"{1}\" enthält.", "Ignore_this_error_message_90019": "Diese Fehlermeldung ignorieren", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "Der ungültige Importbezeichner \"{0}\" weist keine möglichen Auflösungen auf.", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Ungültiger Modulname in Augmentation. Das Modul \"{0}\" wird in ein nicht typisiertes Modul in \"{1}\" aufgelöst, das nicht augmentiert werden kann.", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Ungültiger Modulname in der Erweiterung. Das Modul \"{0}\" wurde nicht gefunden.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Ungültige optionale Kette aus neuem Ausdruck. Wollten Sie '{0}()' anrufen?", "Invalid_reference_directive_syntax_1084": "Ungültige Syntax der reference-Direktive.", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Ungültige Verwendung von \"{0}\". Es kann nicht innerhalb eines statischen Klassenblocks verwendet werden.", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Ungültige Verwendung von \"{0}\". Module befinden sich automatisch im Strict-Modus.", @@ -893,6 +906,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_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.", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "Member \"{0}\" weist implizit einen Typ \"{1}\" auf, möglicherweise kann jedoch ein besserer Typ aus der Syntax abgeleitet werden.", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Projekt \"{0}\" kann nicht erstellt werden, weil die Abhängigkeit \"{1}\" Fehler enthält.", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Das Projekt \"{0}\" kann nicht erstellt werden, weil die zugehörige Abhängigkeit \"{1}\" nicht erstellt wurde.", "Project_0_is_being_forcibly_rebuilt_6388": "Die Neuerstellung des Projekts \"{0}\" wird erzwungen.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "Das Projekt \"{0}\" ist veraltet, da die Buildinfodatei \"{1}\" angibt, dass einige der Änderungen nicht ausgegeben wurden.", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Projekt \"{0}\" ist veraltet, weil die Abhängigkeit \"{1}\" veraltet ist.", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Projekt \"{0}\" ist veraltet, weil die älteste Ausgabe \"{1}\" älter ist als die neueste Eingabe \"{2}\".", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "Das Projekt \"{0}\" ist veraltet, weil die Ausgabe \"{1}\" älter ist als die Eingabe \"{2}\"", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Projekt \"{0}\" ist veraltet, weil die Ausgabedatei \"{1}\" nicht vorhanden ist.", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "Das Projekt \"{0}\" ist veraltet, weil die Ausgabe für das Projekt mit Version {1} generiert wurde, die sich von der aktuellen Version {2} unterscheidet.", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "Das Projekt \"{0}\" ist veraltet, weil sich die zugehörige Abhängigkeit \"{1}\" geändert hat.", "Project_0_is_up_to_date_6361": "Projekt \"{0}\" ist auf dem neuesten Stand.", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Projekt \"{0}\" ist auf dem neuesten Stand, weil die neueste Eingabe \"{1}\" älter ist als die älteste Ausgabe \"{2}\".", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "Projekt \"{0}\" ist auf dem neuesten Stand, weil die neueste Eingabe \"{1}\" älter ist als die Ausgabe \"{2}\".", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "Das Projekt \"{0}\" ist aktuell, muss jedoch Zeitstempel von Ausgabedateien aktualisieren, die älter als Eingabedateien sind.", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Projekt \"{0}\" ist mit .d.ts-Dateien aus den zugehörigen Abhängigkeiten auf dem neuesten Stand.", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Projektverweise dürfen keinen kreisförmigen Graphen bilden. Zyklus erkannt: {0}", "Projects_6255": "Projekte", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Erforderliche Typparameter dürfen nicht auf optionale Typparameter folgen.", "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.", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Auflösungsmodi werden nur unterstützt, wenn „moduleResolution“ „node16“ oder „nodenext“ ist.", "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_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.", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Der \"Type\"-Modifizierer kann nicht für einen benannten Export verwendet werden, wenn \"Export-Typ\" auf seiner Export-Anweisung verwendet wird.", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "Der \"Type\"-Modifizierer kann nicht für einen benannten Import verwendet werden, wenn der \"Import-Typ\" auf seiner Import-Anweisung verwendet wird.", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "Der Typ einer Funktionsdeklaration muss mit der Signatur der Funktion übereinstimmen.", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "Der Typ dieses Ausdrucks kann nicht ohne eine „resolution-mode“-Assertion benannt werden, was eine instabile Funktion ist. Verwenden Sie nächtliches TypeScript, um diesen Fehler zu unterdrücken. Versuchen Sie, mit „npm install -D typescript@next“ zu aktualisieren.", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "Der Typ dieses Knotens kann nicht serialisiert werden, da seine Eigenschaft \"{0}\" nicht serialisiert werden kann.", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Der von der {0}()-Methode eines Async-Iterators zurückgegebene Typ muss eine Zusage für einen Typ mit einer value-Eigenschaft sein.", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Der von der {0}()-Methode eines Iterators zurückgegebene Typ muss eine value-Eigenschaft aufweisen.", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Die with-Anweisung wird nicht unterstützt. Alle Symbole in einem with-Block weisen den Typ \"any\" auf.", "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_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_0_since_the_types_1_and_2_have_no_overlap_2367": "Diese Bedingung gibt immer \"{0}\" zurück, weil die Typen \"{1}\" und \"{2}\" keine Überschneidung aufweisen.", "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?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Diese Syntax erfordert ein importiertes Hilfsprogramm, aber das Modul \"{0}\" wurde nicht gefunden.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Diese Syntax erfordert ein importiertes Hilfsprogramm namens \"{1}\", das in \"{0}\" nicht vorhanden ist. Erwägen Sie ein Upgrade Ihrer Version von \"{0}\".", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Diese Syntax erfordert ein importiertes Hilfsprogramm mit dem Namen \"{1}\" mit {2} Parametern, die nicht mit der in \"{0}\" kompatibel ist. Erwägen Sie ein Upgrade Ihrer Version von \"{0}\".", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Für diesen Typparameter ist möglicherweise die Einschränkung \"extends {0}\" erforderlich.", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Diese Verwendung von „import“ ist ungültig. „import()“-Aufrufe können geschrieben werden, müssen jedoch Klammern aufweisen und dürfen keine Typargumente aufweisen.", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "'await'-Ausdrücke der obersten Ebene sind nur zulässig, wenn die 'module'-Option auf 'es2022', 'esnext', 'system', 'node16' oder 'nodenext' und die 'target'-Option auf ' es2017' oder höher.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Deklarationen der obersten Ebene in .d.ts-Dateien müssen entweder mit einem declare- oder einem export-Modifizierer beginnen.", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Typbibliothek, die über \"{0}\" aus der Datei \"{1}\" mit packageId \"{2}\" referenziert wird", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Der Typ des \"await\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Der Typ des Werts der berechneten Eigenschaft lautet \"{0}\" und kann dem Typ \"{1}\" nicht zugewiesen werden.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "Der Typ der Instanzmembervariablen „{0}“ darf nicht auf den im Konstruktor deklarierten Bezeichner „{1}“ verweisen.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Der Typ iterierter Elemente eines \"yield*\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Der Typ der Eigenschaft \"{0}\" verweist im zugeordneten Typ \"{1}\" auf sich selbst.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Der Typ eines \"yield\"-Operanden in einem asynchronen Generator muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== Die Typverweisdirektive \"{0}\" wurde nicht aufgelöst. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Die Typverweisdirektive \"{0}\" wurde erfolgreich in \"{1}\" aufgelöst. Primär: {2}. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== Die Typverweisdirektive \"{0}\" wurde erfolgreich in \"{1}\" mit Paket-ID \"{2}\" aufgelöst. Primär: {3}. ========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Typen können in Exportdeklarationen in JavaScript-Dateien nicht angezeigt werden.", "Types_have_separate_declarations_of_a_private_property_0_2442": "Typen weisen separate Deklarationen einer privaten Eigenschaft \"{0}\" auf.", "Types_of_construct_signatures_are_incompatible_2419": "Die Typen der Konstruktsignaturen sind nicht kompatibel.", "Types_of_parameters_0_and_1_are_incompatible_2328": "Die Typen der Parameter \"{0}\" und \"{1}\" sind nicht kompatibel.", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "Überwachungs- und Buildmodi", "Watch_input_files_6005": "Eingabedateien überwachen.", "Watch_option_0_requires_a_value_of_type_1_5080": "Die Überwachungsoption \"{0}\" erfordert einen Wert vom Typ \"{1}\".", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Wir können nur einen Typ für „{0}“ schreiben, indem hier ein Typ für den gesamten Parameter hinzugefügt wird.", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Überprüfen Sie beim Zuweisen von Funktionen, ob Parameter und Rückgabewerte untertypkompatibel sind.", "When_type_checking_take_into_account_null_and_undefined_6699": "Berücksichtigen Sie bei der Typüberprüfung „null“ und „undefined“.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Gibt an, ob eine veraltete Konsolenausgabe im Überwachungsmodus beibehalten wird, statt den Bildschirm zu löschen.", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Schließen Sie den folgenden Text, der ein Objektliteral darstellt, in Klammern ein.", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Informationen zu allen Compileroptionen finden Sie unter {0}", "You_cannot_rename_a_module_via_a_global_import_8031": "Ein Modul kann nicht über einen globalen Import umbenannt werden.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Elemente, die in einem Ordner \"node_modules\" definiert sind, können nicht umbenannt werden.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Elemente, die in einem anderen Ordner \"node_modules\" definiert sind, können nicht umbenannt werden.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Sie können keine Elemente umbenennen, die in der TypeScript-Standardbibliothek definiert sind.", "You_cannot_rename_this_element_8000": "Sie können dieses Element nicht umbenennen.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" akzeptiert zu wenige Argumente, um hier als Decorator verwendet zu werden. Wollten Sie es zuerst aufrufen und \"@{0}()\" schreiben?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "\"{0}\" Indexsignaturen sind inkompatibel.", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "\"{0}\" Indextyp \"{1}\" kann nicht \"{2}\" Indextyp \"{3}\" zugewiesen werden.", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "\"{0}\" ist ein primitiver Typ, aber \"{1}\" ist ein Wrapperobjekt. Verwenden Sie vorzugsweise \"{0}\", wenn möglich.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "\"{0}\" ist ein Typ und kann nicht in JavaScript-Dateien importiert werden. Verwenden Sie \"{1}\" in einer JSDoc-Typanmerkung.", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "„{0}“ ist ein Typ und muss mithilfe eines reinen Typimports importiert werden, wenn „preserveValueImports“ und isolatedModules“ beide aktiviert sind.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "„{0}“ ist eine nicht verwendete Umbenennung von „{1}“. Wollten Sie sie als Typanmerkung verwenden?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "\"{0}\" kann der Einschränkung vom Typ \"{1}\" zugewiesen werden, aber \"{1}\" könnte mit einem anderen Untertyp der Einschränkung \"{2}\" instanziiert werden.", + "_0_is_automatically_exported_here_18044": "\"{0}\" wird hier automatisch exportiert.", "_0_is_declared_but_its_value_is_never_read_6133": "\"{0}\" ist deklariert, aber der zugehörige Wert wird nie gelesen.", "_0_is_declared_but_never_used_6196": "\"{0}\" ist deklariert, wird aber nie verwendet.", "_0_is_declared_here_2728": "\"{0}\" wird hier deklariert.", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "eines von:", "one_or_more_Colon_6901": "eins oder mehr:", "options_6024": "Optionen", + "or_JSX_element_expected_1145": "'{' oder JSX-Element erwartet.", "or_expected_1144": "\"{\" oder \";\" wurde erwartet.", "package_json_does_not_have_a_0_field_6100": "\"package.json\" besitzt kein \"{0}\"-Feld.", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "\"package.json\" weist keinen Eintrag \"typesVersions\" auf, der mit der Version {0} übereinstimmt.", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Der Modifizierer \"readonly\" darf nur für eine Eigenschaftendeklaration oder Indexsignatur verwendet werden.", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "Der Typmodifizierer \"readonly\" ist nur für Array- und Tupelliteraltypen zulässig.", "require_call_may_be_converted_to_an_import_80005": "Der Aufruf von \"require\" kann in einen Aufruf von \"import\" konvertiert werden.", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "„resolution-mode“-Zusicherungen werden nur unterstützt, wenn „moduleResolution“ „node16“ oder „nodenext“ ist.", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "'resolution-mode' Behauptungen sind instabil. Verwenden Sie nächtliches TypeScript, um diesen Fehler zu unterdrücken. Versuchen Sie, mit „npm install -D typescript@next“ zu aktualisieren.", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "„resolution-mode“ kann nur für reine Typenimporte festgelegt werden.", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "„resolution-mode“ ist für Typimportassertionen der einzige gültige Schlüssel.", "resolution_mode_should_be_either_require_or_import_1453": "„resolution-mode“ muss entweder auf „require“ oder „import“ festgelegt sein.", diff --git a/tsserver/es/diagnosticMessages.generated.json b/tsserver/es/diagnosticMessages.generated.json index 7ae523eb..06fd2b61 100644 --- a/tsserver/es/diagnosticMessages.generated.json +++ b/tsserver/es/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "El tipo \"this\" solo está disponible en un miembro no estático de una clase o interfaz.", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Ya hay un archivo \"tsconfig.json\" definido en: '{0}'.", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Un miembro de tupla no puede ser tanto opcional como REST.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Un tipo de tupla no se puede indizar con un valor negativo.", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "No se admite una expresión de aserción de tipo en el lado izquierdo de una expresión de exponenciación. Considere la posibilidad de incluir la expresión entre paréntesis.", "A_type_literal_property_cannot_have_an_initializer_1247": "Una propiedad de literal de tipo no puede tener un inicializador.", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Una importación solo de tipo puede especificar una importación predeterminada o enlaces con nombre, pero no ambos.", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "Agregar aserción de asignación definitiva a la propiedad \"{0}\"", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Agregar aserciones de asignación definitiva a todas las propiedades sin inicializar", "Add_export_to_make_this_file_into_a_module_95097": "Agregar \"export {}\" para transformar este archivo en un módulo", + "Add_extends_constraint_2211": "Agregar restricción \"extends\".", + "Add_extends_constraint_to_all_type_parameters_2212": "Agregar restricción \"extends\" a todos los parámetros de tipo", "Add_import_from_0_90057": "Agregar importación desde “{0}”", "Add_index_signature_for_property_0_90017": "Agregar una signatura de índice para la propiedad \"{0}\"", "Add_initializer_to_property_0_95019": "Agregar inicializador a la propiedad \"{0}\"", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parámetro de signatura de índice debe tener una anotación de tipo.", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Un tipo de parámetro de signatura de índice no puede ser un tipo literal o un tipo genérico. Considere la posibilidad de usar, en su lugar, uno de los tipos de objeto asignados.", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "El tipo de parámetro de la signatura de índice debe ser \"string\", \"number\", \"symbol\" o un tipo literal de plantilla.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Una expresión de creación de una instancia no puede ir seguida de un acceso a una propiedad.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Una interfaz solo puede extender un identificador o nombre completo con argumentos de tipo opcional.", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Una interfaz solo puede extender un tipo de objeto o una intersección de tipos de objeto con miembros conocidos estáticamente.", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "Una interfaz no puede extender un tipo primitivo como \"{0}\"; una interfaz solo puede extender tipos y clases con nombre", "An_interface_property_cannot_have_an_initializer_1246": "Una propiedad de interfaz no puede tener un inicializador.", "An_iterator_must_have_a_next_method_2489": "Un iterador debe tener un método \"next()\".", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Se necesita una pragma @jsxFrag cuando se usa una pragma @jsx con fragmentos de JSX.", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La clase \"{0}\" no implementa correctamente la clase \"{1}\". ¿Pretendía extender \"{1}\" y heredar sus miembros como una subclase?", "Class_0_incorrectly_implements_interface_1_2420": "La clase '{0}' implementa la interfaz '{1}' de forma incorrecta.", "Class_0_used_before_its_declaration_2449": "Se ha usado la clase \"{0}\" antes de declararla.", + "Class_constructor_may_not_be_a_generator_1360": "El constructor de clase no puede ser un generador.", + "Class_constructor_may_not_be_an_accessor_1341": "El constructor de clase no puede ser un descriptor de acceso.", "Class_declaration_cannot_implement_overload_list_for_0_2813": "La declaración de clase no puede implementar la lista de sobrecarga para '{0}'.", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Las declaraciones de clase no pueden tener más de una etiqueta \"@augments\" o \"@extends\".", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Los elementos Decorator de una clase no se pueden usar con un identificador privado estático. Pruebe a quitar el elemento Decorator experimental.", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "Archivo '{0}' no encontrado.", "File_Management_6245": "Administración de archivos", "File_change_detected_Starting_incremental_compilation_6032": "Se detectó un cambio de archivo. Iniciando la compilación incremental...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "El archivo es un módulo CommonJS porque “{0}” no tiene el campo “type”", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "El archivo es el módulo CommonJS porque “{0}” tiene el campo “type” cuyo valor no es “module”.", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "El archivo es un módulo CommonJS porque no se encontró “package.json”", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "El archivo es un módulo ECMAScript porque “{0}” tiene el campo “type” con el valor “module”", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "El archivo es un módulo CommonJS; se puede convertir en un módulo ES.", "File_is_default_library_for_target_specified_here_1426": "El archivo es la biblioteca predeterminada para el destino que se especifica aquí.", "File_is_entry_point_of_type_library_specified_here_1419": "El archivo es el punto de entrada de la biblioteca de tipos que se especifica aquí.", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Se esperaba un identificador. \"{0}\" es una palabra reservada que no se puede usar aquí.", "Identifier_expected_1003": "Se esperaba un identificador.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificador esperado. \"__esModule\" está reservado como marcador exportado al transformar módulos ECMAScript.", + "Identifier_or_string_literal_expected_1478": "Se esperaba un literal de cadena o identificador", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Si el paquete \"{0}\" expone realmente este módulo, considere la posibilidad de enviar una solicitud de incorporación de cambios para corregir \"https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}\".", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Si el paquete '{0}' realmente expone este módulo, intente agregar un nuevo archivo de declaración (.d.ts) que contenga 'declarar módulo '{1}';`", "Ignore_this_error_message_90019": "Ignorar este mensaje de error", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "El especificador de importación no válido \"{0}\" no tiene resoluciones posibles.", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nombre de módulo no válido en el aumento. El módulo '{0}' se resuelve como un módulo sin tipo en '{1}', que no se puede aumentar.", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nombre de módulo no válido en un aumento, no se encuentra el módulo '{0}'.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Cadena opcional no válida de la nueva expresión. ¿Quería llamar a \"{0}()\"?", "Invalid_reference_directive_syntax_1084": "Sintaxis de la directiva \"reference\" no válida.", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Uso no válido de '{0}'. No se puede usar dentro de un bloque estático de clase.", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso de '{0}' no válido. Los módulos están en modo strict automáticamente.", @@ -893,6 +906,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_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.", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "El miembro \"{0}\" tiene un tipo \"{1}\" de forma implícita, pero se puede inferir un tipo más adecuado a partir del uso.", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "El proyecto \"{0}\" no puede generarse porque su dependencia \"{1}\" tiene errores", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "El proyecto \"{0}\" no puede compilarse porque su dependencia \"{1}\" no se ha compilado.", "Project_0_is_being_forcibly_rebuilt_6388": "El proyecto \"{0}\" se está recompilando de manera forzada.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "El proyecto \"{0}\" no está actualizado porque el archivo buildinfo \"{1}\" indica que algunos de los cambios no se emitieron", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "El proyecto \"{0}\" está obsoleto porque su dependencia \"{1}\" no está actualizada", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "El proyecto \"{0}\" está obsoleto porque la salida más antigua \"{1}\" es anterior a la entrada más reciente \"{2}\"", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "El proyecto \"{0}\" está obsoleto porque la salida \"{1}\" es anterior a la entrada \"{2}\"", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "El proyecto \"{0}\" está obsoleto porque el archivo de salida \"{1}\" no existe", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "El proyecto \"{0}\" está obsoleto porque su salida se generó con la versión \"{1}\", que es distinta a la versión actual \"{2}\".", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "El proyecto \"{0}\" está obsoleto porque la salida de su dependencia \"{1}\" ha cambiado.", "Project_0_is_up_to_date_6361": "El proyecto \"{0}\" está actualizado", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "El proyecto \"{0}\" está actualizado porque la entrada más reciente \"{1}\" es anterior a la salida más antigua \"{2}\"", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "El proyecto \"{0}\" está actualizado porque la entrada más reciente \"{1}\" es anterior a la salida \"{2}\"", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "El proyecto \"{0}\" está actualizado, pero debe actualizar las marcas de tiempo de los archivos de salida anteriores a los archivos de entrada", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "El proyecto \"{0}\" está actualizado con archivos .d.ts de sus dependencias", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Las referencias del proyecto no pueden formar un gráfico circular. Ciclo detectado: {0}", "Projects_6255": "Proyectos", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Los parámetros de tipo requeridos pueden no seguir parámetros de tipo opcionales.", "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}\".", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Los modos de resolución solo se admiten cuando \"moduleResolution\" es \"node16\" o \"nodenext\".", "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_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}'.", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "El modificador 'tipo' no se puede usar en una exportación con nombre cuando se usa 'exportar tipo' en su instrucción exportar.", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "El modificador 'tipo' no se puede usar en una importación con nombre cuando se usa 'exportar tipo' en su instrucción importar.", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "El tipo de una declaración de función debe coincidir con la signatura de la función.", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "No se puede nombrar el tipo de esta expresión sin una aserción \"modo de resolución\", que es una característica inestable. Use TypeScript nocturno para silenciar este error. Intente actualizar con \"npm install -D typescript@next\".", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "No se ha podido serializar el tipo de este nodo porque su propiedad '{0}' no se puede serializar.", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "El tipo devuelto por el método \"{0}()\" de un iterador de asincronía debe ser una promesa para un tipo con una propiedad \"value\".", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "El tipo devuelto por el método \"{0}()\" de un iterador debe tener una propiedad \"value\".", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "No se admite la instrucción 'with'. Todos los símbolos de un bloque 'with' tendrán el tipo 'any'.", "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_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_0_since_the_types_1_and_2_have_no_overlap_2367": "Esta condición siempre devolverá \"{0}\", porque los tipos \"{1}\" y \"{2}\" no se superponen.", "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?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere un asistente importado, pero no se puede encontrar el módulo \"{0}\".", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Esta sintaxis requiere una aplicación auxiliar importada denominada \"{1}\", que no existe en \"{0}\". Considere la posibilidad de actualizar la versión de \"{0}\".", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Esta sintaxis requiere un asistente importado denominado \"{1}\" con parámetros de {2}, que no es compatible con el de \"{0}\". Pruebe a actualizar la versión de \"{0}\".", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Este parámetro de tipo podría necesitar una restricción \"extends {0}\".", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Este uso de \"import\" no es válido. Se pueden escribir llamadas \"import()\", pero deben tener paréntesis y no pueden tener argumentos de tipo.", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Las expresiones \"await\" de nivel superior solo se permiten cuando la opción \"módulo\" está establecida en \"es2022\", \"esnext\", \"system\", \"node16\" o \"nodenext\", y la opción \"destino\" está establecida en \"es2017\" o superior.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Las declaraciones de nivel superior de los archivos .d.ts deben comenzar con un modificador \"declare\" o \"export\".", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Biblioteca de tipos a la que se hace referencia mediante \"{0}\" desde el archivo \"{1}\" con el valor packageId \"{2}\"", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "El tipo de operando \"await\" debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "El tipo de valor de la propiedad calculada es \"{0}\", que no se puede asignar al tipo \"{1}\".", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "El tipo de variable miembro de instancia \"{0}\" no puede hacer referencia al identificador \"{1}\" declarado en el constructor.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "El tipo de elementos iterados de un operando \"yield*\" debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "El tipo de propiedad \"{0}\" hace referencia circular a sí misma en el tipo asignado \"{1}\".", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "El tipo de operando \"yield\" en un generador asincrónico debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== No se resolvió la directiva de referencia de tipo '{0}'. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La directiva de referencia de tipo '{0}' se resolvió correctamente como '{1}', principal: {2}. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== La directiva de referencia de tipo \"{0}\" se resolvió correctamente como \"{1}\" con el identificador de paquete \"{2}\", principal: {3}. ========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Los tipos no pueden aparecer en declaraciones de exportación en archivos JavaScript.", "Types_have_separate_declarations_of_a_private_property_0_2442": "Los tipos tienen declaraciones independientes de una propiedad '{0}' privada.", "Types_of_construct_signatures_are_incompatible_2419": "Los tipos de signaturas de construcción son incompatibles.", "Types_of_parameters_0_and_1_are_incompatible_2328": "Los tipos de parámetros '{0}' y '{1}' no son compatibles.", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "Modos de compilación e inspección", "Watch_input_files_6005": "Inspeccionar archivos de entrada.", "Watch_option_0_requires_a_value_of_type_1_5080": "La opción \"{0}\" de inspección requiere un valor de tipo {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Solo se puede escribir un tipo para '{0}' agregando aquí un tipo para todo el parámetro.", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Al asignar funciones, compruebe que efectivamente los parámetros y los valores devueltos son compatibles con el subtipo.", "When_type_checking_take_into_account_null_and_undefined_6699": "Al comprobar tipos, tenga en cuenta \"null\" y \"undefined\".", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Si se debe mantener la salida de la consola no actualizada en el modo de inspección en lugar de borrar la pantalla.", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Encapsular el cuerpo siguiente entre paréntesis, lo cual debe ser un literal de objeto", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Puede obtener información sobre todas las opciones del compilador en {0}", "You_cannot_rename_a_module_via_a_global_import_8031": "No se puede cambiar el nombre de un módulo mediante una importación global.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "No se puede cambiar el nombre de los elementos definidos en una carpeta 'node_modules'.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "No se puede cambiar el nombre de los elementos definidos en otra carpeta 'node_modules'.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "No se puede cambiar el nombre de elementos definidos en la biblioteca TypeScript estándar.", "You_cannot_rename_this_element_8000": "No se puede cambiar el nombre a este elemento.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" no acepta suficientes argumentos para utilizarse como decorador aquí. ¿Pretendía llamar primero y escribir \"@{0}()\"?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "Las signaturas de índice \"{0}\" no son compatibles.", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "El tipo de índice \"{0}\"' \"{1}\" no se puede asignar al tipo de índice \"{2}\" \"{3}\".", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' es un elemento primitivo, pero '{1}' es un objeto contenedor. Use '{0}' preferentemente cuando sea posible.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' es un tipo y no se puede importar en archivos JavaScript. Use '{1}' en una anotación de tipo JSDoc.", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "\"{0}\" es un tipo y debe importarse mediante una importación de solo tipo cuando \"preserveValueImports\" y \"isolatedModules\" estén habilitados.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}' es un cambio de nombre de '{1}' sin usar. ¿Quería usarlo como una anotación de tipo?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "\"{0}\" puede asignarse a la restricción de tipo \"{1}\", pero no se pudo crear una instancia de \"{1}\" con un subtipo distinto de la restricción \"{2}\".", + "_0_is_automatically_exported_here_18044": "'{0}' se exporta automáticamente aquí.", "_0_is_declared_but_its_value_is_never_read_6133": "Se declara \"{0}\", pero su valor no se lee nunca.", "_0_is_declared_but_never_used_6196": "\"{0}\" se declara pero nunca se utiliza.", "_0_is_declared_here_2728": "\"{0}\" se declara aquí.", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "uno de:", "one_or_more_Colon_6901": "uno o más:", "options_6024": "Opciones", + "or_JSX_element_expected_1145": "Se esperaba \"{\" o un elemento JSX.", "or_expected_1144": "Se esperaba \"{\" o \";\".", "package_json_does_not_have_a_0_field_6100": "\"package.json\" no tiene un campo \"{0}\".", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "El archivo \"package.json\" no tiene ninguna entrada \"typesVersions\" que coincida con la versión \"{0}\".", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "El modificador 'readonly' solo puede aparecer en una declaración de propiedad o una signatura de índice.", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "El modificador de tipo \"readonly\" solo se permite en los tipos literales de matriz y de tupla.", "require_call_may_be_converted_to_an_import_80005": "La llamada a \"require\" puede convertirse en una importación.", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Las aserciones \"modo de resolución\" solo se admiten cuando \"moduleResolution\" es \"node16\" o \"nodenext\".", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "Las aserciones \"modo de resolución\" son inestables. Use TypeScript nocturno para silenciar este error. Intente actualizar con \"npm install -D typescript@next\".", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "\"resolution-mode\" solo se puede establecer para importaciones solamente de tipo.", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "\"resolution-mode\" es la única clave válida para las aserciones de importación de tipos.", "resolution_mode_should_be_either_require_or_import_1453": "\"modo de resolución\" debe ser \"requerir\" o \"importar\".", diff --git a/tsserver/fr/diagnosticMessages.generated.json b/tsserver/fr/diagnosticMessages.generated.json index e515dfab..632cac15 100644 --- a/tsserver/fr/diagnosticMessages.generated.json +++ b/tsserver/fr/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Un type 'this' est disponible uniquement dans un membre non statique d'une classe ou d'une interface.", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Un fichier 'tsconfig.json' est déjà défini à l'emplacement '{0}'.", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Un membre de tuple ne peut pas être à la fois facultatif et rest.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Un type tuple ne peut pas être indexé avec une valeur négative.", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Une expression d'assertion de type n'est pas autorisée dans la partie gauche d'une expression d'élévation à une puissance. Mettez l'expression entre parenthèses.", "A_type_literal_property_cannot_have_an_initializer_1247": "Une propriété de littéral de type ne peut pas avoir d'initialiseur.", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Une importation de type uniquement peut spécifier une importation par défaut ou des liaisons nommées, mais pas les deux.", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "Ajouter une assertion d'assignation définie à la propriété '{0}'", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Ajouter des assertions d'affectation définie à toutes les propriétés non initialisées", "Add_export_to_make_this_file_into_a_module_95097": "Ajouter 'export {}' pour faire de ce fichier un module", + "Add_extends_constraint_2211": "Ajoutez la contrainte « extends ».", + "Add_extends_constraint_to_all_type_parameters_2212": "Ajouter la contrainte « extends » à tous les paramètres de type", "Add_import_from_0_90057": "Ajouter l'importation de \"{0}\"", "Add_index_signature_for_property_0_90017": "Ajouter une signature d'index pour la propriété '{0}'", "Add_initializer_to_property_0_95019": "Ajouter un initialiseur à la propriété '{0}'", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un paramètre de signature d'index doit avoir une annotation de type.", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Un type de paramètre de signature d’index ne peut pas être un type littéral ni générique. Envisagez plutôt d’utiliser un type d’objet mappé.", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Un type de paramètre de signature d’index doit être « string », « number », « symbol » ou un type littéral de modèle.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Une expression d’instanciation ne peut pas être suivie d’un accès à la propriété.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Une interface peut uniquement étendre un identificateur/nom qualifié avec des arguments de type facultatifs.", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Une interface peut étendre uniquement un type d'objet ou une intersection de types d'objet avec des membres connus de manière statique.", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "Une interface ne peut pas étendre un type primitif comme « {0} » ; une interface peut uniquement étendre des types nommés et des classes.", "An_interface_property_cannot_have_an_initializer_1246": "Une propriété d'interface ne peut pas avoir d'initialiseur.", "An_iterator_must_have_a_next_method_2489": "Un itérateur doit comporter une méthode 'next()'.", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Un pragma @jsxFrag est nécessaire quand un pragma @jsx est utilisé avec des fragments JSX.", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La classe '{0}' implémente de manière incorrecte la classe '{1}'. Voulez-vous vraiment étendre '{1}' et hériter de ses membres en tant que sous-classe ?", "Class_0_incorrectly_implements_interface_1_2420": "La classe '{0}' implémente de manière incorrecte l'interface '{1}'.", "Class_0_used_before_its_declaration_2449": "Classe '{0}' utilisée avant sa déclaration.", + "Class_constructor_may_not_be_a_generator_1360": "Le constructeur de classe ne peut pas être un générateur.", + "Class_constructor_may_not_be_an_accessor_1341": "Le constructeur de la classe ne peut pas être un accesseur.", "Class_declaration_cannot_implement_overload_list_for_0_2813": "La déclaration de classe ne peut pas implémenter la liste de surcharge pour «{0}».", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Les déclarations de classes ne peuvent pas avoir plusieurs balises '@augments' ou '@extends'.", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Impossible d'utiliser des éléments décoratifs de classe avec un identificateur privé static. Supprimez l'élément décoratif expérimental.", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "Fichier '{0}' introuvable.", "File_Management_6245": "Gestion de fichiers", "File_change_detected_Starting_incremental_compilation_6032": "Modification de fichier détectée. Démarrage de la compilation incrémentielle...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "Le fichier est un module CommonJS, car « {0} » n’a pas de champ « type »", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "Le fichier est un module CommonJS, car « {0} » a un champ « type » dont la valeur n’est pas « module »", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "Le fichier est un module CommonJS, car « package.json » est introuvable", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "Le fichier est un module ECMAScript, car « {0} » a un champ « type » avec la valeur « module »", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Le fichier est un module CommonJS ; il peut être converti en module ES.", "File_is_default_library_for_target_specified_here_1426": "Le fichier représente la bibliothèque par défaut de la cible spécifiée ici.", "File_is_entry_point_of_type_library_specified_here_1419": "Le fichier représente le point d'entrée de la bibliothèque de types spécifiée ici.", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Identificateur attendu. '{0}' est un mot réservé qui ne peut pas être utilisé ici.", "Identifier_expected_1003": "Identificateur attendu.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificateur attendu. '__esModule' est réservé en tant que marqueur exporté durant la transformation des modules ECMAScript.", + "Identifier_or_string_literal_expected_1478": "Identificateur ou littéral de chaîne attendu", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Si le package '{0}' expose réellement ce module, envoyez une demande de tirage (pull request) pour modifier 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Si le package' {0} 'expose effectivement ce module, essayez d’ajouter un nouveau fichier de déclaration (. d. TS) contenant’declare module' {1} '; '", "Ignore_this_error_message_90019": "Ignorer ce message d'erreur", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "Le spécificateur d’importation non valide « {0} » n’a aucune résolution possible.", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nom de module non valide dans l'augmentation. Le module '{0}' est résolu en module non typé à l'emplacement '{1}', ce qui empêche toute augmentation.", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nom de module non valide dans l'augmentation. Le module '{0}' est introuvable.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Chaîne facultative non valide à partir de la nouvelle expression. Voulez-vous appeler '{0}()' ?", "Invalid_reference_directive_syntax_1084": "Syntaxe de directive 'reference' non valide.", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Utilisation non valide de « {0} ». Il ne peut pas être utilisé à l’intérieur d’un bloc statique de classe.", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Utilisation non valide de '{0}'. Les modules sont automatiquement en mode strict.", @@ -893,6 +906,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_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}'.", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "Le membre '{0}' a implicitement un type '{1}', mais il est possible de déduire un meilleur type à partir de l'utilisation.", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Impossible de générer le projet '{0}' car sa dépendance '{1}' comporte des erreurs", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Impossible de générer le projet '{0}', car sa dépendance '{1}' n'a pas été générée", "Project_0_is_being_forcibly_rebuilt_6388": "Le projet « {0} » est en cours de régénération forcée", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "Le projet « {0} » est obsolète, car le fichier buildinfo « {1} » indique que certaines modifications n’ont pas été émises", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Le projet '{0}' est obsolète car sa dépendance '{1}' est obsolète", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Le projet '{0}' est obsolète car la sortie la plus ancienne ('{1}') est antérieure à l'entrée la plus récente '{2}'", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "Le projet '{0}' est obsolète car la sortie (« {1} ») est antérieure à l'entrée « {2} »", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Le projet '{0}' est obsolète car le fichier de sortie '{1}' n'existe pas", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "Le projet '{0}' est obsolète, car sa sortie a été générée avec la version '{1}', qui diffère de la version actuelle '{2}'", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "Le projet '{0}' est obsolète, car la sortie de sa dépendance '{1}' a changé", "Project_0_is_up_to_date_6361": "Le projet '{0}' est à jour", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Le projet '{0}' est à jour car l'entrée la plus récente ('{1}') est antérieure à la sortie la plus ancienne ('{2}')", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "Le projet « {0} » est à jour car l'entrée la plus récente (« {1} ») est antérieure à la sortie (« {2} »)", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "Project « {0} » est à jour, mais doit mettre à jour les horodatages des fichiers de sortie plus anciens que les fichiers d’entrée", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Le projet '{0}' est à jour avec les fichiers .d.ts de ses dépendances", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Les références de projet ne peuvent pas former un graphe circulaire. Cycle détecté : {0}", "Projects_6255": "Projets", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Les paramètres de type obligatoires ne peuvent pas être placés à la suite des paramètres de type optionnels.", "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}'.", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Les modes de résolution sont pris en charge uniquement lorsque 'moduleResolution' est 'node16' ou 'nodenext'.", "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_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}'.", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Le ’type’ de modificateur ne peut pas être utilisé sur une importation nommée quand le ’type’ d’exportation est utilisé dans son instruction import.", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "Le ’type’ de modificateur ne peut pas être utilisé sur une importation nommée quand le ’type’ d’importation est utilisé dans son instruction import.", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "Le type d'une déclaration de fonction doit correspondre à la signature de la fonction.", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "Le type de cette expression ne peut pas être nommé sans une assertion de « mode résolution », qui est une fonctionnalité instable. Utilisez TypeScript nocturne pour désactiver cette erreur. Essayez de mettre à jour avec « npm install -D typescript@next ».", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "Impossible de sérialiser le type de ce nœud, car sa propriété «{0}» ne peut pas être sérialisée.", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Le type retourné par la méthode '{0}()' d'un itérateur asynchrone doit être une promesse pour un type ayant une propriété 'value'.", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Le type retourné par la méthode '{0}()' d'un itérateur doit avoir une propriété 'value'.", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "L'instruction 'with' n'est pas prise en charge. Tous les symboles d'un bloc 'with' ont le type 'any'.", "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_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_0_since_the_types_1_and_2_have_no_overlap_2367": "Cette condition retourne toujours '{0}', car les types '{1}' et '{2}' n'ont pas de chevauchement.", "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 ?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Cette syntaxe nécessite une application d'assistance importée, mais le module '{0}' est introuvable.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Cette syntaxe nécessite une assistance importée nommée '{1}' mais qui n'existe pas dans '{0}'. Effectuez une mise à niveau de votre version de '{0}'.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Cette syntaxe nécessite un composant d'assistance importé nommé '{1}' avec {2} paramètres, ce qui n'est pas compatible avec celui qui se trouve dans '{0}'. Effectuez une mise à niveau de votre version de '{0}'.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Ce paramètre de type nécessite peut-être une contrainte « extends {0}».", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Cette utilisation de « import » n’est pas valide. Les appels « import() » peuvent être écrits, mais ils doivent avoir des parenthèses et ne peuvent pas avoir d’arguments de type.", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Les expressions 'await' de niveau supérieur sont autorisées uniquement lorsque l’option 'module' a la valeur 'es2022', 'esnext', 'system', 'node16' ou 'nodenext' et que l’option 'target' a la valeur 'es2017' ou une valeur supérieure.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Les déclarations de niveau supérieur dans les fichiers .d.ts doivent commencer par un modificateur 'declare' ou 'export'.", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Bibliothèque de types référencée via '{0}' à partir du fichier '{1}' ayant le packageId '{2}'", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Le type d'un opérande 'await' doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Le type de la valeur de la propriété calculée est '{0}'. Il ne peut pas être assigné au type '{1}'.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "Le type de variable membre d’instance '{0}' ne peut pas référencer l’identificateur '{1}' déclaré dans le constructeur.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Le type des éléments itérés d'un opérande 'yield*' doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Le type de la propriété '{0}' se référence de façon circulaire dans le type mappé '{1}'.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Le type d'un opérande 'yield' dans un générateur asynchrone doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== La directive de référence de type '{0}' n'a pas été résolue. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La directive de référence de type '{0}' a été correctement résolue en '{1}', primaire : {2}. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== La directive de référence de type '{0}' a été correctement résolue en '{1}' avec l'ID de package '{2}', primaire : {3}. ========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Les types ne peuvent pas apparaître dans les déclarations d’exportation dans les fichiers JavaScript.", "Types_have_separate_declarations_of_a_private_property_0_2442": "Les types ont des déclarations distinctes d'une propriété privée '{0}'.", "Types_of_construct_signatures_are_incompatible_2419": "Les types de signature de construction sont incompatibles.", "Types_of_parameters_0_and_1_are_incompatible_2328": "Les types des paramètres '{0}' et '{1}' sont incompatibles.", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "Modes d’Observation et de Génération", "Watch_input_files_6005": "Fichiers d'entrée d'espion.", "Watch_option_0_requires_a_value_of_type_1_5080": "L'option de surveillance '{0}' nécessite une valeur de type {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Nous ne pouvons écrire un type pour « {0} » qu’en ajoutant un type pour l’ensemble du paramètre ici.", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Lors de l’attribution de fonctions, vérifiez que les paramètres et les valeurs de retour sont compatibles avec le sous-type.", "When_type_checking_take_into_account_null_and_undefined_6699": "Lors de la vérification de type, prenez en compte « null » et « undefined ».", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Garder la sortie de console obsolète en mode espion au lieu d'effacer l'écran.", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Placer le corps suivant entre parenthèses pour indiquer qu'il s'agit d'un littéral d'objet", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Vous pouvez en savoir plus sur toutes les options du compilateur sur {0}", "You_cannot_rename_a_module_via_a_global_import_8031": "Vous ne pouvez pas renommer un module via une importation globale.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Vous ne pouvez pas renommer les éléments définis dans un dossier « node_modules ».", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Vous ne pouvez pas renommer les éléments définis dans un autre dossier « node_modules ».", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Vous ne pouvez pas renommer des éléments définis dans la bibliothèque TypeScript standard.", "You_cannot_rename_this_element_8000": "Vous ne pouvez pas renommer cet élément.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accepte trop peu d'arguments pour pouvoir être utilisé ici en tant qu'élément décoratif. Voulez-vous vraiment l'appeler d'abord et écrire '@{0}()' ?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "Les signatures d'index « {0} » sont incompatibles.", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "Le type d’index « {0} », « {1} », ne peut pas être attribué au type d’index « {2} », « {3} ».", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' est une primitive, mais '{1}' est un objet wrapper. Si possible, utilisez '{0}' de préférence.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' est un type qui ne peut pas être importé dans des fichiers JavaScript. Utilisez '{1}' dans une annotation de type JSDoc.", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "« {0} » est un type seul et doit être importé à l'aide d'une importation de type seul lorsque « preserveValueImports » et « isolatedModules » sont tous deux activés.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "« {0} » est un changement de nom inutilisé de « {1} ». Souhaitiez-vous l’utiliser comme annotation de type?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}' peut être assigné à la contrainte de type '{1}', mais '{1}' a pu être instancié avec un autre sous-type de contrainte '{2}'.", + "_0_is_automatically_exported_here_18044": "'{0}' est automatiquement exporté ici.", "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' est déclaré mais sa valeur n'est jamais lue.", "_0_is_declared_but_never_used_6196": "'{0}' est déclaré mais n'est jamais utilisé.", "_0_is_declared_here_2728": "'{0}' est déclaré ici.", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "L'un de :", "one_or_more_Colon_6901": "un ou plusieurs :", "options_6024": "options", + "or_JSX_element_expected_1145": "'{' ou élément JSX attendu.", "or_expected_1144": "'{' ou ';' attendu.", "package_json_does_not_have_a_0_field_6100": "'package.json' n'a aucun champ '{0}'.", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json' n'a aucune entrée 'typesVersions' qui correspond à la version '{0}'.", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Le modificateur 'readonly' peut apparaître uniquement dans une déclaration de propriété ou une signature d'index.", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "Le modificateur de type 'readonly' est uniquement autorisé sur les types littéraux de tableau et de tuple.", "require_call_may_be_converted_to_an_import_80005": "L'appel de 'require' peut être converti en import.", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Les assertions 'resolution-mode' sont prises en charge uniquement quand 'moduleResolution' est 'node16' ou 'nodenext'.", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "Les assertions 'resolution-mode' sont instables. Utilisez TypeScript nocturne pour désactiver cette erreur. Essayez de mettre à jour avec « npm install -D typescript@next ».", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "« mode résolution » ne peut être défini que pour les importations de type uniquement.", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "« mode résolution » est la seule clé valide pour les assertions d’importation de type.", "resolution_mode_should_be_either_require_or_import_1453": "'resolution-mode' doit être 'require' ou 'import'.", diff --git a/tsserver/it/diagnosticMessages.generated.json b/tsserver/it/diagnosticMessages.generated.json index 1535b015..dff39262 100644 --- a/tsserver/it/diagnosticMessages.generated.json +++ b/tsserver/it/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Un tipo 'this' è disponibile solo in un membro non statico di una classe o di interfaccia.", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Un file 'tsconfig.json' è già definito in: '{0}'.", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Un membro di tupla non può essere sia facoltativo che inattivo.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Un tipo di tupla non può essere indicizzato con un valore negativo.", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Nella parte sinistra di un'espressione di elevamento a potenza non è consentita un'espressione di asserzione tipi. Provare a racchiudere l'espressione tra parentesi.", "A_type_literal_property_cannot_have_an_initializer_1247": "Una proprietà di valore letterale di tipo non può contenere un inizializzatore.", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Un'importazione solo di tipi può specificare un'importazione predefinita o binding denominati, ma non entrambi.", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "Aggiungere l'asserzione di assegnazione definita alla proprietà '{0}'", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Aggiungere le asserzioni di assegnazione definite a tutte le proprietà non inizializzate", "Add_export_to_make_this_file_into_a_module_95097": "Aggiungere 'export {}' per trasformare questo file in un modulo", + "Add_extends_constraint_2211": "Aggiungere il vincolo 'extends'.", + "Add_extends_constraint_to_all_type_parameters_2212": "Aggiungere il vincolo `extends` a tutti i parametri di tipo", "Add_import_from_0_90057": "Aggiungere l'importazione da \"{0}\"", "Add_index_signature_for_property_0_90017": "Aggiungere la firma dell'indice per la proprietà '{0}'", "Add_initializer_to_property_0_95019": "Aggiungere l'inizializzatore alla proprietà '{0}'", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parametro della firma dell'indice deve contenere un'annotazione di tipo.", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Un tipo di parametro della firma dell'indice non può essere un tipo di valore letterale o un tipo generico. Considerare l'utilizzo di un tipo di oggetto con mapping.", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Un tipo di parametro della firma dell'indice deve essere 'stringa', 'numero', 'simbolo' o un tipo di valore letterale del modello.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Un'espressione di creazione di un'istanza non può essere seguita da un accesso a proprietà.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Un'interfaccia può estendere solo un identificatore/nome qualificato con argomenti tipo facoltativi.", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Un'interfaccia può estendere solo un tipo di oggetto o un'intersezione di tipi di oggetto con membri noti in modo statico.", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "Un'interfaccia non può estendere un tipo primitivo come '{0}'; un'interfaccia può estendere solo tipi e classi denominati", "An_interface_property_cannot_have_an_initializer_1246": "Una proprietà di interfaccia non può contenere un inizializzatore.", "An_iterator_must_have_a_next_method_2489": "Un iteratore deve contenere un metodo 'next()'.", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Quando si usa un'istruzione @jsx con frammenti JSX, è necessaria un'istruzione pragma @jsxFrag.", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La classe '{0}' implementa in modo errato la classe '{1}'. Si intendeva estendere '{1}' ed ereditarne i membri come sottoclasse?", "Class_0_incorrectly_implements_interface_1_2420": "La classe '{0}' implementa in modo errato l'interfaccia '{1}'.", "Class_0_used_before_its_declaration_2449": "La classe '{0}' è stata usata prima di essere stata dichiarata.", + "Class_constructor_may_not_be_a_generator_1360": "Il costruttore di classe non può essere un generatore.", + "Class_constructor_may_not_be_an_accessor_1341": "Il costruttore di classe non può essere una funzione di accesso.", "Class_declaration_cannot_implement_overload_list_for_0_2813": "La dichiarazione classe non può implementare l'elenco di overload per '{0}'.", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Le dichiarazioni di classe non possono contenere più di un tag '@augments' o '@extends'.", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Non è possibile elementi Decorator di classe con l'identificatore privato statico. Provare a rimuovere l'elemento Decorator sperimentale.", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "Il file '{0}' non è stato trovato.", "File_Management_6245": "Gestione dei file", "File_change_detected_Starting_incremental_compilation_6032": "È stata rilevata una modifica ai file. Verrà avviata la compilazione incrementale...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "Il file è un modulo CommonJS perché '{0}' non contiene il campo \"type\"", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "Il file è un modulo CommonJS perché '{0}' contiene il campo \"type\" il cui valore non è \"module\"", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "Il file è un modulo CommonJS perché 'package.json' non è stato trovato", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "Il file è un modulo ECMAScript perché '{0}' contiene il campo \"type\" con valore \"module\"", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Il file è un modulo CommonJS e può essere convertito in un modulo ES6.", "File_is_default_library_for_target_specified_here_1426": "Il file è la libreria predefinita per la destinazione specificata in questo punto.", "File_is_entry_point_of_type_library_specified_here_1419": "Il file è il punto di ingresso della libreria dei tipi specificata in questo punto.", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "È previsto un identificatore. '{0}' è una parola riservata che non può essere usata in questo punto.", "Identifier_expected_1003": "È previsto l'identificatore.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "È previsto un identificatore. '__esModule' è riservato come marcatore esportato durante la trasformazione di moduli ECMAScript.", + "Identifier_or_string_literal_expected_1478": "Previsto identificatore o valore letterale stringa.", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Se il pacchetto '{0}' espone effettivamente questo modulo, provare a inviare una richiesta pull per modificare 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Se il pacchetto ' {0}' espone effettivamente il modulo, provare ad aggiungere un nuovo file di dichiarazione (.d.ts) contenente ' Dichiara modulo' {1}';'", "Ignore_this_error_message_90019": "Ignorare questo messaggio di errore", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "L'identificatore di importazione non è valido ' {0}' non contiene risoluzioni possibili.", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Il nome di modulo nell'aumento non è valido. Il modulo '{0}' viene risolto in un modulo non tipizzato in '{1}', che non può essere aumentato.", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Il nome di modulo nell'aumento non è valido. Il modulo '{0}' non è stato trovato.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Catena facoltativa non valida dalla nuova espressione. Si intendeva chiamare '{0}()'?", "Invalid_reference_directive_syntax_1084": "La sintassi della direttiva 'reference' non è valida.", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Uso non valido di '{0}'. Non può essere usato all'interno di un blocco statico di classe.", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso non valido di '{0}'. I moduli vengono impostati automaticamente in modalità strict.", @@ -893,6 +906,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_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}'.", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "Il membro '{0}' include implicitamente un tipo '{1}', ma è possibile dedurre un tipo migliore dall'utilizzo.", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Non è possibile compilare il progetto '{0}' perché la dipendenza '{1}' contiene errori", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Non è possibile compilare il progetto '{0}' perché la relativa dipendenza '{1}' non è stata compilata", "Project_0_is_being_forcibly_rebuilt_6388": "Il progetto '{0}' è stato ricompilato forzatamente", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "Il '{0}' del progetto non è aggiornato perché il file buildinfo '{1}' indica che alcune modifiche non sono state generate", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Il progetto '{0}' non è aggiornato perché la dipendenza '{1}' non è aggiornata", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Il progetto '{0}' non è aggiornato perché l'output meno recente '{1}' è meno recente dell'input più recente '{2}'", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "Il progetto '{0}' non è aggiornato perché l'output '{1}' è meno recente dell'input '{2}'", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Il progetto '{0}' non è aggiornato perché il file di output '{1}' non esiste", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "Il progetto '{0}' non è aggiornato perché l'output per il progetto è stato generato con la versione '{1}' che non corrisponde alla versione corrente '{2}'", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "Il progetto '{0}' non è aggiornato perché l'output della relativa dipendenza '{1}' è cambiato", "Project_0_is_up_to_date_6361": "Il progetto '{0}' è aggiornato", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Il progetto '{0}' è aggiornato perché l'input più recente '{1}' è meno recente dell'output meno recente '{2}'", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "Il progetto '{0}' è aggiornato perché l'input più recente '{1}' è meno recente dell'output '{2}'", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "Project '{0}' è aggiornato ma deve aggiornare i timestamp dei file di output precedenti ai file di input", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Il progetto '{0}' è aggiornato con i file con estensione d.ts delle relative dipendenze", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "I riferimenti al progetto non possono formare un grafico circolare. Ciclo rilevato: {0}", "Projects_6255": "Progetti", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "I parametri di tipo obbligatori potrebbero non seguire i parametri di tipo facoltativi.", "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}'.", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Le modalità di risoluzione sono supportate solo quando 'moduleResolution' è 'node16' o 'nodenext'.", "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_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}'.", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Impossibile utilizzare il modificatore 'tipo' in un'esportazione denominata quando 'tipo di esportazione' viene usato nell'istruzione di esportazione.", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "Impossibile utilizzare il modificatore 'tipo' in un'importazione denominata quando 'tipo di importazione' viene usato nella relativa istruzione di importazione.", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "Il tipo di una dichiarazione di funzione deve corrispondere alla firma della funzione.", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "Impossibile assegnare un nome al tipo di questa espressione senza un'asserzione 'resolution-mode', che è una funzionalità instabile. Usare TypeScript notturno per disattivare l'errore. Provare ad aggiornare con 'npm install -D typescript@next'.", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "Impossibile serializzare questo tipo di nodo perché la sua proprietà '{0}' non può essere serializzata.", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Il tipo restituito dal metodo '{0}()' di un iteratore asincrono deve essere una promessa per un tipo con una proprietà 'value'.", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Il tipo restituito dal metodo '{0}()' di un iteratore deve contenere una proprietà 'value'.", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "L'istruzione 'with' non è supportata. Il tipo di tutti i simboli in un blocco 'with' è 'any'.", "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_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_0_since_the_types_1_and_2_have_no_overlap_2367": "Questa condizione restituirà sempre '{0}' perché i tipi '{1}' e '{2}' non presentano alcuna sovrapposizione.", "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?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Con questa sintassi è richiesto un helper importato, ma il modulo '{0}' non è stato trovato.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Con questa sintassi è richiesto un helper importato denominato '{1}', che non esiste in '{0}'. Provare ad aggiornare la versione di '{0}'.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Con questa sintassi è richiesto un helper importato denominato '{1}' con {2} parametri, che non è compatibile con quello presente in '{0}'. Provare ad aggiornare la versione di '{0}'.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Questo parametro di tipo potrebbe richiedere un vincolo `extends {0}`.", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Questo uso di 'import' non è valido. le chiamate 'import()' possono essere scritte, ma devono avere parentesi e non possono avere argomenti di tipo.", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Le espressioni 'await' di primo livello sono consentite solo quando l'opzione 'module' è impostata su 'es2022', 'esnext', 'system', 'node16', or 'nodenext', e l'opzione 'target' è impostata su 'es2017' o versione successiva.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Le dichiarazioni di primo livello nei file con estensione d.ts devono iniziare con un modificatore 'declare' o 'export'.", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Libreria dei tipi a cui viene fatto riferimento tramite '{0}' dal file '{1}' con packageId '{2}'", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Il tipo dell'operando 'await' deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Il tipo del valore della proprietà calcolata è '{0}', che non è assegnabile al tipo '{1}'.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "Il tipo di variabile del membro di istanza '{0}' non può fare riferimento all'identificatore '{1}' dichiarato nel costruttore.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Il tipo di elementi iterati di un operando 'yield*' deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Il tipo di proprietà '{0}' contiene un riferimento circolare a se stesso nel tipo con mapping '{1}'.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Il tipo dell'operando 'yield' in un generatore asincrono deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== La direttiva '{0}' del riferimento al tipo non è stata risolta. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== La direttiva '{0}' del riferimento al tipo è stata risolta in '{1}'. Primaria: {2}. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== La direttiva '{0}' del riferimento al tipo è stata risolta in '{1}' con ID pacchetto ID '{2}'. Primaria: {3}. ========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "I tipi non possono essere visualizzati nelle dichiarazioni di esportazione nei file JavaScript.", "Types_have_separate_declarations_of_a_private_property_0_2442": "I tipi contengono dichiarazioni separate di una proprietà privata '{0}'.", "Types_of_construct_signatures_are_incompatible_2419": "I tipi delle firme del costrutto sono incompatibili.", "Types_of_parameters_0_and_1_are_incompatible_2328": "I tipi dei parametri '{0}' e '{1}' sono incompatibili.", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "Modalità di espressione di controllo e compilazione", "Watch_input_files_6005": "Controlla i file di input.", "Watch_option_0_requires_a_value_of_type_1_5080": "Con l'opzione '{0}' dell'espressione di controllo è richiesto un valore di tipo {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "È possibile solo scrivere un tipo per '{0}' aggiungendo qui un tipo per l'intero parametro.", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Durante l'assegnazione di funzioni verifica che i parametri e i valori restituiti siano compatibili con il sottotipo.", "When_type_checking_take_into_account_null_and_undefined_6699": "Durante il controllo del tipo prende in considerazione 'null' e 'undefined'.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Indica se mantenere l'output della console obsoleto in modalità espressione di controllo invece di pulire lo schermo.", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Racchiudere tra parentesi il corpo seguente che deve essere un valore letterale di oggetto", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Per informazioni su tutte le opzioni del compilatore, vedere {0}", "You_cannot_rename_a_module_via_a_global_import_8031": "Non è possibile rinominare un modulo tramite un'importazione globale.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Non è possibile rinominare gli elementi definiti in una cartella 'node_modules'.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Non è possibile rinominare gli elementi definiti in un'altra cartella 'node_modules'.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Non è possibile rinominare elementi definiti nella libreria TypeScript standard.", "You_cannot_rename_this_element_8000": "Non è possibile rinominare questo elemento.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accetta un numero troppo ridotto di argomenti da usare come espressione Decorator in questo punto. Si intendeva chiamarlo prima e scrivere '@{0}()'?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "Le firme dell'indice '{0}' non sono compatibili.", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "Il tipo di indice '{0}' '{1}' non è assegnabile al tipo di indice '{2}' '{3}'.", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' è una primitiva, ma '{1}' è un oggetto wrapper. Quando possibile, preferire '{0}'.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' è un tipo e non può essere importato nei file JavaScript. Usare '{1}' in un'annotazione di tipo JSDoc.", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "'{0}' è un tipo e deve essere importato usando un'importazione solo di tipi quando 'preserveValueImports' e 'isolatedModules' sono entrambi abilitati.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}' è una ridenominazione inutilizzata di '{1}'. Si intendeva utilizzarla come annotazione di tipo?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}' è assegnabile al vincolo di tipo '{1}', ma è possibile creare un'istanza di '{1}' con un sottotipo diverso del vincolo '{2}'.", + "_0_is_automatically_exported_here_18044": "'{0}' viene esportato automaticamente qui.", "_0_is_declared_but_its_value_is_never_read_6133": "L'elemento '{0}' è dichiarato, ma il suo valore non viene mai letto.", "_0_is_declared_but_never_used_6196": "La variabile '{0}' è dichiarata, ma non viene mai usata.", "_0_is_declared_here_2728": "In questo punto viene dichiarato '{0}'.", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "uno di:", "one_or_more_Colon_6901": "uno o più:", "options_6024": "opzioni", + "or_JSX_element_expected_1145": "Previsto elemento '{' o JSX.", "or_expected_1144": "È previsto '{' o ';'.", "package_json_does_not_have_a_0_field_6100": "Il file 'package.json' non contiene un campo '{0}'.", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json' non contiene alcuna voce di 'typesVersions' corrispondente alla versione '{0}'.", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Il modificatore 'readonly' può essere incluso solo in una dichiarazione di proprietà o una firma dell'indice.", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "Il modificatore di tipo 'readonly' è consentito solo in tipi di valore letterale matrice e tupla.", "require_call_may_be_converted_to_an_import_80005": "La chiamata a 'require' può essere convertita in un'importazione.", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Le asserzioni 'resolution-mode' sono supportate solo quando 'moduleResolution' è 'node16' o 'nodenext'.", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "Le asserzioni 'resolution-mode' sono instabili. Usare TypeScript notturno per disattivare questo errore. Provare ad eseguire l'aggiornamento con 'npm install -D typescript@next'.", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "'resolution-mode' può essere impostata solo per le importazioni di tipo.", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "'resolution-mode' è l'unica chiave valida per l’importazione dei tipi di asserzioni.", "resolution_mode_should_be_either_require_or_import_1453": "'resolution-mode' deve essere 'require' o 'import'.", diff --git a/tsserver/ja/diagnosticMessages.generated.json b/tsserver/ja/diagnosticMessages.generated.json index 4fb7a69a..9841773a 100644 --- a/tsserver/ja/diagnosticMessages.generated.json +++ b/tsserver/ja/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 型はクラスまたはインターフェイスの静的でないメンバーでのみ使用できます。", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' ファイルは既に '{0}' で定義されています。", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "タプル メンバーを optional と rest の両方に指定することはできません。", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "タプル型に負の値のインデックスを指定することはできません。", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "累乗式の左辺で型アサーション式を使用することはできません。式を括弧で囲むことを検討してください。", "A_type_literal_property_cannot_have_an_initializer_1247": "型リテラル プロパティに初期化子を使用することはできません。", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "型のみのインポートでは既定のインポートまたは名前付きバインドを指定できますが、両方を指定することはできません。", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "プロパティ '{0}' に限定代入アサーションを追加します", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "初期化されていないすべてのプロパティに限定代入アサーションを追加します", "Add_export_to_make_this_file_into_a_module_95097": "'export {}' を追加して、このファイルをモジュールにする", + "Add_extends_constraint_2211": "'extends' 制約を追加します。", + "Add_extends_constraint_to_all_type_parameters_2212": "すべての型パラメーターに 'extends' 制約を追加する", "Add_import_from_0_90057": "\"{0}\" からのインポートの追加", "Add_index_signature_for_property_0_90017": "プロパティ '{0}' のインデックス シグネチャを追加する", "Add_initializer_to_property_0_95019": "プロパティ '{0}' に初期化子を追加します", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "インデックス シグネチャのパラメーターには型の注釈が必要です。", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "インデックス シグネチャ パラメーターの型をリテラル型またはジェネリック型にすることはできません。代わりに、マップされたオブジェクト型の使用を検討してください。", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "インデックス シグネチャ パラメーター型は、'string'、'number'、'symbol'、またはテンプレート リテラルの型である必要があります。", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "インスタンス化式の後にプロパティ アクセスを続けることはできません。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "インターフェイスが拡張するのは、オプションの型引数が指定された識別子/完全修飾名のみです。", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "インターフェイスが拡張できるのは、オブジェクト型または静的な既知のメンバーを持つオブジェクト型の積集合のみです。", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "インターフェイスは、'{0}' のようなプリミティブ型を拡張できません。インターフェイスは名前付きの型とクラスのみを拡張できます", "An_interface_property_cannot_have_an_initializer_1246": "インターフェイス プロパティに初期化子を使用することはできません。", "An_iterator_must_have_a_next_method_2489": "反復子には 'next()' メソッドが必要です。", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "@jsx pragma を JSX フラグメントで使用する場合は、@jsxFrag pragma が必要です。", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "クラス '{0}' はクラス '{1}' を正しく実装していません。'{1}' を拡張し、そのメンバーをサブクラスとして継承しますか?", "Class_0_incorrectly_implements_interface_1_2420": "クラス '{0}' はインターフェイス '{1}' を正しく実装していません。", "Class_0_used_before_its_declaration_2449": "クラス '{0}' は宣言の前に使用されました。", + "Class_constructor_may_not_be_a_generator_1360": "クラス コンストラクターをジェネレーターにすることはできません。", + "Class_constructor_may_not_be_an_accessor_1341": "クラス コンストラクターをアクセサーにすることはできません。", "Class_declaration_cannot_implement_overload_list_for_0_2813": "クラスの宣言では '{0}' のオーバーロード リストを実装できません。", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "クラスの宣言で複数の '@augments' または '@extends' タグを含めることはできません。", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "クラス デコレーターは、静的プライベート識別子と共に使用することはできません。試験段階のデコレーターを削除することをご検討ください。", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "ファイル '{0}' が見つかりません。", "File_Management_6245": "ファイルの管理", "File_change_detected_Starting_incremental_compilation_6032": "ファイルの変更が検出されました。インクリメンタル コンパイルを開始しています...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "'{0}' にはフィールド \"type\" がないため、ファイルは CommonJS モジュールです", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "'{0}' にフィールド \"type\" があり、値が \"module\" ではないため、ファイルは CommonJS モジュールです。", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "\"package.json\" が見つからなかったため、ファイルは CommonJS モジュールです", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "'{0}' には値 \"module\" のフィールド \"type\" があるため、ファイルは ECMAScript モジュールです。", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "ファイルは CommonJS モジュールです。ES モジュールに変換される可能性があります。", "File_is_default_library_for_target_specified_here_1426": "ファイルはこちらで指定されたターゲットの既定のライブラリです。", "File_is_entry_point_of_type_library_specified_here_1419": "ファイルはこちらで指定されたタイプ ライブラリのエントリ ポイントです。", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "識別子が予期されていました。'{0}' は、ここでは使用できない予約語です。", "Identifier_expected_1003": "識別子が必要です。", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "識別子が必要です。'__esModule' は、ECMAScript モジュールを変換するときのエクスポート済みマーカーとして予約されています。", + "Identifier_or_string_literal_expected_1478": "識別子または文字列リテラルが必要です。", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "'{0}' パッケージが実際にこのモジュールを公開する場合は、pull request を送信して 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}' を修正することを検討してください", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "'{0}' パッケージが実際にこのモジュールを公開する場合は、'declare module '{1}';' を含む新しい宣言 (d.ts) ファイルを追加してみてください。", "Ignore_this_error_message_90019": "このエラー メッセージを無視する", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "無効なインポート指定子 '{0}' には解決策がありません。", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "拡張のモジュール名が無効です。モジュール '{0}' は '{1}' の型指定のないモジュールに解決されるため、拡張されません。", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "拡張のモジュール名が無効です。モジュール '{0}' が見つかりません。", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "新しい式の省略可能なチェーンが無効です。'{0}()' の呼び出しを意図していましたか?", "Invalid_reference_directive_syntax_1084": "無効な 'reference' ディレクティブ構文です。", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "'{0}' の使用が無効です。クラスの静的ブロック内では使用できません。", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}' の使用方法が無効です。モジュールは自動的に厳格モードになります。", @@ -893,6 +906,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_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}' になります。", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "メンバー '{0}' の型は暗黙的に '{1}' ですが、使い方からより良い型を推論する場合があります。", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "プロジェクト '{0}' はその依存関係 '{1}' にエラーがあるためビルドできません", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "依存関係 '{1}' がビルドされていないため、プロジェクト '{0}' はビルドできません", "Project_0_is_being_forcibly_rebuilt_6388": "プロジェクト '{0}' が強制的にリビルドされています", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "buildinfo ファイルの '{1}' により、一部の変更が生成されなかったことが示されているため、プロジェクトの '{0}' は最新ではありません", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "プロジェクト '{0}' はその依存関係 '{1}' が古いため最新の状態ではありません", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "プロジェクト '{0}' は最も古い出力 '{1}' が最新の入力 '{2}' より古いため最新の状態ではありません", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "プロジェクト '{0}' は出力 '{1}' が入力 '{2}' より古いため最新の状態ではありません", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "プロジェクト '{0}' は出力ファイル '{1}' が存在しないため最新の状態ではありません", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "プロジェクト '{0}' の出力が現在のバージョン '{2}' と異なるバージョン '{1}' で生成されているため、このプロジェクトは最新の状態ではありません", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "依存関係 '{1}' の出力が変更されているため、プロジェクト '{0}' は最新の状態ではありません", "Project_0_is_up_to_date_6361": "プロジェクト '{0}' は最新の状態です", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "プロジェクト '{0}' は最新の入力 '{1}' が最も古い出力 '{2}' より古いため最新の状態です", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "プロジェクト '{0}' は最新の入力 '{1}' が出力 '{2}' より古いため最新の状態です", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "プロジェクト '{0}' は最新ですが、入力ファイルよりも古い出力ファイルのタイムスタンプを更新する必要があります", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "プロジェクト '{0}' はその依存関係からの .d.ts ファイルで最新の状態です", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "プロジェクト参照が円グラフを形成できません。循環が検出されました: {0}", "Projects_6255": "プロジェクト", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必須の型パラメーターの後に、オプションの型パラメーターを続けることはできません。", "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}' のキャッシュには見つかりませんでした。", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "解決モードは、`moduleResolution` が `node16` または `nodenext` の場合にのみサポートされます。", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'keyof' を文字列値のプロパティ名のみに解決します (数字または記号なし)。", "Resolving_module_0_from_1_6086": "======== '{1}' からモジュール '{0}' を解決しています。========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "ベース URL '{1}' - '{2}' に相対するモジュール名 '{0}' を解決しています。", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "名前付きエクスポートで、export ステートメントに 'export type' が使用されている場合、'type' 修飾子は使用できません。", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "名前付きインポートで、import ステートメントに 'import type' が使用されている場合、'type' 修飾子は使用できません。", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "関数の宣言の型は、関数のシグネチャと一致する必要があります。", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "この式の型には、不安定な機能である 'resolution-mode' アサーションなしで名前を付けることはできません。ナイトリー TypeScript を使用して、このエラーをサイレントにします。'npm install -D typescript@next' を使用して更新してみてください。", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "このノードの種類は、そのプロパティ '{0}' をシリアル化できないため、シリアル化できません。", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "非同期反復子の '{0}()' メソッドによって返される型は、'value' プロパティを持つ型に対する promise である必要があります。", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "反復子の '{0}()' メソッドによって返される型には 'value' プロパティが必要です。", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' ステートメントはサポートされていません。'with' ブロック内のすべてのシンボルの型は 'any' になります。", "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_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "JavaScript が値ではなく参照でオブジェクトを比較するため、この条件は常に '{0}' を返します。", "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367": "型 '{1}' と '{2}' には重複がないため、この条件は常に '{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 を返します。代わりにこれを呼び出すことを意図していましたか?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "この構文にはインポートされたヘルパーが必要ですが、モジュール '{0}' が見つかりません。", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "この構文には、'{1}' という名前のインポートされたヘルパーが必要ですが、'{0}' には存在しません。'{0}' のバージョンのアップグレードを検討してください。", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "この構文には、{2} パラメーターを持つ '{1}' という名前のインポートされたヘルパーが必要ですが、'{0}' にあるものと互換性がありません。'{0}' のバージョンをアップグレードすることをご検討ください。", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "この型パラメーターには 'extends {0}' 制約が必要な場合があります。", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "この 'import' の使用は無効です。'import()' 呼び出しは書き込むことができますが、かっこが必要であり、型引数を指定することはできません。", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "トップレベルの 'await' 式は、'module' オプションが 'es2022'、'esnext'、'system'、'node16' または 'nodenext' に設定されていて、'target' オプションが 'es2017' 以上に設定されている場合にのみ使用できます。", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": ".d.ts ファイルのトップレベルの宣言は、'declare' または 'export' 修飾子で始める必要があります。", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "packageId が '{2}' のファイル '{1}' から '{0}' を介して参照されたタイプ ライブラリ", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' オペランドの型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "計算されたプロパティの値の型は '{0}' です。これは、型 '{1}' に代入することはできません。", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "インスタンス メンバー変数 '{0}' の型は、コンストラクターで宣言された識別子 '{1}' を参照できません。", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' オペランドの反復要素の型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "マップされた型 '{1}' で、プロパティ '{0}' の型によってそれ自体が循環参照されています。", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同期ジェネレーター内の 'yield' オペランドの型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== 型参照ディレクティブ '{0}' が解決されませんでした。========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 型参照ディレクティブ '{0}' が正常に '{1}' に解決されました。プライマリ: {2}。========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== 型参照ディレクティブ '{0}' が正常に '{1}' に解決されました (パッケージ ID '{2}'、プライマリ: {3})。========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "JavaScript ファイルのエクスポート宣言に型を含めることはできません。", "Types_have_separate_declarations_of_a_private_property_0_2442": "複数の型に、プライベート プロパティ '{0}' の異なる宣言が含まれています。", "Types_of_construct_signatures_are_incompatible_2419": "コンストラクト シグネチャの型に互換性がありません。", "Types_of_parameters_0_and_1_are_incompatible_2328": "パラメーター '{0}' および '{1}' は型に互換性がありません。", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "ウォッチ モードとビルド モード", "Watch_input_files_6005": "入力ファイルを監視します。", "Watch_option_0_requires_a_value_of_type_1_5080": "監視オプション '{0}' には型 {1} の値が必要です。", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "ここにパラメーター全体の型を追加することによってのみ、'{0}' の型を書き込むことができます。", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "関数を割り当てる際、パラメーターと戻り値が互換性のあるサブタイプであることを確認します。", "When_type_checking_take_into_account_null_and_undefined_6699": "型チェックを行うときは、'null' と 'undefined' が考慮されます。", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "画面をクリアする代わりに、古くなったコンソール出力をウォッチ モードで保持するかどうか。", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "次の本体をかっこで囲みます。これはオブジェクト リテラルです", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "コンパイラ オプションの詳細については、{0} をご覧ください。", "You_cannot_rename_a_module_via_a_global_import_8031": "グローバル インポートを使用してモジュールの名前を変更することはできません。", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "'node_modules' フォルダーで定義されている要素の名前を変更することはできません。", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "別の 'node_modules' フォルダーで定義されている要素の名前を変更することはできません。", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "標準の TypeScript ライブラリで定義された要素の名前を変更することはできません。", "You_cannot_rename_this_element_8000": "この要素の名前を変更することはできません。", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' は受け入れる引数が少なすぎるので、ここでデコレーターとして使用することができません。最初にこれを呼び出してから、'@{0}()' を書き込むつもりでしたか?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "'{0}' インデックス シグネチャに互換性がありません。", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "'{0}'インデックス型'{1}' を '{2}'インデックス型'{3}' に割り当てることはできません。", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' はプリミティブですが、'{1}' はラッパー オブジェクトです。できれば '{0}' をご使用ください。", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' は型であるため、JavaScript ファイルにインポートできません。JSDoc 型の注釈で '{1}' を使用します。", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "\"{0}\" は型であり、\"preserveValueImports\" と \"isolatedModules\" の両方が有効な場合、型に限定したインポートを使用してインポートされる必要があります。", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}' は、'{1}' の未使用の名前変更です。型の注釈として使用するつもりでしたか?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}' は型 '{1}' の制約に代入できますが、'{1}' は制約 '{2}' の別のサブタイプでインスタンス化できることがあります。", + "_0_is_automatically_exported_here_18044": "`{0}` は自動的にここにエクスポートされます。", "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' が宣言されていますが、その値が読み取られることはありません。", "_0_is_declared_but_never_used_6196": "'{0}' は宣言されましたが使用されませんでした。", "_0_is_declared_here_2728": "'{0}' はここで宣言されています。", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "次のいずれか:", "one_or_more_Colon_6901": "1 つ以上", "options_6024": "オプション", + "or_JSX_element_expected_1145": "'{' または JSX 要素が必要です。", "or_expected_1144": "'{' または ';' が必要です。", "package_json_does_not_have_a_0_field_6100": "'package.json' に '{0}' フィールドがありません。", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json' には、バージョン '{0}' と一致する 'typesVersions' エントリがありません。", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾子はプロパティ宣言またはインデックス シグネチャのみに使用できます。", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "'readonly' 型の修飾子は、配列およびタプル リテラル型でのみ使用できます。", "require_call_may_be_converted_to_an_import_80005": "'require' の呼び出しはインポートに変換される可能性があります。", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "'resolution-mode' アサーションは、`moduleResolution` が `node16` または `nodenext` の場合にのみサポートされます。", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "'resolution-mode' アサーションが不安定です。ナイトリー TypeScript を使用して、このエラーをサイレントにします。npm install -D typescript@next' で更新してみてください。", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "`resolution-mode` は、型のみのインポートに対してのみ設定できます。", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "`resolution-mode` は、型インポート アサーションの唯一の有効なキーです。", "resolution_mode_should_be_either_require_or_import_1453": "\"resolution-mode\" は \"require\" または \"import\" のいずれかにする必要があります。", diff --git a/tsserver/ko/diagnosticMessages.generated.json b/tsserver/ko/diagnosticMessages.generated.json index 5a998475..e60bffb9 100644 --- a/tsserver/ko/diagnosticMessages.generated.json +++ b/tsserver/ko/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 형식은 클래스 또는 인터페이스의 비정적 멤버에서만 사용할 수 있습니다.", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' 파일이 이미 '{0}'에 정의되어 있습니다.", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "튜플 멤버는 optional이면서 rest일 수 없습니다.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "튜플 형식은 음수 값으로 인덱싱할 수 없습니다.", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "지수 식의 왼쪽에는 type assertion expression을 사용할 수 없습니다. 식을 괄호로 묶는 것이 좋습니다.", "A_type_literal_property_cannot_have_an_initializer_1247": "형식 리터럴 속성에는 이니셜라이저를 사용할 수 없습니다.", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "형식 전용 가져오기는 기본 가져오기 또는 명명된 바인딩을 지정할 수 있지만, 둘 다 지정할 수는 없습니다.", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "'{0}' 속성에 한정된 할당 어설션 추가", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "초기화되지 않은 모든 속성에 한정된 할당 어설션 추가", "Add_export_to_make_this_file_into_a_module_95097": "'export {}'를 추가하여 이 파일을 모듈로 만들기", + "Add_extends_constraint_2211": "`extends` 제약 조건을 추가합니다.", + "Add_extends_constraint_to_all_type_parameters_2212": "모든 형식 매개 변수에 `extends` 제약 조건 추가", "Add_import_from_0_90057": "\"{0}\"에서 가져오기 추가", "Add_index_signature_for_property_0_90017": "'{0}' 속성에 대해 인덱스 시그니처 추가", "Add_initializer_to_property_0_95019": "'{0}' 속성에 이니셜라이저 추가", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "인덱스 시그니처 매개 변수에는 형식 주석을 사용할 수 없습니다.", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "인덱스 시그니처 매개 변수 형식은 리터럴 유형이나 제네릭 형식일 수 없습니다. 대신 매핑된 개체 형식을 사용하세요.", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "인덱스 시그니처 매개 변수 형식은 'string', 'number', 'symbol' 또는 템플릿 리터럴 형식이어야 합니다.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "인스턴스화 식 뒤에 속성 액세스가 있을 수 없습니다.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "인터페이스는 선택적 형식 인수가 포함된 식별자/정규화된 이름만 확장할 수 있습니다.", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "인터페이스는 개체 형식 또는 정적으로 알려진 멤버가 포함된 개체 형식의 교집합만 확장할 수 있습니다.", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "인터페이스는 '{0}' 같은 기본 형식을 확장할 수 없습니다. 인터페이스는 명명된 형식 및 클래스만 확장할 수 있습니다.", "An_interface_property_cannot_have_an_initializer_1246": "인터페이스 속성에는 이니셜라이저를 사용할 수 없습니다.", "An_iterator_must_have_a_next_method_2489": "반복기에는 'next()' 메서드가 있어야 합니다.", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "@jsx pragma를 JSX 조각과 함께 사용하는 경우에는 @jsxFrag pragma가 필요합니다.", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "'{0}' 클래스가 '{1}' 클래스를 잘못 구현합니다. '{1}'을(를) 확장하고 이 클래스의 멤버를 하위 클래스로 상속하시겠습니까?", "Class_0_incorrectly_implements_interface_1_2420": "'{0}' 클래스가 '{1}' 인터페이스를 잘못 구현합니다.", "Class_0_used_before_its_declaration_2449": "선언 전에 사용된 '{0}' 클래스입니다.", + "Class_constructor_may_not_be_a_generator_1360": "클래스 생성자는 생성기가 아닐 수 있습니다.", + "Class_constructor_may_not_be_an_accessor_1341": "클래스 생성자는 접근자가 아닐 수 있습니다.", "Class_declaration_cannot_implement_overload_list_for_0_2813": "클래스 선언에서 '{0}'에 대한 오버로드 목록을 구현할 수 없습니다.", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "클래스 선언은 '@augments' 또는 '@extends' 태그를 둘 이상 가질 수 없습니다.", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "클래스 데코레이터는 정적 프라이빗 식별자와 함께 사용할 수 없습니다. 실험적 데코레이터를 제거하는 것이 좋습니다.", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "파일 '{0}'을(를) 찾을 수 없습니다.", "File_Management_6245": "파일 관리", "File_change_detected_Starting_incremental_compilation_6032": "파일 변경이 검색되었습니다. 증분 컴파일을 시작하는 중...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "'{0}'에 \"type\" 필드가 없으므로 파일이 CommonJS 모듈입니다.", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "'{0}'에 값이 \"module\"이 아닌 \"type\" 필드가 있으므로 파일이 CommonJS 모듈입니다.", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "'package.json'을 찾을 수 없으므로 파일이 CommonJS 모듈입니다.", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "'{0}'에 값이 \"module\"인 \"type\" 필드가 있으므로 파일이 ECMAScript 모듈입니다.", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "파일이 CommonJS 모듈입니다. ES 모듈로 변환될 수 있습니다.", "File_is_default_library_for_target_specified_here_1426": "파일은 여기에 지정된 대상의 기본 라이브러리입니다.", "File_is_entry_point_of_type_library_specified_here_1419": "파일은 여기에 지정된 형식 라이브러리의 진입점입니다.", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "식별자가 필요합니다. '{0}'은(는) 여기에서 사용할 수 없는 예약어입니다.", "Identifier_expected_1003": "식별자가 필요합니다.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "식별자가 필요합니다. '__esModule'은 ECMAScript 모듈을 변환할 때 내보낸 표식으로 예약되어 있습니다.", + "Identifier_or_string_literal_expected_1478": "식별자 또는 문자열 리터럴이 필요합니다.", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "'{0}' 패키지가 이 모듈을 실제로 공개하는 경우 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}' 수정을 위한 끌어오기 요청을 보내는 것이 좋습니다.", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "'{0}' 패키지가 실제로 이 모듈을 노출하는 경우 'declare module {1}';'이(가) 포함된 새 선언(.d.ts) 파일을 추가해 보세요.", "Ignore_this_error_message_90019": "이 오류 메시지 무시", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "잘못된 가져오기 지정자 '{0}'에는 가능한 해결 방법이 없습니다.", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "확대의 모듈 이름이 잘못되었습니다. '{1}'에서 '{0}' 모듈이 형식화되지 않은 모듈로 확인되어 확대할 수 없습니다.", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "확대의 모듈 이름이 잘못되었습니다. '{0}' 모듈을 찾을 수 없습니다.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "새 식의 선택적 체인이 잘못되었습니다. '{0}()'을 호출하시겠습니까?", "Invalid_reference_directive_syntax_1084": "'reference' 지시문 구문이 잘못되었습니다.", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "'{0}'을(를) 잘못 사용했습니다. 해당 항목은 클래스 정적 블록 내에서 사용할 수 없습니다.", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}'을(를) 잘못 사용했습니다. 모듈은 자동으로 strict 모드가 됩니다.", @@ -893,6 +906,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_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}' 형식이 포함됩니다.", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "'{0}' 멤버는 암시적으로 '{1}' 형식이지만, 사용량에서 더 나은 형식을 유추할 수 있습니다.", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{0}' 프로젝트는 '{1}' 종속성에 오류가 있기 때문에 빌드할 수 없습니다.", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "'{1}' 종속성이 빌드되지 않았기 때문에 '{0}' 프로젝트를 빌드할 수 없습니다.", "Project_0_is_being_forcibly_rebuilt_6388": "'{0}' 프로젝트가 강제로 재구축되고 있습니다.", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "buildinfo 파일 '{1}'이(가) 일부 변경 내용이 내보내지지 않았음을 나타내므로 프로젝트 '{0}'은(는) 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "'{1}' 종속성이 최신 상태가 아니기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "가장 오래된 출력 '{1}'이(가) 최신 입력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "출력 '{1}'이(가) 최신 입력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "'{1}' 출력 파일이 존재하지 않기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "'{0}' 프로젝트의 출력이 현재 버전 '{2}'과(와) 다른 '{1}' 버전으로 생성되었기 때문에 이 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "'{1}' 종속성의 출력이 변경되었기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_up_to_date_6361": "'{0}' 프로젝트가 최신 상태입니다.", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "최신 입력 '{1}'이(가) 가장 오래된 출력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태입니다.", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "최신 입력 '{1}'이(가) 출력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태입니다.", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "프로젝트 '{0}'이(가) 최신 상태이지만 입력 파일보다 오래된 출력 파일의 타임스탬프를 업데이트해야 합니다.", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "'{0}' 프로젝트는 종속성에 .d.ts 파일이 있는 최신 상태입니다.", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "프로젝트 참조는 순환 그래프를 형성할 수 없습니다. 순환이 발견되었습니다. {0}", "Projects_6255": "프로젝트", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "필수 형식 매개 변수는 선택적 형식 매개 변수 다음에 올 수 없습니다.", "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}'에 대한 해상도가 발견되었습니다.", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "해상도 모드는 `moduleResolution`이 `node16` 또는 `nodenext`인 경우에만 지원됩니다.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "문자열 값 속성 이름에 대해서만 'keyof'를 확인합니다(숫자나 기호 아님).", "Resolving_module_0_from_1_6086": "======== '{1}'에서 '{0}' 모듈을 확인하는 중입니다. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "기본 URL '{1}' - '{2}'을(를) 기준으로 모듈 이름 '{0}'을(를) 확인하는 중입니다.", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "export 문에 'export type'이 사용될 때 명명된 내보내기에서 'type' 한정자를 사용할 수 없습니다.", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "import 문에 'import type'이 사용되는 경우 'type' 수정자는 명명된 가져오기에 사용할 수 없습니다.", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "함수 선언의 형식은 함수의 시그니처와 일치해야 합니다.", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "이 식의 형식은 불안정한 기능인 'resolution-mode' 어설션 없이 이름을 지정할 수 없습니다. 야간 TypeScript를 사용하여 이 오류를 무음으로 처리합니다. 'npm install -D typescript@next'로 업데이트해 보세요.", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "속성 '{0}'을(를) 직렬화할 수 없기 때문에 이 노드의 유형을 직렬화할 수 없습니다.", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "비동기 반복기의 '{0}()' 메서드에서 반환하는 형식은 'value' 속성이 있는 형식에 대한 프라미스여야 합니다.", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "반복기의 '{0}()' 메서드에 의해 반환되는 형식에는 'value' 속성이 있어야 합니다.", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' 문은 지원되지 않습니다. 'with' 블록의 모든 기호가 'any' 형식이 됩니다.", "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_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "JavaScript는 값이 아닌 참조로 개체를 비교하므로 이 조건은 항상 '{0}'을(를) 반환합니다.", "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367": "'{1}' 및 '{2}' 형식에 겹침이 없기 때문에 이 조건은 항상 '{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를 반환합니다. 대신 호출하시겠어요?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "이 구문에는 가져온 도우미가 필요하지만 '{0}' 모듈을 찾을 수 없습니다.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "이 구문에는 '{0}'에 없는 '{1}'(이)라는 가져온 도우미가 필요합니다. '{0}'의 버전을 업그레이드하는 것이 좋습니다.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "이 구문에는 {2} 매개 변수가 포함된 '{1}'(이)라는 가져온 도우미가 필요하지만, 이 도우미는 '{0}'에 있는 도우미와 호환되지 않습니다. '{0}' 버전을 업그레이드하는 것이 좋습니다.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "이 형식 매개 변수에는 `extends {0}` 제약 조건이 필요할 수 있습니다.", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "이 '가져오기' 사용은 유효하지 않습니다. 'import()' 호출을 작성할 수 있지만 괄호가 있어야 하며 유형 인수를 가질 수 없습니다.", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "최상위 'await' 식은 'module' 옵션이 'es2022', 'esnext', 'system', 'node16' 또는 'nodenext'로 설정되고 'target' 옵션이 'es2017' 이상으로 설정된 경우에만 허용됩니다.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": ".d.ts 파일의 최상위 수준 선언은 'declare' 또는 'export' 한정자로 시작해야 합니다.", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "packageId가 '{2}'인 '{1}' 파일에서 '{0}'을(를) 통해 형식 라이브러리가 참조되었습니다.", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "계산된 속성 값의 형식은 '{1}' 형식에 할당할 수 없는 '{0}'입니다.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "인스턴스 멤버 변수 '{0}'의 형식은 생성자에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*'의 반복되는 요소 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "'{0}' 속성의 형식은 매핑된 형식 '{1}'에서 순환적으로 자신을 참조합니다.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "비동기 생성기에 있는 'yield' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== 형식 참조 지시문 '{0}'이(가) 확인되지 않았습니다. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 형식 참조 지시문 '{0}'이(가) '{1}'(으)로 확인되었습니다. 주: {2}. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== 형식 참조 지시문 '{0}'이(가) 패키지 ID가 '{2}'인 '{1}'(으)로 확인되었습니다. 주: {3}. ========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "유형은 JavaScript 파일의 내보내기 선언에 나타날 수 없습니다.", "Types_have_separate_declarations_of_a_private_property_0_2442": "형식에 별도의 프라이빗 속성 '{0}' 선언이 있습니다.", "Types_of_construct_signatures_are_incompatible_2419": "구문 시그니처 형식이 호환되지 않습니다.", "Types_of_parameters_0_and_1_are_incompatible_2328": "'{0}' 및 '{1}' 매개 변수의 형식이 호환되지 않습니다.", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "시청 및 빌드 모드", "Watch_input_files_6005": "조사식 입력 파일입니다.", "Watch_option_0_requires_a_value_of_type_1_5080": "조사식 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "여기에서 전체 매개 변수에 대한 형식을 추가하여 '{0}'에 대한 형식만 작성할 수 있습니다.", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "함수를 할당할 때 매개 변수와 반환 값이 하위 형식과 호환되는지 확인합니다.", "When_type_checking_take_into_account_null_and_undefined_6699": "유형 검사 시 'null' 및 'undefined'를 고려하세요.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "화면을 지우지 않고, 감시 모드의 오래된 콘솔 출력을 유지할지 여부입니다.", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "괄호를 사용하여 개체 리터럴이어야 하는 다음 본문 래핑", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "{0}에서 모든 컴파일러 옵션에 대해 알아볼 수 있습니다.", "You_cannot_rename_a_module_via_a_global_import_8031": "전역 가져오기를 통해 모듈 이름을 바꿀 수 없습니다.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "'node_modules' 폴더에 정의된 요소의 이름은 변경할 수 없습니다.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "다른 'node_modules' 폴더에 정의된 요소의 이름은 변경할 수 없습니다.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "표준 TypeScript 라이브러리에 정의된 요소의 이름을 바꿀 수 없습니다.", "You_cannot_rename_this_element_8000": "이 요소의 이름을 바꿀 수 없습니다.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}'이(가) 여기에서 decorator로 사용할 인수를 너무 적게 허용합니다. 먼저 이를 호출하고 '@{0}()'을(를) 작성하시겠습니까?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "'{0}' 인덱스 시그니처가 호환되지 않습니다.", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "'{0}' 인덱스 유형 '{1}'을(를) '{2}' 인텍스 유형 '{3}'에 할당할 수 없습니다.", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "{0}'은(는) 기본 개체이지만 '{1}'은(는) 래퍼 개체입니다. 가능한 경우 '{0}'을(를) 사용하세요.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}'은(는) 유형이며 JavaScript 파일로 가져올 수 없습니다. JSDoc 유형 주석에서 '{1}'을(를) 사용하세요.", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "'{0}'은(는) 형식이며, 'preserveValueImports'와 'isolatedModules'를 모두 사용하도록 설정한 경우 형식 전용 가져오기를 사용하여 가져와야 합니다.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}'은(는) '{1}'의 사용되지 않는 이름 변경입니다. 형식 주석으로 사용하려고 했습니까?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}'은(는) '{1}' 형식의 제약 조건에 할당할 수 있지만, '{1}'은(는) '{2}' 제약 조건의 다른 하위 형식으로 인스턴스화할 수 있습니다.", + "_0_is_automatically_exported_here_18044": "'{0}'은(는) 여기에서 자동으로 내보내집니다.", "_0_is_declared_but_its_value_is_never_read_6133": "'{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", "_0_is_declared_but_never_used_6196": "'{0}'이(가) 선언되었지만 사용되지 않았습니다.", "_0_is_declared_here_2728": "여기서는 '{0}'이(가) 선언됩니다.", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "다음 중 하나:", "one_or_more_Colon_6901": "하나 이상:", "options_6024": "옵션", + "or_JSX_element_expected_1145": "'{' 또는 JSX 요소가 필요합니다.", "or_expected_1144": "'{' 또는 ';'이(가) 필요합니다.", "package_json_does_not_have_a_0_field_6100": "'package.json'에는 '{0}' 필드가 없습니다.", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json'에 '{0}' 버전과 일치하는 'typesVersions' 항목이 없습니다.", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 한정자는 속성 선언 또는 인덱스 시그니처에만 나타날 수 있습니다.", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "'readonly' 형식 한정자는 배열 및 튜플 리터럴 형식에서만 사용할 수 있습니다.", "require_call_may_be_converted_to_an_import_80005": "'require' 호출이 가져오기로 변환될 수 있습니다.", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "'resolution-mode' 어설션은 'moduleResolution'이 'node16' 또는 'nodenext'인 경우에만 지원됩니다.", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "‘resolution-mode’ 어설션이 불안정합니다. 야간 TypeScript를 사용하여 이 오류를 차단하십시오. 'npm install -D typescript@next'로 업데이트해 보세요.", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "'resolution-mode'는 유형 전용 가져오기에만 설정할 수 있습니다.", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "'resolution-mode'는 유형 가져오기 어설션에 유효한 유일한 키입니다.", "resolution_mode_should_be_either_require_or_import_1453": "'해상도 모드'는 '요구' 또는 '가져오기'여야 합니다.", diff --git a/tsserver/lib.dom.d.ts b/tsserver/lib.dom.d.ts index f1761f1c..d1223acc 100644 --- a/tsserver/lib.dom.d.ts +++ b/tsserver/lib.dom.d.ts @@ -590,6 +590,10 @@ interface IDBObjectStoreParameters { keyPath?: string | string[] | null; } +interface IDBTransactionOptions { + durability?: IDBTransactionDurability; +} + interface IDBVersionChangeEventInit extends EventInit { newVersion?: number | null; oldVersion?: number; @@ -721,19 +725,6 @@ interface LockOptions { steal?: boolean; } -interface MIDIConnectionEventInit extends EventInit { - port?: MIDIPort; -} - -interface MIDIMessageEventInit extends EventInit { - data?: Uint8Array; -} - -interface MIDIOptions { - software?: boolean; - sysex?: boolean; -} - interface MediaCapabilitiesDecodingInfo extends MediaCapabilitiesInfo { configuration?: MediaDecodingConfiguration; } @@ -1514,12 +1505,12 @@ interface RTCTransportStats extends RTCStats { tlsVersion?: string; } -interface ReadableStreamDefaultReadDoneResult { +interface ReadableStreamReadDoneResult { done: true; value?: undefined; } -interface ReadableStreamDefaultReadValueResult { +interface ReadableStreamReadValueResult { done: false; value: T; } @@ -1815,6 +1806,19 @@ interface UnderlyingSource { type?: undefined; } +interface ValidityStateFlags { + badInput?: boolean; + customError?: boolean; + patternMismatch?: boolean; + rangeOverflow?: boolean; + rangeUnderflow?: boolean; + stepMismatch?: boolean; + tooLong?: boolean; + tooShort?: boolean; + typeMismatch?: boolean; + valueMissing?: boolean; +} + interface VideoColorSpaceInit { fullRange?: boolean; matrix?: VideoMatrixCoefficients; @@ -2191,6 +2195,7 @@ declare var AudioBufferSourceNode: { /** An audio-processing graph built from audio modules linked together, each represented by an AudioNode. */ interface AudioContext extends BaseAudioContext { readonly baseLatency: number; + readonly outputLatency: number; close(): Promise; createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; createMediaStreamDestination(): MediaStreamAudioDestinationNode; @@ -2567,7 +2572,7 @@ declare var CSSAnimation: { /** A single condition CSS at-rule, which consists of a condition and a statement block. It is a child of CSSGroupingRule. */ interface CSSConditionRule extends CSSGroupingRule { - conditionText: string; + readonly conditionText: string; } declare var CSSConditionRule: { @@ -2853,7 +2858,6 @@ interface CSSStyleDeclaration { columns: string; contain: string; content: string; - contentVisibility: string; counterIncrement: string; counterReset: string; counterSet: string; @@ -3227,6 +3231,8 @@ interface CSSStyleDeclaration { /** @deprecated This is a legacy alias of `perspectiveOrigin`. */ webkitPerspectiveOrigin: string; webkitTextFillColor: string; + /** @deprecated This is a legacy alias of `textSizeAdjust`. */ + webkitTextSizeAdjust: string; webkitTextStroke: string; webkitTextStrokeColor: string; webkitTextStrokeWidth: string; @@ -3294,6 +3300,8 @@ interface CSSStyleSheet extends StyleSheet { insertRule(rule: string, index?: number): number; /** @deprecated */ removeRule(index?: number): void; + replace(text: string): Promise; + replaceSync(text: string): void; } declare var CSSStyleSheet: { @@ -3777,6 +3785,7 @@ declare var CustomEvent: { /** An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. */ interface DOMException extends Error { + /** @deprecated */ readonly code: number; readonly message: string; readonly name: string; @@ -4521,8 +4530,6 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; createEvent(eventInterface: "InputEvent"): InputEvent; createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; - createEvent(eventInterface: "MIDIConnectionEvent"): MIDIConnectionEvent; - createEvent(eventInterface: "MIDIMessageEvent"): MIDIMessageEvent; createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; @@ -4734,6 +4741,7 @@ interface DocumentOrShadowRoot { * Similarly, when the focused element is in a different node tree than documentOrShadowRoot, the element returned will be the host that's located in the same node tree as documentOrShadowRoot if documentOrShadowRoot is a shadow-including inclusive ancestor of the focused element, and null if not. */ readonly activeElement: Element | null; + adoptedStyleSheets: CSSStyleSheet[]; /** Returns document's fullscreen element. */ readonly fullscreenElement: Element | null; readonly pictureInPictureElement: Element | null; @@ -4981,14 +4989,24 @@ interface ElementInternals extends ARIAMixin { readonly labels: NodeList; /** Returns the ShadowRoot for internals's target element, if the target element is a shadow host, or null otherwise. */ readonly shadowRoot: ShadowRoot | null; + /** Returns the error message that would be shown to the user if internals's target element was to be checked for validity. */ + readonly validationMessage: string; + /** Returns the ValidityState object for internals's target element. */ + readonly validity: ValidityState; /** Returns true if internals's target element will be validated when the form is submitted; false otherwise. */ readonly willValidate: boolean; + /** Returns true if internals's target element has no validity problems; false otherwise. Fires an invalid event at the element in the latter case. */ + checkValidity(): boolean; + /** Returns true if internals's target element has no validity problems; otherwise, returns false, fires an invalid event at the element, and (if the event isn't canceled) reports the problem to the user. */ + reportValidity(): boolean; /** * Sets both the state and submission value of internals's target element to value. * * If value is null, the element won't participate in form submission. */ setFormValue(value: File | string | FormData | null, state?: File | string | FormData | null): void; + /** Marks internals's target element as suffering from the constraints indicated by the flags argument, and sets the element's validation message to message. If anchor is specified, the user agent might use it to indicate problems with the constraints of internals's target element when the form owner is validated interactively or reportValidity() is called. */ + setValidity(flags?: ValidityStateFlags, message?: string, anchor?: HTMLElement): void; } declare var ElementInternals: { @@ -6072,7 +6090,6 @@ declare var HTMLBaseElement: { }; interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { - "orientationchange": Event; } /** Provides special properties (beyond those inherited from the regular HTMLElement interface) for manipulating elements. */ @@ -6086,8 +6103,6 @@ interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { /** @deprecated */ link: string; /** @deprecated */ - onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null; - /** @deprecated */ text: string; /** @deprecated */ vLink: string; @@ -6346,6 +6361,7 @@ interface HTMLElement extends Element, DocumentAndElementEventHandlers, ElementC dir: string; draggable: boolean; hidden: boolean; + inert: boolean; innerText: string; lang: string; readonly offsetHeight: number; @@ -7009,6 +7025,7 @@ interface HTMLInputElement extends HTMLElement { * @param direction The direction in which the selection is performed. */ setSelectionRange(start: number | null, end: number | null, direction?: "forward" | "backward" | "none"): void; + showPicker(): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -7236,6 +7253,7 @@ interface HTMLMediaElement extends HTMLElement { readonly played: TimeRanges; /** Gets or sets a value indicating what data should be preloaded, if any. */ preload: "none" | "metadata" | "auto" | ""; + preservesPitch: boolean; readonly readyState: number; readonly remote: RemotePlayback; /** Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -7602,16 +7620,25 @@ declare var HTMLParagraphElement: { new(): HTMLParagraphElement; }; -/** Provides special properties (beyond those of the regular HTMLElement object interface it inherits) for manipulating elements, representing a pair of a key and a value that acts as a parameter for an element. */ +/** + * Provides special properties (beyond those of the regular HTMLElement object interface it inherits) for manipulating elements, representing a pair of a key and a value that acts as a parameter for an element. + * @deprecated + */ interface HTMLParamElement extends HTMLElement { - /** Sets or retrieves the name of an input parameter for an element. */ + /** + * Sets or retrieves the name of an input parameter for an element. + * @deprecated + */ name: string; /** * Sets or retrieves the content type of the resource designated by the value attribute. * @deprecated */ type: string; - /** Sets or retrieves the value of an input parameter for an element. */ + /** + * Sets or retrieves the value of an input parameter for an element. + * @deprecated + */ value: string; /** * Sets or retrieves the data type of the value attribute. @@ -7624,6 +7651,7 @@ interface HTMLParamElement extends HTMLElement { removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } +/** @deprecated */ declare var HTMLParamElement: { prototype: HTMLParamElement; new(): HTMLParamElement; @@ -8517,7 +8545,7 @@ interface IDBDatabase extends EventTarget { */ deleteObjectStore(name: string): void; /** Returns a new transaction with the given mode ("readonly" or "readwrite") and scope which can be a single object store name or an array of names. */ - transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode, options?: IDBTransactionOptions): IDBTransaction; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -9103,126 +9131,6 @@ declare var LockManager: { new(): LockManager; }; -interface MIDIAccessEventMap { - "statechange": Event; -} - -/** Available only in secure contexts. */ -interface MIDIAccess extends EventTarget { - readonly inputs: MIDIInputMap; - onstatechange: ((this: MIDIAccess, ev: Event) => any) | null; - readonly outputs: MIDIOutputMap; - readonly sysexEnabled: boolean; - addEventListener(type: K, listener: (this: MIDIAccess, ev: MIDIAccessEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: MIDIAccess, ev: MIDIAccessEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -declare var MIDIAccess: { - prototype: MIDIAccess; - new(): MIDIAccess; -}; - -/** Available only in secure contexts. */ -interface MIDIConnectionEvent extends Event { - readonly port: MIDIPort; -} - -declare var MIDIConnectionEvent: { - prototype: MIDIConnectionEvent; - new(type: string, eventInitDict?: MIDIConnectionEventInit): MIDIConnectionEvent; -}; - -interface MIDIInputEventMap extends MIDIPortEventMap { - "midimessage": Event; -} - -/** Available only in secure contexts. */ -interface MIDIInput extends MIDIPort { - onmidimessage: ((this: MIDIInput, ev: Event) => any) | null; - addEventListener(type: K, listener: (this: MIDIInput, ev: MIDIInputEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: MIDIInput, ev: MIDIInputEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -declare var MIDIInput: { - prototype: MIDIInput; - new(): MIDIInput; -}; - -/** Available only in secure contexts. */ -interface MIDIInputMap { - forEach(callbackfn: (value: MIDIInput, key: string, parent: MIDIInputMap) => void, thisArg?: any): void; -} - -declare var MIDIInputMap: { - prototype: MIDIInputMap; - new(): MIDIInputMap; -}; - -/** Available only in secure contexts. */ -interface MIDIMessageEvent extends Event { - readonly data: Uint8Array; -} - -declare var MIDIMessageEvent: { - prototype: MIDIMessageEvent; - new(type: string, eventInitDict?: MIDIMessageEventInit): MIDIMessageEvent; -}; - -/** Available only in secure contexts. */ -interface MIDIOutput extends MIDIPort { - send(data: number[], timestamp?: DOMHighResTimeStamp): void; - addEventListener(type: K, listener: (this: MIDIOutput, ev: MIDIPortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: MIDIOutput, ev: MIDIPortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -declare var MIDIOutput: { - prototype: MIDIOutput; - new(): MIDIOutput; -}; - -/** Available only in secure contexts. */ -interface MIDIOutputMap { - forEach(callbackfn: (value: MIDIOutput, key: string, parent: MIDIOutputMap) => void, thisArg?: any): void; -} - -declare var MIDIOutputMap: { - prototype: MIDIOutputMap; - new(): MIDIOutputMap; -}; - -interface MIDIPortEventMap { - "statechange": Event; -} - -/** Available only in secure contexts. */ -interface MIDIPort extends EventTarget { - readonly connection: MIDIPortConnectionState; - readonly id: string; - readonly manufacturer: string | null; - readonly name: string | null; - onstatechange: ((this: MIDIPort, ev: Event) => any) | null; - readonly state: MIDIPortDeviceState; - readonly type: MIDIPortType; - readonly version: string | null; - close(): Promise; - open(): Promise; - addEventListener(type: K, listener: (this: MIDIPort, ev: MIDIPortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: MIDIPort, ev: MIDIPortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -declare var MIDIPort: { - prototype: MIDIPort; - new(): MIDIPort; -}; - interface MathMLElementEventMap extends ElementEventMap, DocumentAndElementEventHandlersEventMap, GlobalEventHandlersEventMap { } @@ -9925,7 +9833,7 @@ declare var NavigationPreloadManager: { }; /** The state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities. */ -interface Navigator extends NavigatorAutomationInformation, NavigatorConcurrentHardware, NavigatorContentUtils, NavigatorCookies, NavigatorID, NavigatorLanguage, NavigatorLocks, NavigatorNetworkInformation, NavigatorOnLine, NavigatorPlugins, NavigatorStorage { +interface Navigator extends NavigatorAutomationInformation, NavigatorConcurrentHardware, NavigatorContentUtils, NavigatorCookies, NavigatorID, NavigatorLanguage, NavigatorLocks, NavigatorOnLine, NavigatorPlugins, NavigatorStorage { /** Available only in secure contexts. */ readonly clipboard: Clipboard; /** Available only in secure contexts. */ @@ -9944,8 +9852,6 @@ interface Navigator extends NavigatorAutomationInformation, NavigatorConcurrentH canShare(data?: ShareData): boolean; getGamepads(): (Gamepad | null)[]; /** Available only in secure contexts. */ - requestMIDIAccess(options?: MIDIOptions): Promise; - /** Available only in secure contexts. */ requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; sendBeacon(url: string | URL, data?: BodyInit | null): boolean; /** Available only in secure contexts. */ @@ -9982,7 +9888,6 @@ interface NavigatorID { readonly appName: string; /** @deprecated */ readonly appVersion: string; - /** @deprecated */ readonly platform: string; /** @deprecated */ readonly product: string; @@ -10004,10 +9909,6 @@ interface NavigatorLocks { readonly locks: LockManager; } -interface NavigatorNetworkInformation { - readonly connection: NetworkInformation; -} - interface NavigatorOnLine { readonly onLine: boolean; } @@ -10027,15 +9928,6 @@ interface NavigatorStorage { readonly storage: StorageManager; } -interface NetworkInformation extends EventTarget { - readonly type: ConnectionType; -} - -declare var NetworkInformation: { - prototype: NetworkInformation; - new(): NetworkInformation; -}; - /** Node is an interface from which a number of DOM API object types inherit. It allows those types to be treated similarly; for example, inheriting the same set of methods, or being tested in the same way. */ interface Node extends EventTarget { /** Returns node's node document's document base URL. */ @@ -10994,6 +10886,7 @@ declare var PushManager: { */ interface PushSubscription { readonly endpoint: string; + readonly expirationTime: EpochTimeStamp | null; readonly options: PushSubscriptionOptions; getKey(name: PushEncryptionKeyName): ArrayBuffer | null; toJSON(): PushSubscriptionJSON; @@ -11475,6 +11368,19 @@ declare var Range: { toString(): string; }; +interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(e?: any): void; +} + +declare var ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; +}; + /** This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. */ interface ReadableStream { readonly locked: boolean; @@ -11490,6 +11396,27 @@ declare var ReadableStream: { new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; +interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + read(view: ArrayBufferView): Promise>; + releaseLock(): void; +} + +declare var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; +}; + +interface ReadableStreamBYOBRequest { + readonly view: ArrayBufferView | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBufferView): void; +} + +declare var ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; +}; + interface ReadableStreamDefaultController { readonly desiredSize: number | null; close(): void; @@ -11503,7 +11430,7 @@ declare var ReadableStreamDefaultController: { }; interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { - read(): Promise>; + read(): Promise>; releaseLock(): void; } @@ -13921,11 +13848,11 @@ declare var SubmitEvent: { * Available only in secure contexts. */ interface SubtleCrypto { - decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise; digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; - encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; exportKey(format: "jwk", key: CryptoKey): Promise; exportKey(format: Exclude, key: CryptoKey): Promise; generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray): Promise; @@ -16683,7 +16610,7 @@ interface Window extends EventTarget, AnimationFrameProvider, GlobalEventHandler /** Returns true if the toolbar is visible; otherwise, returns false. */ readonly toolbar: BarProp; readonly top: WindowProxy | null; - readonly visualViewport: VisualViewport; + readonly visualViewport: VisualViewport | null; readonly window: Window & typeof globalThis; alert(message?: any): void; blur(): void; @@ -16802,8 +16729,8 @@ interface WindowOrWorkerGlobalScope { readonly performance: Performance; atob(data: string): string; btoa(data: string): string; - clearInterval(id?: number): void; - clearTimeout(id?: number): void; + clearInterval(id: number | undefined): void; + clearTimeout(id: number | undefined): void; createImageBitmap(image: ImageBitmapSource, options?: ImageBitmapOptions): Promise; createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; fetch(input: RequestInfo | URL, init?: RequestInit): Promise; @@ -16875,6 +16802,7 @@ declare var WritableStream: { /** This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. */ interface WritableStreamDefaultController { + readonly signal: AbortSignal; error(e?: any): void; } @@ -17493,7 +17421,6 @@ interface HTMLElementTagNameMap { "details": HTMLDetailsElement; "dfn": HTMLElement; "dialog": HTMLDialogElement; - "dir": HTMLDirectoryElement; "div": HTMLDivElement; "dl": HTMLDListElement; "dt": HTMLElement; @@ -17502,11 +17429,8 @@ interface HTMLElementTagNameMap { "fieldset": HTMLFieldSetElement; "figcaption": HTMLElement; "figure": HTMLElement; - "font": HTMLFontElement; "footer": HTMLElement; "form": HTMLFormElement; - "frame": HTMLFrameElement; - "frameset": HTMLFrameSetElement; "h1": HTMLHeadingElement; "h2": HTMLHeadingElement; "h3": HTMLHeadingElement; @@ -17531,7 +17455,6 @@ interface HTMLElementTagNameMap { "main": HTMLElement; "map": HTMLMapElement; "mark": HTMLElement; - "marquee": HTMLMarqueeElement; "menu": HTMLMenuElement; "meta": HTMLMetaElement; "meter": HTMLMeterElement; @@ -17543,7 +17466,6 @@ interface HTMLElementTagNameMap { "option": HTMLOptionElement; "output": HTMLOutputElement; "p": HTMLParagraphElement; - "param": HTMLParamElement; "picture": HTMLPictureElement; "pre": HTMLPreElement; "progress": HTMLProgressElement; @@ -17585,7 +17507,34 @@ interface HTMLElementTagNameMap { } interface HTMLElementDeprecatedTagNameMap { + "acronym": HTMLElement; + "applet": HTMLUnknownElement; + "basefont": HTMLElement; + "bgsound": HTMLUnknownElement; + "big": HTMLElement; + "blink": HTMLUnknownElement; + "center": HTMLElement; + "dir": HTMLDirectoryElement; + "font": HTMLFontElement; + "frame": HTMLFrameElement; + "frameset": HTMLFrameSetElement; + "isindex": HTMLUnknownElement; + "keygen": HTMLUnknownElement; "listing": HTMLPreElement; + "marquee": HTMLMarqueeElement; + "menuitem": HTMLElement; + "multicol": HTMLUnknownElement; + "nextid": HTMLUnknownElement; + "nobr": HTMLElement; + "noembed": HTMLElement; + "noframes": HTMLElement; + "param": HTMLParamElement; + "plaintext": HTMLElement; + "rb": HTMLElement; + "rtc": HTMLElement; + "spacer": HTMLUnknownElement; + "strike": HTMLElement; + "tt": HTMLElement; "xmp": HTMLPreElement; } @@ -17734,7 +17683,7 @@ declare var statusbar: BarProp; /** Returns true if the toolbar is visible; otherwise, returns false. */ declare var toolbar: BarProp; declare var top: WindowProxy | null; -declare var visualViewport: VisualViewport; +declare var visualViewport: VisualViewport | null; declare var window: Window & typeof globalThis; declare function alert(message?: any): void; declare function blur(): void; @@ -18088,8 +18037,8 @@ declare var origin: string; declare var performance: Performance; declare function atob(data: string): string; declare function btoa(data: string): string; -declare function clearInterval(id?: number): void; -declare function clearTimeout(id?: number): void; +declare function clearInterval(id: number | undefined): void; +declare function clearTimeout(id: number | undefined): void; declare function createImageBitmap(image: ImageBitmapSource, options?: ImageBitmapOptions): Promise; declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; @@ -18138,7 +18087,7 @@ type GLuint64 = number; type HTMLOrSVGImageElement = HTMLImageElement | SVGImageElement; type HTMLOrSVGScriptElement = HTMLScriptElement | SVGScriptElement; type HashAlgorithmIdentifier = AlgorithmIdentifier; -type HeadersInit = string[][] | Record | Headers; +type HeadersInit = [string, string][] | Record | Headers; type IDBValidKey = number | string | Date | BufferSource | IDBValidKey[]; type ImageBitmapSource = CanvasImageSource | Blob | ImageData; type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; @@ -18152,7 +18101,7 @@ type OnBeforeUnloadEventHandler = OnBeforeUnloadEventHandlerNonNull | null; type OnErrorEventHandler = OnErrorEventHandlerNonNull | null; type PerformanceEntryList = PerformanceEntry[]; type ReadableStreamController = ReadableStreamDefaultController; -type ReadableStreamDefaultReadResult = ReadableStreamDefaultReadValueResult | ReadableStreamDefaultReadDoneResult; +type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; type ReadableStreamReader = ReadableStreamDefaultReader; type RenderingContext = CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext; type RequestInfo = Request | string; @@ -18196,11 +18145,10 @@ type ColorGamut = "p3" | "rec2020" | "srgb"; type ColorSpaceConversion = "default" | "none"; type CompositeOperation = "accumulate" | "add" | "replace"; type CompositeOperationOrAuto = "accumulate" | "add" | "auto" | "replace"; -type ConnectionType = "bluetooth" | "cellular" | "ethernet" | "mixed" | "none" | "other" | "unknown" | "wifi"; type CredentialMediationRequirement = "optional" | "required" | "silent"; type DOMParserSupportedType = "application/xhtml+xml" | "application/xml" | "image/svg+xml" | "text/html" | "text/xml"; type DirectionSetting = "" | "lr" | "rl"; -type DisplayCaptureSurfaceType = "application" | "browser" | "monitor" | "window"; +type DisplayCaptureSurfaceType = "browser" | "monitor" | "window"; type DistanceModelType = "exponential" | "inverse" | "linear"; type DocumentReadyState = "complete" | "interactive" | "loading"; type DocumentVisibilityState = "hidden" | "visible"; @@ -18227,9 +18175,6 @@ type KeyType = "private" | "public" | "secret"; type KeyUsage = "decrypt" | "deriveBits" | "deriveKey" | "encrypt" | "sign" | "unwrapKey" | "verify" | "wrapKey"; type LineAlignSetting = "center" | "end" | "start"; type LockMode = "exclusive" | "shared"; -type MIDIPortConnectionState = "closed" | "open" | "pending"; -type MIDIPortDeviceState = "connected" | "disconnected"; -type MIDIPortType = "input" | "output"; type MediaDecodingType = "file" | "media-source" | "webrtc"; type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"; type MediaEncodingType = "record" | "webrtc"; diff --git a/tsserver/lib.dom.iterable.d.ts b/tsserver/lib.dom.iterable.d.ts index 4fcd2a2d..cde428df 100644 --- a/tsserver/lib.dom.iterable.d.ts +++ b/tsserver/lib.dom.iterable.d.ts @@ -121,7 +121,7 @@ interface Headers { interface IDBDatabase { /** Returns a new transaction with the given mode ("readonly" or "readwrite") and scope which can be a single object store name or an array of names. */ - transaction(storeNames: string | Iterable, mode?: IDBTransactionMode): IDBTransaction; + transaction(storeNames: string | Iterable, mode?: IDBTransactionMode, options?: IDBTransactionOptions): IDBTransaction; } interface IDBObjectStore { @@ -133,16 +133,6 @@ interface IDBObjectStore { createIndex(name: string, keyPath: string | Iterable, options?: IDBIndexParameters): IDBIndex; } -interface MIDIInputMap extends ReadonlyMap { -} - -interface MIDIOutput { - send(data: Iterable, timestamp?: DOMHighResTimeStamp): void; -} - -interface MIDIOutputMap extends ReadonlyMap { -} - interface MediaKeyStatusMap { [Symbol.iterator](): IterableIterator<[BufferSource, MediaKeyStatus]>; entries(): IterableIterator<[BufferSource, MediaKeyStatus]>; diff --git a/tsserver/lib.es2015.collection.d.ts b/tsserver/lib.es2015.collection.d.ts index dc154ca1..c2e7733a 100644 --- a/tsserver/lib.es2015.collection.d.ts +++ b/tsserver/lib.es2015.collection.d.ts @@ -19,18 +19,38 @@ and limitations under the License. interface Map { + clear(): void; + /** + * @returns true if an element in the Map existed and has been removed, or false if the element does not exist. + */ delete(key: K): boolean; + /** + * Executes a provided function once per each key/value pair in the Map, in insertion order. + */ forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; + /** + * Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map. + * @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. + */ get(key: K): V | undefined; + /** + * @returns boolean indicating whether an element with the specified key exists or not. + */ has(key: K): boolean; + /** + * Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated. + */ set(key: K, value: V): this; + /** + * @returns the number of elements in the Map. + */ readonly size: number; } interface MapConstructor { new(): Map; - new(entries?: readonly (readonly [K, V])[] | null): Map; + new (entries?: readonly (readonly [K, V])[] | null): Map; readonly prototype: Map; } declare var Map: MapConstructor; @@ -43,9 +63,23 @@ interface ReadonlyMap { } interface WeakMap { + /** + * Removes the specified element from the WeakMap. + * @returns true if the element was successfully removed, or false if it was not present. + */ delete(key: K): boolean; + /** + * @returns a specified element. + */ get(key: K): V | undefined; + /** + * @returns a boolean indicating whether an element with the specified key exists or not. + */ has(key: K): boolean; + /** + * Adds a new element with a specified key and value. + * @param key Must be an object. + */ set(key: K, value: V): this; } @@ -56,11 +90,28 @@ interface WeakMapConstructor { declare var WeakMap: WeakMapConstructor; interface Set { + /** + * Appends a new element with a specified value to the end of the Set. + */ add(value: T): this; + clear(): void; + /** + * Removes a specified value from the Set. + * @returns Returns true if an element in the Set existed and has been removed, or false if the element does not exist. + */ delete(value: T): boolean; + /** + * Executes a provided function once per each value in the Set object, in insertion order. + */ forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + /** + * @returns a boolean indicating whether an element with the specified value exists in the Set or not. + */ has(value: T): boolean; + /** + * @returns the number of (unique) elements in Set. + */ readonly size: number; } @@ -77,8 +128,18 @@ interface ReadonlySet { } interface WeakSet { + /** + * Appends a new object to the end of the WeakSet. + */ add(value: T): this; + /** + * Removes the specified element from the WeakSet. + * @returns Returns true if the element existed and has been removed, or false if the element does not exist. + */ delete(value: T): boolean; + /** + * @returns a boolean indicating whether an object exists in the WeakSet or not. + */ has(value: T): boolean; } diff --git a/tsserver/lib.es2015.proxy.d.ts b/tsserver/lib.es2015.proxy.d.ts index 9e8b8757..c2418661 100644 --- a/tsserver/lib.es2015.proxy.d.ts +++ b/tsserver/lib.es2015.proxy.d.ts @@ -19,23 +19,112 @@ and limitations under the License. interface ProxyHandler { + /** + * A trap method for a function call. + * @param target The original callable object which is being proxied. + */ apply?(target: T, thisArg: any, argArray: any[]): any; + + /** + * A trap for the `new` operator. + * @param target The original object which is being proxied. + * @param newTarget The constructor that was originally called. + */ construct?(target: T, argArray: any[], newTarget: Function): object; - defineProperty?(target: T, p: string | symbol, attributes: PropertyDescriptor): boolean; + + /** + * A trap for `Object.defineProperty()`. + * @param target The original object which is being proxied. + * @returns A `Boolean` indicating whether or not the property has been defined. + */ + defineProperty?(target: T, property: string | symbol, attributes: PropertyDescriptor): boolean; + + /** + * A trap for the `delete` operator. + * @param target The original object which is being proxied. + * @param p The name or `Symbol` of the property to delete. + * @returns A `Boolean` indicating whether or not the property was deleted. + */ deleteProperty?(target: T, p: string | symbol): boolean; + + /** + * A trap for getting a property value. + * @param target The original object which is being proxied. + * @param p The name or `Symbol` of the property to get. + * @param receiver The proxy or an object that inherits from the proxy. + */ get?(target: T, p: string | symbol, receiver: any): any; + + /** + * A trap for `Object.getOwnPropertyDescriptor()`. + * @param target The original object which is being proxied. + * @param p The name of the property whose description should be retrieved. + */ getOwnPropertyDescriptor?(target: T, p: string | symbol): PropertyDescriptor | undefined; + + /** + * A trap for the `[[GetPrototypeOf]]` internal method. + * @param target The original object which is being proxied. + */ getPrototypeOf?(target: T): object | null; + + /** + * A trap for the `in` operator. + * @param target The original object which is being proxied. + * @param p The name or `Symbol` of the property to check for existence. + */ has?(target: T, p: string | symbol): boolean; + + /** + * A trap for `Object.isExtensible()`. + * @param target The original object which is being proxied. + */ isExtensible?(target: T): boolean; + + /** + * A trap for `Reflect.ownKeys()`. + * @param target The original object which is being proxied. + */ ownKeys?(target: T): ArrayLike; + + /** + * A trap for `Object.preventExtensions()`. + * @param target The original object which is being proxied. + */ preventExtensions?(target: T): boolean; - set?(target: T, p: string | symbol, value: any, receiver: any): boolean; + + /** + * A trap for setting a property value. + * @param target The original object which is being proxied. + * @param p The name or `Symbol` of the property to set. + * @param receiver The object to which the assignment was originally directed. + * @returns `A `Boolean` indicating whether or not the property was set. + */ + set?(target: T, p: string | symbol, newValue: any, receiver: any): boolean; + + /** + * A trap for `Object.setPrototypeOf()`. + * @param target The original object which is being proxied. + * @param newPrototype The object's new prototype or `null`. + */ setPrototypeOf?(target: T, v: object | null): boolean; } interface ProxyConstructor { + /** + * Creates a revocable Proxy object. + * @param target A target object to wrap with Proxy. + * @param handler An object whose properties define the behavior of Proxy when an operation is attempted on it. + */ revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + + /** + * Creates a Proxy object. The Proxy object allows you to create an object that can be used in place of the + * original object, but which may redefine fundamental Object operations like getting, setting, and defining + * properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs. + * @param target A target object to wrap with Proxy. + * @param handler An object whose properties define the behavior of Proxy when an operation is attempted on it. + */ new (target: T, handler: ProxyHandler): T; } declare var Proxy: ProxyConstructor; diff --git a/tsserver/lib.es2017.intl.d.ts b/tsserver/lib.es2017.intl.d.ts index f20c149f..c2ab43e8 100644 --- a/tsserver/lib.es2017.intl.d.ts +++ b/tsserver/lib.es2017.intl.d.ts @@ -19,7 +19,22 @@ and limitations under the License. declare namespace Intl { - type DateTimeFormatPartTypes = "day" | "dayPeriod" | "era" | "hour" | "literal" | "minute" | "month" | "second" | "timeZoneName" | "weekday" | "year"; + + interface DateTimeFormatPartTypesRegistry { + day: any + dayPeriod: any + era: any + hour: any + literal: any + minute: any + month: any + second: any + timeZoneName: any + weekday: any + year: any + } + + type DateTimeFormatPartTypes = keyof DateTimeFormatPartTypesRegistry; interface DateTimeFormatPart { type: DateTimeFormatPartTypes; diff --git a/tsserver/lib.es2020.intl.d.ts b/tsserver/lib.es2020.intl.d.ts index af981e31..5bce3812 100644 --- a/tsserver/lib.es2020.intl.d.ts +++ b/tsserver/lib.es2020.intl.d.ts @@ -18,6 +18,7 @@ and limitations under the License. /// +/// declare namespace Intl { /** @@ -50,6 +51,25 @@ declare namespace Intl { | "second" | "seconds"; + /** + * Value of the `unit` property in objects returned by + * `Intl.RelativeTimeFormat.prototype.formatToParts()`. `formatToParts` and + * `format` methods accept either singular or plural unit names as input, + * but `formatToParts` only outputs singular (e.g. "day") not plural (e.g. + * "days"). + * + * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts). + */ + type RelativeTimeFormatUnitSingular = + | "year" + | "quarter" + | "month" + | "week" + | "day" + | "hour" + | "minute" + | "second"; + /** * The locale matching algorithm to use. * @@ -120,11 +140,16 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts). */ - interface RelativeTimeFormatPart { - type: string; - value: string; - unit?: RelativeTimeFormatUnit; - } + type RelativeTimeFormatPart = + | { + type: "literal"; + value: string; + } + | { + type: Exclude; + value: string; + unit: RelativeTimeFormatUnitSingular; + }; interface RelativeTimeFormat { /** diff --git a/tsserver/lib.es2021.intl.d.ts b/tsserver/lib.es2021.intl.d.ts index 1e8cec37..e66ebb1a 100644 --- a/tsserver/lib.es2021.intl.d.ts +++ b/tsserver/lib.es2021.intl.d.ts @@ -20,17 +20,25 @@ and limitations under the License. declare namespace Intl { + interface DateTimeFormatPartTypesRegistry { + fractionalSecond: any + } + interface DateTimeFormatOptions { formatMatcher?: "basic" | "best fit" | "best fit" | undefined; dateStyle?: "full" | "long" | "medium" | "short" | undefined; timeStyle?: "full" | "long" | "medium" | "short" | undefined; dayPeriod?: "narrow" | "short" | "long" | undefined; - fractionalSecondDigits?: 0 | 1 | 2 | 3 | undefined; + fractionalSecondDigits?: 1 | 2 | 3 | undefined; + } + + interface DateTimeRangeFormatPart extends DateTimeFormatPart { + source: "startRange" | "endRange" | "shared" } interface DateTimeFormat { formatRange(startDate: Date | number | bigint, endDate: Date | number | bigint): string; - formatRangeToParts(startDate: Date | number | bigint, endDate: Date | number | bigint): DateTimeFormatPart[]; + formatRangeToParts(startDate: Date | number | bigint, endDate: Date | number | bigint): DateTimeRangeFormatPart[]; } interface ResolvedDateTimeFormatOptions { @@ -39,7 +47,7 @@ declare namespace Intl { timeStyle?: "full" | "long" | "medium" | "short"; hourCycle?: "h11" | "h12" | "h23" | "h24"; dayPeriod?: "narrow" | "short" | "long"; - fractionalSecondDigits?: 0 | 1 | 2 | 3; + fractionalSecondDigits?: 1 | 2 | 3; } /** diff --git a/tsserver/lib.es2022.d.ts b/tsserver/lib.es2022.d.ts index 6d4283d2..83eb960c 100644 --- a/tsserver/lib.es2022.d.ts +++ b/tsserver/lib.es2022.d.ts @@ -23,4 +23,5 @@ and limitations under the License. /// /// /// +/// /// diff --git a/tsserver/lib.es2022.error.d.ts b/tsserver/lib.es2022.error.d.ts index d97525dc..4b16e091 100644 --- a/tsserver/lib.es2022.error.d.ts +++ b/tsserver/lib.es2022.error.d.ts @@ -19,11 +19,11 @@ and limitations under the License. interface ErrorOptions { - cause?: Error; + cause?: unknown; } interface Error { - cause?: Error; + cause?: unknown; } interface ErrorConstructor { diff --git a/tsserver/lib.es2022.sharedmemory.d.ts b/tsserver/lib.es2022.sharedmemory.d.ts new file mode 100644 index 00000000..43b9b88d --- /dev/null +++ b/tsserver/lib.es2022.sharedmemory.d.ts @@ -0,0 +1,27 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface Atomics { + /** + * A non-blocking, asynchronous version of wait which is usable on the main thread. + * Waits asynchronously on a shared memory location and returns a Promise + */ + waitAsync(typedArray: BigInt64Array | Int32Array, index: number, value: bigint, timeout?: number): { async: false, value: "ok" | "not-equal" | "timed-out" } | { async: true, value: Promise<"ok" | "not-equal" | "timed-out"> }; +} diff --git a/tsserver/lib.es5.d.ts b/tsserver/lib.es5.d.ts index d45132b5..28ca95ab 100644 --- a/tsserver/lib.es5.d.ts +++ b/tsserver/lib.es5.d.ts @@ -933,12 +933,24 @@ interface DateConstructor { declare var Date: DateConstructor; interface RegExpMatchArray extends Array { + /** + * The index of the search at which the result was found. + */ index?: number; + /** + * A copy of the search string. + */ input?: string; } interface RegExpExecArray extends Array { + /** + * The index of the search at which the result was found. + */ index: number; + /** + * A copy of the search string. + */ input: string; } @@ -1584,7 +1596,7 @@ type Omit = Pick>; /** * Exclude null and undefined from T */ -type NonNullable = T extends null | undefined ? never : T; +type NonNullable = T & {}; /** * Obtain the parameters of a function type in a tuple diff --git a/tsserver/lib.esnext.intl.d.ts b/tsserver/lib.esnext.intl.d.ts index 95467945..0eaac02b 100644 --- a/tsserver/lib.esnext.intl.d.ts +++ b/tsserver/lib.esnext.intl.d.ts @@ -19,8 +19,12 @@ and limitations under the License. declare namespace Intl { + interface NumberRangeFormatPart extends NumberFormatPart { + source: "startRange" | "endRange" | "shared" + } + interface NumberFormat { formatRange(start: number | bigint, end: number | bigint): string; - formatRangeToParts(start: number | bigint, end: number | bigint): NumberFormatPart[]; + formatRangeToParts(start: number | bigint, end: number | bigint): NumberRangeFormatPart[]; } } diff --git a/tsserver/lib.webworker.d.ts b/tsserver/lib.webworker.d.ts index 6f9a2eaf..30f83bc8 100644 --- a/tsserver/lib.webworker.d.ts +++ b/tsserver/lib.webworker.d.ts @@ -271,6 +271,10 @@ interface IDBObjectStoreParameters { keyPath?: string | string[] | null; } +interface IDBTransactionOptions { + durability?: IDBTransactionDurability; +} + interface IDBVersionChangeEventInit extends EventInit { newVersion?: number | null; oldVersion?: number; @@ -496,12 +500,12 @@ interface RTCEncodedVideoFrameMetadata { width?: number; } -interface ReadableStreamDefaultReadDoneResult { +interface ReadableStreamReadDoneResult { done: true; value?: undefined; } -interface ReadableStreamDefaultReadValueResult { +interface ReadableStreamReadValueResult { done: false; value: T; } @@ -1004,6 +1008,7 @@ declare var CustomEvent: { /** An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. */ interface DOMException extends Error { + /** @deprecated */ readonly code: number; readonly message: string; readonly name: string; @@ -1466,7 +1471,7 @@ declare var EventTarget: { /** Extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. */ interface ExtendableEvent extends Event { - waitUntil(f: any): void; + waitUntil(f: Promise): void; } declare var ExtendableEvent: { @@ -1801,7 +1806,7 @@ interface IDBDatabase extends EventTarget { */ deleteObjectStore(name: string): void; /** Returns a new transaction with the given mode ("readonly" or "readwrite") and scope which can be a single object store name or an array of names. */ - transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction; + transaction(storeNames: string | string[], mode?: IDBTransactionMode, options?: IDBTransactionOptions): IDBTransaction; addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -2287,7 +2292,6 @@ interface NavigatorID { readonly appName: string; /** @deprecated */ readonly appVersion: string; - /** @deprecated */ readonly platform: string; /** @deprecated */ readonly product: string; @@ -2304,10 +2308,6 @@ interface NavigatorLocks { readonly locks: LockManager; } -interface NavigatorNetworkInformation { - readonly connection: NetworkInformation; -} - interface NavigatorOnLine { readonly onLine: boolean; } @@ -2317,15 +2317,6 @@ interface NavigatorStorage { readonly storage: StorageManager; } -interface NetworkInformation extends EventTarget { - readonly type: ConnectionType; -} - -declare var NetworkInformation: { - prototype: NetworkInformation; - new(): NetworkInformation; -}; - interface NotificationEventMap { "click": Event; "close": Event; @@ -2658,6 +2649,7 @@ declare var PushMessageData: { */ interface PushSubscription { readonly endpoint: string; + readonly expirationTime: EpochTimeStamp | null; readonly options: PushSubscriptionOptions; getKey(name: PushEncryptionKeyName): ArrayBuffer | null; toJSON(): PushSubscriptionJSON; @@ -2702,6 +2694,19 @@ declare var RTCEncodedVideoFrame: { new(): RTCEncodedVideoFrame; }; +interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(e?: any): void; +} + +declare var ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; +}; + /** This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. */ interface ReadableStream { readonly locked: boolean; @@ -2717,6 +2722,27 @@ declare var ReadableStream: { new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; +interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + read(view: ArrayBufferView): Promise>; + releaseLock(): void; +} + +declare var ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; +}; + +interface ReadableStreamBYOBRequest { + readonly view: ArrayBufferView | null; + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBufferView): void; +} + +declare var ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; +}; + interface ReadableStreamDefaultController { readonly desiredSize: number | null; close(): void; @@ -2730,7 +2756,7 @@ declare var ReadableStreamDefaultController: { }; interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { - read(): Promise>; + read(): Promise>; releaseLock(): void; } @@ -2899,6 +2925,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { onnotificationclose: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; onpush: ((this: ServiceWorkerGlobalScope, ev: PushEvent) => any) | null; readonly registration: ServiceWorkerRegistration; + readonly serviceWorker: ServiceWorker; skipWaiting(): Promise; addEventListener(type: K, listener: (this: ServiceWorkerGlobalScope, ev: ServiceWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -2981,11 +3008,11 @@ declare var StorageManager: { * Available only in secure contexts. */ interface SubtleCrypto { - decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise; digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; - encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; exportKey(format: "jwk", key: CryptoKey): Promise; exportKey(format: Exclude, key: CryptoKey): Promise; generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray): Promise; @@ -5278,8 +5305,8 @@ interface WindowOrWorkerGlobalScope { readonly performance: Performance; atob(data: string): string; btoa(data: string): string; - clearInterval(id?: number): void; - clearTimeout(id?: number): void; + clearInterval(id: number | undefined): void; + clearTimeout(id: number | undefined): void; createImageBitmap(image: ImageBitmapSource, options?: ImageBitmapOptions): Promise; createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; fetch(input: RequestInfo | URL, init?: RequestInit): Promise; @@ -5371,7 +5398,7 @@ declare var WorkerLocation: { }; /** A subset of the Navigator interface allowed to be accessed from a Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.navigator property obtained by calling window.self.navigator. */ -interface WorkerNavigator extends NavigatorConcurrentHardware, NavigatorID, NavigatorLanguage, NavigatorLocks, NavigatorNetworkInformation, NavigatorOnLine, NavigatorStorage { +interface WorkerNavigator extends NavigatorConcurrentHardware, NavigatorID, NavigatorLanguage, NavigatorLocks, NavigatorOnLine, NavigatorStorage { readonly mediaCapabilities: MediaCapabilities; } @@ -5395,6 +5422,7 @@ declare var WritableStream: { /** This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. */ interface WritableStreamDefaultController { + readonly signal: AbortSignal; error(e?: any): void; } @@ -5818,8 +5846,8 @@ declare var origin: string; declare var performance: Performance; declare function atob(data: string): string; declare function btoa(data: string): string; -declare function clearInterval(id?: number): void; -declare function clearTimeout(id?: number): void; +declare function clearInterval(id: number | undefined): void; +declare function clearTimeout(id: number | undefined): void; declare function createImageBitmap(image: ImageBitmapSource, options?: ImageBitmapOptions): Promise; declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; @@ -5859,7 +5887,7 @@ type GLsizeiptr = number; type GLuint = number; type GLuint64 = number; type HashAlgorithmIdentifier = AlgorithmIdentifier; -type HeadersInit = string[][] | Record | Headers; +type HeadersInit = [string, string][] | Record | Headers; type IDBValidKey = number | string | Date | BufferSource | IDBValidKey[]; type ImageBitmapSource = CanvasImageSource | Blob | ImageData; type Int32List = Int32Array | GLint[]; @@ -5869,7 +5897,7 @@ type OnErrorEventHandler = OnErrorEventHandlerNonNull | null; type PerformanceEntryList = PerformanceEntry[]; type PushMessageDataInit = BufferSource | string; type ReadableStreamController = ReadableStreamDefaultController; -type ReadableStreamDefaultReadResult = ReadableStreamDefaultReadValueResult | ReadableStreamDefaultReadDoneResult; +type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; type ReadableStreamReader = ReadableStreamDefaultReader; type RequestInfo = Request | string; type TexImageSource = ImageBitmap | ImageData | OffscreenCanvas; @@ -5882,7 +5910,6 @@ type BinaryType = "arraybuffer" | "blob"; type ClientTypes = "all" | "sharedworker" | "window" | "worker"; type ColorGamut = "p3" | "rec2020" | "srgb"; type ColorSpaceConversion = "default" | "none"; -type ConnectionType = "bluetooth" | "cellular" | "ethernet" | "mixed" | "none" | "other" | "unknown" | "wifi"; type DocumentVisibilityState = "hidden" | "visible"; type EndingType = "native" | "transparent"; type FileSystemHandleKind = "directory" | "file"; diff --git a/tsserver/lib.webworker.iterable.d.ts b/tsserver/lib.webworker.iterable.d.ts index af258815..3d9e75d0 100644 --- a/tsserver/lib.webworker.iterable.d.ts +++ b/tsserver/lib.webworker.iterable.d.ts @@ -59,7 +59,7 @@ interface Headers { interface IDBDatabase { /** Returns a new transaction with the given mode ("readonly" or "readwrite") and scope which can be a single object store name or an array of names. */ - transaction(storeNames: string | Iterable, mode?: IDBTransactionMode): IDBTransaction; + transaction(storeNames: string | Iterable, mode?: IDBTransactionMode, options?: IDBTransactionOptions): IDBTransaction; } interface IDBObjectStore { diff --git a/tsserver/pl/diagnosticMessages.generated.json b/tsserver/pl/diagnosticMessages.generated.json index bff4cd6b..8523a81e 100644 --- a/tsserver/pl/diagnosticMessages.generated.json +++ b/tsserver/pl/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Typ „this” jest dostępny tylko w niestatycznej składowej klasy lub interfejsu.", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Plik „tsconfig.json” jest już zdefiniowany w: „{0}”.", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Składowa krotki nie może być jednocześnie opcjonalna i typu rest.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Nie można indeksować typu krotki z wartością ujemną.", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Wyrażenie asercji typu jest niedozwolone po lewej stronie wyrażenia potęgowania. Zastanów się nad zamknięciem wyrażenia w nawiasach.", "A_type_literal_property_cannot_have_an_initializer_1247": "Właściwość literału typu nie może mieć inicjatora.", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Import dotyczący tylko typu może określać import domyślny lub powiązania nazwane, ale nie jedno i drugie jednocześnie.", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "Dodaj asercję określonego przypisania do właściwości „{0}”", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Dodaj asercję określonego przypisania do wszystkich niezainicjowanych właściwości", "Add_export_to_make_this_file_into_a_module_95097": "Dodaj element „export {}”, aby przekształcić ten plik w moduł", + "Add_extends_constraint_2211": "Dodaj ograniczenie „rozszerzeń”.", + "Add_extends_constraint_to_all_type_parameters_2212": "Dodaj ograniczenie „rozszerzeń” do wszystkich parametrów typu", "Add_import_from_0_90057": "Dodaj import z „{0}”", "Add_index_signature_for_property_0_90017": "Dodaj sygnaturę indeksu dla właściwości „{0}”", "Add_initializer_to_property_0_95019": "Dodaj inicjator do właściwości „{0}”", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "Parametr sygnatury indeksu musi mieć adnotację typu.", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Typ parametru sygnatury indeksu nie może być typem literału ani typem ogólnym. Rozważ użycie zamiast tego mapowanego typu obiektu.", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Parametr sygnatury indeksu musi mieć typ „string”, „number” lub „symbol” albo typ literału szablonu.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Po wyrażeniu tworzenia wystąpienia nie może następować dostęp do właściwości.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Interfejs może rozszerzać tylko identyfikator/nazwę kwalifikowaną z opcjonalnymi argumentami typu.", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Interfejs może rozszerzać tylko typ obiektu lub część wspólną typów obiektów ze statycznie znanymi elementami członkowskimi.", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "Interfejs nie może rozszerzyć typu pierwotnego, takiego jak „{0}”; interfejs może rozszerzać tylko nazwane typy i klasy", "An_interface_property_cannot_have_an_initializer_1246": "Właściwość interfejsu nie może mieć inicjatora.", "An_iterator_must_have_a_next_method_2489": "Iterator musi zawierać metodę „next()”.", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "W przypadku używania dyrektywy pragma @jsx z fragmentami JSX jest wymagana dyrektywa pragma @jsxFrag.", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Klasa „{0}” niepoprawnie implementuje klasę „{1}”. Czy chodziło o rozszerzenie „{1}” i odziedziczenie jego elementów członkowskich jako podklasy?", "Class_0_incorrectly_implements_interface_1_2420": "Klasa „{0}” zawiera niepoprawną implementację interfejsu „{1}”.", "Class_0_used_before_its_declaration_2449": "Klasa „{0}” została użyta przed zadeklarowaniem.", + "Class_constructor_may_not_be_a_generator_1360": "Konstruktor klas nie może być generatorem.", + "Class_constructor_may_not_be_an_accessor_1341": "Konstruktor klas nie może być metodą dostępu.", "Class_declaration_cannot_implement_overload_list_for_0_2813": "Deklaracja klasy nie może implementować listy przeciążeń dla elementu \"{0}\".", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Deklaracje klas nie mogą mieć więcej niż jeden tag \"@augments\" lub \"@extends\".", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Dekoratorów klas nie można używać ze statycznym identyfikatorem prywatnym. Rozważ usunięcie eksperymentalnego dekoratora.", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "Nie można odnaleźć pliku '{0}'.", "File_Management_6245": "Zarządzanie plikami", "File_change_detected_Starting_incremental_compilation_6032": "Wykryto zmianę pliku. Trwa rozpoczynanie kompilacji przyrostowej...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "Plik jest modułem CommonJS, ponieważ element „{0}” nie ma pola „type”", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "Plik jest modułem CommonJS, ponieważ element „{0}” ma pole „type”, którego wartość nie jest „module”", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "Plik jest modułem CommonJS, ponieważ nie znaleziono pliku „package.json”", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "Plik jest modułem ECMAScript, ponieważ element „{0}” ma pole „type” z wartością „module”", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Plik jest modułem CommonJS; może zostać przekonwertowany na moduł ES.", "File_is_default_library_for_target_specified_here_1426": "Plik to domyślna biblioteka dla elementu docelowego określonego w tym miejscu.", "File_is_entry_point_of_type_library_specified_here_1419": "Plik to punkt wejścia biblioteki typów określonej w tym miejscu.", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Oczekiwano identyfikatora. „{0}” jest słowem zastrzeżonym, którego nie można użyć w tym miejscu.", "Identifier_expected_1003": "Oczekiwano identyfikatora.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Oczekiwano identyfikatora. Ciąg „__esModule” jest zastrzeżony jako eksportowany znacznik podczas transformowania modułów ECMAScript.", + "Identifier_or_string_literal_expected_1478": "Oczekiwano identyfikatora lub literału ciągu.", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Jeśli pakiet \"{0}\" faktycznie udostępnia ten moduł, rozważ wysłanie żądania ściągnięcia w celu zmiany elementu \"https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}\"", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Jeśli pakiet „{0}” rzeczywiście uwidacznia ten moduł, spróbuj dodać nowy plik deklaracji (.d.ts) zawierający „declare module”{1}';`", "Ignore_this_error_message_90019": "Ignoruj ten komunikat o błędzie", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "Nieprawidłowy specyfikator importu „{0}” nie ma możliwych rozwiązań.", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nieprawidłowa nazwa modułu w rozszerzeniu. Moduł „{0}” jest rozpoznawany jako moduł bez typu na poziomie „{1}”, którego nie można rozszerzyć.", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nieprawidłowa nazwa modułu w rozszerzeniu. Nie można znaleźć modułu „{0}”.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Nieprawidłowy opcjonalny łańcuch z nowego wyrażenia. Czy chodziło Ci o wywołanie „{0}()”?", "Invalid_reference_directive_syntax_1084": "Nieprawidłowa składnia dyrektywy „reference”.", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Nieprawidłowe użycie elementu \"{0}\". Nie można go użyć wewnątrz bloku statycznego klasy.", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Nieprawidłowe użycie elementu „{0}”. Moduły są określane automatycznie w trybie z ograniczeniami.", @@ -893,6 +906,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_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}”.", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "Element członkowski „{0}” niejawnie ma typ „{1}”, ale lepszy typ można wywnioskować na podstawie użycia.", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Nie można skompilować projektu „{0}”, ponieważ jego zależność „{1}” zawiera błędy", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Nie można skompilować projektu „{0}”, ponieważ jego zależność „{1}” nie została skompilowania", "Project_0_is_being_forcibly_rebuilt_6388": "Trwa wymuszone odbudowanie projektu „{0}”", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "Projekt „{0}” jest nieaktualny, ponieważ plik buildinfo „{1}” wskazuje, że niektóre zmiany nie zostały wyemitowane", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Projekt „{0}” jest nieaktualny, ponieważ jego zależność „{1}” jest nieaktualna", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Projekt „{0}” jest nieaktualny, ponieważ najstarsze dane wyjściowe „{1}” są starsze niż najnowsze dane wejściowe „{2}”", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "Projekt „{0}” jest nieaktualny, ponieważ dane wyjściowe „{1}” są starsze niż dane wejściowe „{2}”", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Projekt „{0}” jest nieaktualny, ponieważ plik wyjściowy „{1}” nie istnieje", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "Projekt „{0}” jest nieaktualny, ponieważ jego dane wyjściowe zostały wygenerowane w wersji „{1}”, która różni się od bieżącej wersji „{2}”", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "Projekt „{0}” jest nieaktualny, ponieważ dane wyjściowe jego zależności „{1}” uległy zmianie", "Project_0_is_up_to_date_6361": "Projekt „{0}” jest aktualny", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Projekt „{0}” jest aktualny, ponieważ najnowsze dane wejściowe „{1}” są starsze niż najstarsze dane wyjściowe „{2}”", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "Projekt „{0}” jest aktualny, ponieważ najnowsze dane wejściowe „{1}” są starsze niż dane wyjściowe „{2}”", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "Projekt „{0}” jest aktualny, ale musi zaktualizować sygnatury czasowe plików wyjściowych, które są starsze niż pliki wejściowe", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Projekt „{0}” jest aktualny z plikami .d.ts z jego zależności", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odwołania do projektu nie mogą tworzyć grafu kołowego. Wykryto cykl: {0}", "Projects_6255": "Projekty", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Wymagane parametry typu mogą nie być zgodne z opcjonalnymi parametrami typu.", "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}”.", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Tryby rozdzielczości są obsługiwane tylko wtedy, gdy element „moduleResolution” ma wartość „node16” lub „nodenext”.", "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_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}”.", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Modyfikatora „type” nie można użyć w nazwanym eksporcie, gdy w instrukcji eksportowania jest używany element „export type”.", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "Modyfikatora „type” nie można użyć w nazwanym imporcie, gdy w instrukcji importowania jest używany element „import type”.", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "Typ deklaracji funkcji musi być zgodny z sygnaturą funkcji.", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "Nie można nazwać typu tego wyrażenia bez asercji „resolution-mode”, która jest niestabilną funkcją. Aby wyciszyć ten błąd, użyj nocnego języka TypeScript. Spróbuj zaktualizować przy użyciu polecenia „npm install -D typescript@next”.", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "Typ tego węzła nie może być serializowany, ponieważ jego właściwość „{0}” nie może być serializowana.", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Typ zwracany przez metodę „{0}()” iteratora asynchronicznego musi być obietnicą dla typu z właściwością „value”.", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Typ zwracany przez metodę „{0}()” iteratora musi mieć właściwość „value”.", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Instrukcja „with” nie jest obsługiwana. Wszystkie symbole w bloku „with” będą mieć typ „any”.", "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_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_0_since_the_types_1_and_2_have_no_overlap_2367": "Ten warunek będzie zawsze zwracał element „{0}”, ponieważ typy „{1}” i „{2}” nie nakładają się.", "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?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Ta składnia wymaga zaimportowanego pomocnika, ale nie można znaleźć modułu „{0}”.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Ta składnia wymaga zaimportowanego pomocnika o nazwie „{1}”, który nie istnieje w elemencie „{0}”. Rozważ uaktualnienie wersji „{0}”.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Ta składnia wymaga zaimportowanego pomocnika o nazwie „{1}” z parametrami {2}, który nie jest zgodny z tym w elemencie „{0}”. Rozważ uaktualnienie wersji elementu „{0}”.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Ten parametr typu może wymagać ograniczenia „rozszerzeń{0}”.", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "To użycie elementu „import” jest nieprawidłowe. Wywołania „import()” mogą być zapisywane, ale muszą mieć nawiasy i nie mogą mieć argumentów typu.", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Wyrażenia „await” najwyższego poziomu są dozwolone tylko wtedy, gdy opcja „module” jest ustawiona na wartość „es2022”, „esnext”, „system”, „node16” lub „nodenext”, a opcja „target” jest ustawiona na wartość „es2017” lub wyższą.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Deklaracje najwyższego poziomu w plikach .d.ts muszą rozpoczynać się od modyfikatora „declare” lub „export”.", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Biblioteka typów jest przywoływana za pośrednictwem elementu „{0}” z pliku „{1}” o identyfikatorze packageId „{2}”", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Typ operandu „await” musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Typ wartości właściwości obliczanej to „{0}”, którego nie można przypisać do typu „{1}”.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "Typ zmiennej składowej wystąpienia „{0}” nie może odwoływać się do identyfikatora „{1}” zadeklarowanego w konstruktorze.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterowanych elementów operandu „yield*” musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Typ właściwości „{0}” cyklicznie odwołuje się do siebie w zamapowanym typie „{1}”.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu „yield” w generatorze asynchronicznym musi być prawidłową obietnicą lub nie może zawierać wywoływalnej składowej „then”.", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== Dyrektywa odwołania do typu „{0}” nie została rozpoznana. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Dyrektywa odwołania do typu „{0}” została pomyślnie rozpoznana jako „{1}”, podstawowe: {2}. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== Dyrektywa odwołania do typu „{0}” została pomyślnie rozpoznana jako „{1}” z identyfikatorem pakietu „{2}”, podstawowe: {3}. ========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Typy nie mogą występować w deklaracjach eksportu w plikach JavaScript.", "Types_have_separate_declarations_of_a_private_property_0_2442": "Typy mają osobne deklaracje właściwości prywatnej „{0}”.", "Types_of_construct_signatures_are_incompatible_2419": "Typy sygnatur konstrukcji są niezgodne.", "Types_of_parameters_0_and_1_are_incompatible_2328": "Typy parametrów „{0}” i „{1}” są niezgodne.", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "Tryb wyrażeń kontrolnych i kompilowania", "Watch_input_files_6005": "Obserwuj pliki wejściowe.", "Watch_option_0_requires_a_value_of_type_1_5080": "Opcja obserwowania „{0}” wymaga wartości typu {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Możemy napisać typ tylko dla elementu „{0}”, dodając typ dla całego parametru w tym miejscu.", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Podczas przypisywania funkcji upewnij się, że parametry i zwracane wartości są zgodne pod względem podtypów.", "When_type_checking_take_into_account_null_and_undefined_6699": "Podczas sprawdzania typów uwzględniaj wartości „null” i „undefined”.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Określa, czy zachować nieaktualne dane wyjściowe konsoli w trybie śledzenia zamiast wyczyścić ekran.", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Zawijaj następującą treść z nawiasami, która powinna być literałem obiektu", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "O wszystkich opcjach kompilatora przeczytasz na stronie {0}", "You_cannot_rename_a_module_via_a_global_import_8031": "Nie można zmienić nazwy modułu za pomocą importu globalnego.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Nie można zmieniać nazw elementów zdefiniowanych w folderze „node_modules”.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Nie można zmieniać nazw elementów zdefiniowanych w innym folderze „node_modules”.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nie można zmienić nazw elementów zdefiniowanych w standardowej bibliotece TypeScript.", "You_cannot_rename_this_element_8000": "Nie można zmienić nazwy tego elementu.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Element „{0}” akceptuje za mało argumentów, aby można go było użyć w tym miejscu jako dekorator. Czy chcesz najpierw go wywołać i zapisać tag „@{0}()”?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "Sygnatury indeksów „{0}” są niezgodne.", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "Typu indeksu „{0}” „{1}” nie można przypisać do typu indeksu „{2}” „{3}”.", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "Element „{0}” jest elementem podstawowym, ale element „{1}” jest obiektem otoki. Preferuje się użycie elementu „{0}”, jeśli jest to możliwe.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "„{0}” jest typem i nie można go zaimportować w plikach JavaScript. Użyj elementu „{1}” w adnotacji typu JSDoc.", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "Element \"{0}\" jest typem i musi być importowany przy użyciu importu tylko typu, gdy są włączone opcje \"preserveValueImports\" i \"isolatedModules\".", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "„{0}” to nieużywana zmiana nazwy elementu „{1}”. Czy zamierzano używać go jako adnotacji typu?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "Element „{0}” można przypisać do ograniczenia typu „{1}”, ale wystąpienie typu „{1}” można utworzyć z innym podtypem ograniczenia „{2}”.", + "_0_is_automatically_exported_here_18044": "W tym miejscu jest automatycznie eksportowany element „{0}”.", "_0_is_declared_but_its_value_is_never_read_6133": "Element „{0}” jest zadeklarowany, ale jego wartość nie jest nigdy odczytywana.", "_0_is_declared_but_never_used_6196": "Element „{0}” jest zadeklarowany, ale nie jest nigdy używany.", "_0_is_declared_here_2728": "Element „{0}” jest zadeklarowany tutaj.", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "jeden z:", "one_or_more_Colon_6901": "co najmniej jeden:", "options_6024": "opcje", + "or_JSX_element_expected_1145": "Oczekiwano elementu „{” lub JSX.", "or_expected_1144": "Oczekiwano znaku „{” lub „;”.", "package_json_does_not_have_a_0_field_6100": "Plik „package.json” nie zawiera pola „{0}”.", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "Plik „package.json” nie zawiera wpisu „typesVersions” odpowiadającego wersji „{0}”.", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modyfikator „readonly” może występować jedynie w deklaracji właściwości lub sygnaturze indeksu.", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "Modyfikator typu „readonly” jest dozwolony tylko w typach literału tablicy i krotki.", "require_call_may_be_converted_to_an_import_80005": "Wywołanie „require” może zostać przekonwertowane na wywołanie import.", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Asercje „resolution-mode” są obsługiwane tylko wtedy, gdy element „moduleResolution” ma wartość „node16” lub „nodenext”.", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "Asercje „resolution-mode” są niestabilne. Użyj nocnego języka TypeScript, aby wyciszyć ten błąd. Spróbuj zaktualizować za pomocą polecenia „npm install -D typescript@next”.", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "Element „resolution-mode“ można ustawić wyłącznie dla importów tylko typów.", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "Element „resolution-mode“ jest jedynym prawidłowym kluczem dla twierdzenia importu typu.", "resolution_mode_should_be_either_require_or_import_1453": "Element „resolution-mode” powinien mieć wartość „require” lub „import”.", diff --git a/tsserver/protocol.d.ts b/tsserver/protocol.d.ts index 4407b6bf..44e76da5 100644 --- a/tsserver/protocol.d.ts +++ b/tsserver/protocol.d.ts @@ -2699,9 +2699,11 @@ declare namespace ts.server.protocol { readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; readonly includeInlayFunctionParameterTypeHints?: boolean; readonly includeInlayVariableTypeHints?: boolean; + readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; readonly includeInlayPropertyDeclarationTypeHints?: boolean; readonly includeInlayFunctionLikeReturnTypeHints?: boolean; readonly includeInlayEnumMemberValueHints?: boolean; + readonly autoImportFileExcludePatterns?: string[]; } interface CompilerOptions { allowJs?: boolean; diff --git a/tsserver/pt-br/diagnosticMessages.generated.json b/tsserver/pt-br/diagnosticMessages.generated.json index 410dde0d..269fbc9d 100644 --- a/tsserver/pt-br/diagnosticMessages.generated.json +++ b/tsserver/pt-br/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Um tipo 'this' está disponível somente em um membro não estático de uma classe ou interface.", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Um arquivo 'tsconfig.json' já está definido em: '{0}'.", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Um membro de tupla não pode ser opcional e rest.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Um tipo de tupla não pode ser indexado com um valor negativo.", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Uma expressão de asserção de tipo não é permitida no lado esquerdo de uma expressão de exponenciação. Considere delimitar a expressão em parênteses.", "A_type_literal_property_cannot_have_an_initializer_1247": "Uma propriedade literal de tipo não pode ter um inicializador.", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Uma importação somente de tipo pode especificar uma importação padrão ou associações nomeadas, mas não ambos.", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "Adicionar a asserção de atribuição definitiva à propriedade '{0}'", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Adicionar declarações de atribuição definidas a todas as propriedades não inicializadas", "Add_export_to_make_this_file_into_a_module_95097": "Adicionar 'export {}' para transformar este arquivo em um módulo", + "Add_extends_constraint_2211": "Adicione a restrição `extends`.", + "Add_extends_constraint_to_all_type_parameters_2212": "Adicionar a restrição `extends` a todos os parâmetros de tipo", "Add_import_from_0_90057": "Adicionar importação de \"{0}\"", "Add_index_signature_for_property_0_90017": "Adicionar assinatura de índice para a propriedade '{0}'", "Add_initializer_to_property_0_95019": "Adicionar inicializador à propriedade '{0}'", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "Um parâmetro de assinatura de índice deve ter uma anotação de tipo.", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Um tipo de parâmetro de assinatura de índice não pode ser um tipo literal ou genérico. Considere usar um tipo de objeto mapeado.", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Um tipo de parâmetro de assinatura de índice deve ser 'cadeia de caracteres', 'número', 'símbolo' ou um tipo literal de modelo.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Uma expressão de instanciação não pode ser seguida por um acesso de propriedade.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Uma interface só pode estender um identificador/nome qualificado com argumentos de tipo opcionais.", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Uma interface só pode estender um tipo de objeto ou interseção de tipos de objeto com membros estaticamente conhecidos.", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "Uma interface não pode estender um tipo primitivo como '{0}'; uma interface só pode estender tipos e classes nomeados", "An_interface_property_cannot_have_an_initializer_1246": "Uma propriedade de interface não pode ter um inicializador.", "An_iterator_must_have_a_next_method_2489": "Um iterador deve ter um método 'next()'.", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "Um pragma @jsxFrag é necessário ao usar um pragma @jsx com fragmentos JSX.", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "A classe '{0}' implementa incorretamente a classe '{1}'. Você pretendia estender '{1}' e herdar seus membros como uma subclasse?", "Class_0_incorrectly_implements_interface_1_2420": "A classe '{0}' implementa incorretamente a interface '{1}'.", "Class_0_used_before_its_declaration_2449": "Classe '{0}' usada antes de sua declaração.", + "Class_constructor_may_not_be_a_generator_1360": "O construtor de classe não pode ser um gerador.", + "Class_constructor_may_not_be_an_accessor_1341": "O construtor de classe não pode ser um acessador.", "Class_declaration_cannot_implement_overload_list_for_0_2813": "A declaração da classe não pode implementar a lista de sobrecarga para '{0}'.", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "As declarações de classe não podem ter mais de uma marca '@augments' ou '@extends'.", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Os decoradores de classe não podem ser usados com um identificador privado estático. Considere remover o decorador experimental.", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "Arquivo '{0}' não encontrado.", "File_Management_6245": "Gerenciamento de Arquivos", "File_change_detected_Starting_incremental_compilation_6032": "Alteração do arquivo detectada. Iniciando compilação incremental...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "O arquivo é um módulo CommonJS porque '{0}' não tem o campo \"type\"", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "O arquivo é o módulo CommonJS porque '{0}' tem o campo \"type\" cujo valor não é \"module\"", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "O arquivo é um módulo CommonJS porque 'package.json' não foi encontrado", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "O arquivo é o módulo ECMAScript porque '{0}' tem o campo \"type\" com o valor \"module\"", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "O arquivo é um módulo CommonJS; ele pode ser convertido em um módulo ES.", "File_is_default_library_for_target_specified_here_1426": "O arquivo é a biblioteca padrão para o destino especificado aqui.", "File_is_entry_point_of_type_library_specified_here_1419": "O arquivo é o ponto de entrada da biblioteca de tipos especificada aqui.", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Identificador esperado. '{0}' é uma palavra reservada que não pode ser usada aqui.", "Identifier_expected_1003": "Identificador esperado.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificador esperado. '__esModule' é reservado como um marcador exportado ao transformar os módulos ECMAScript.", + "Identifier_or_string_literal_expected_1478": "Identificador ou literal de cadeia de caracteres esperado.", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Se o pacote '{0}' realmente expõe este módulo, considere enviar uma solicitação de pull para corrigir 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Se o pacote '{0}' realmente expõe este módulo, tente adicionar um novo arquivo de declaração (.d.ts) contendo o módulo `declare '{1}';`", "Ignore_this_error_message_90019": "Ignorar essa mensagem de erro", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "O especificador de importação inválido '{0}' não tem resoluções possíveis.", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Nome de módulo inválido no aumento. O módulo '{0}' resolve para um módulo não tipado em '{1}', que não pode ser aumentado.", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Nome de módulo inválido em acréscimo, o módulo '{0}' não pôde ser encontrado.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Cadeia opcional inválida da nova expressão. Você quis dizer chamar '{0}()'?", "Invalid_reference_directive_syntax_1084": "Sintaxe de diretiva 'reference' inválida.", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Uso inválido de “{0}”. Ele não pode ser usado dentro de um bloco estático de classe.", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Uso inválido de '{0}'. Os módulos ficam automaticamente em modo estrito.", @@ -893,6 +906,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_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}'.", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "O membro '{0}' implicitamente tem um tipo '{1}', mas um tipo melhor pode ser inferido do uso.", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "O projeto '{0}' não pode ser compilado porque sua dependência '{1}' tem erros", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "O projeto '{0}' não pode ser criado porque sua dependência '{1}' não foi criada", "Project_0_is_being_forcibly_rebuilt_6388": "O projeto '{0}' está sendo reconstruído forçadamente", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "O projeto '{0}' está desatualizado porque o arquivo buildinfo '{1}' indica que algumas das alterações não foram emitidas", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "O projeto '{0}' está desatualizado porque sua dependência '{1}' está desatualizada", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "O projeto '{0}' está desatualizado porque a saída mais antiga '{1}' é mais antiga que a entrada mais recente '{2}'", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "O projeto '{0}' está desatualizado porque a saída '{1}' é mais antiga que a entrada '{2}'", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "O projeto '{0}' está desatualizado porque o arquivo de saída '{1}' não existe", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "O projeto '{0}' está desatualizado porque a saída foi gerada com a versão '{1}' que difere da versão atual '{2}'", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "O projeto '{0}' está desatualizado porque a saída de sua dependência '{1}' foi alterada", "Project_0_is_up_to_date_6361": "O projeto '{0}' está atualizado", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "O projeto '{0}' está atualizado porque a entrada mais recente '{1}' é mais antiga que a saída mais antiga '{2}'", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "O projeto '{0}' está atualizado porque a entrada mais recente '{1}' é mais antiga que a saída '{2}'", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "O projeto '{0}' está atualizado, mas precisa atualizar os registros de data e hora dos arquivos de saída mais antigos que os arquivos de entrada", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "O projeto '{0}' está atualizado com os arquivos .d.ts de suas dependências", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Referências de projeto não podem formar um gráfico circular. Ciclo detectado: {0}", "Projects_6255": "Projetos", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Os parâmetros de tipo necessários podem não seguir os parâmetros de tipo opcionais.", "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}'.", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Os modos de resolução são suportados apenas quando `moduleResolution` for `node16` ou `nodenext`.", "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_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}'.", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "O modificador “type” não pode ser usado em uma exportação nomeada quando “export type” for usado em sua instrução de exportar.", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "O modificador “type” não pode ser usado em uma importação nomeada quando “import type” for usado em sua instrução de importar.", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "O tipo de uma declaração de função deve corresponder à assinatura da função.", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "O tipo dessa expressão não pode ser nomeado sem uma declaração 'modo de resolução', que é um recurso instável. Use o TypeScript noturno para silenciar esse erro. Tente atualizar com 'npm install -D typescript@next'.", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "O tipo deste nó não pode ser serializado porque sua propriedade '{0}' não pode ser serializada.", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "O tipo retornado pelo método '{0}()' de um iterador assíncrono deve ser uma promessa para um tipo com a propriedade 'value'.", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "O tipo retornado pelo método '{0}()' de um iterador deve ter uma propriedade 'value'.", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "A instrução \"with\" não tem suporte. Todos os símbolos em um bloco \"with\" terão o tipo \"any\".", "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_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_0_since_the_types_1_and_2_have_no_overlap_2367": "Essa condição sempre retornará '{0}', pois os tipos '{1}' e '{2}' não têm nenhuma sobreposição.", "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?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Essa sintaxe requer um auxiliar importado, mas o módulo '{0}' não pode ser encontrado.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Esta sintaxe requer um auxiliar importado chamado '{1}' que não existe em '{0}'. Considere atualizar sua versão do '{0}'.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Esta sintaxe exige um auxiliar importado nomeado como '{1}' com parâmetros {2}, o que não é compatível com o que está em '{0}'. Considere atualizar sua versão do '{0}'.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Este parâmetro de tipo pode precisar de uma restrição `extends {0}`.", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Este uso de 'importar' é inválido. Chamadas 'import()' podem ser escritas, mas devem ter parênteses e não podem ter argumentos de tipo.", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "As expressões 'await' de nível superior só são permitidas quando a opção 'module' está definida como 'es2022', 'esnext', 'system', 'node16' ou 'nodenext' e a opção 'target' está definida como ' es2017' ou superior.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "As declarações de nível superior em arquivos .d.ts devem começar com um modificador 'declare' ou 'export'.", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Biblioteca de tipos referenciada via '{0}' do arquivo '{1}' com packageId '{2}'", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "O tipo de operando \"await\" deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "O tipo de valor da propriedade computada é '{0}', que não pode ser atribuído ao tipo '{1}'.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "O tipo de variável '{0}' de membro de instância não pode referenciar o identificador '{1}' declarado no construtor.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "O tipo de elementos iterados de um operando \"yield*\" deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "O tipo de propriedade '{0}' faz referência circular a si mesmo no tipo mapeado '{1}'.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "O tipo do operando \"yield\" em um gerador assíncrono deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== A diretiva de referência de tipo '{0}' não foi resolvida. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== A diretiva de referência de tipo '{0}' foi resolvida com sucesso para '{1}', primário: {2}. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== A diretiva de referência de tipo '{0}' foi resolvida com sucesso para '{1}' com a ID do Pacote '{2}', primário: {3}. ========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Os tipos não podem aparecer em declarações de exportação em arquivos JavaScript.", "Types_have_separate_declarations_of_a_private_property_0_2442": "Tipos têm declarações separadas de uma propriedade privada '{0}'.", "Types_of_construct_signatures_are_incompatible_2419": "Os tipos de assinaturas de constructo são incompatíveis.", "Types_of_parameters_0_and_1_are_incompatible_2328": "Os tipos de parâmetros '{0}' e '{1}' são incompatíveis.", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "Modos Inspeção e Compilação", "Watch_input_files_6005": "Observe os arquivos de entrada.", "Watch_option_0_requires_a_value_of_type_1_5080": "A opção do observador '{0}' requer um valor do tipo {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Só podemos gravar um tipo de '{0}' adicionando um tipo para o parâmetro inteiro aqui.", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "Ao atribuir funções, certifique-se que os parâmetros e os valores de retorno sejam compatíveis com subtipo.", "When_type_checking_take_into_account_null_and_undefined_6699": "Quando a fizer a verificação de tipo, considere 'null' e 'undefined'.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se é necessário manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Colocar entre parênteses o corpo a seguir, que deve ser um literal de objeto", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Você pode aprender sobre todas as opções do compilador em {0}", "You_cannot_rename_a_module_via_a_global_import_8031": "Não é possível renomear um módulo por meio de uma importação global.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Não é possível renomear elementos definidos em uma pasta 'node_modules'.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Não é possível renomear elementos definidos em outra pasta 'node_modules'.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Não é possível renomear elementos que são definidos na biblioteca TypeScript padrão.", "You_cannot_rename_this_element_8000": "Você não pode renomear este elemento.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' aceita muito poucos argumentos para serem usados como um decorador aqui. Você quis dizer para chamá-lo primeiro e gravar '@{0}()'?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "'{0}' assinaturas de índice são incompatíveis.", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "'{0}' tipo de índice '{1}' não pode ser atribuído a '{2}' tipo de índice '{3}'.", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' é um primitivo, mas '{1}' é um objeto de wrapper. Prefira usar '{0}' quando possível.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' é um tipo e não pode ser importado em arquivos JavaScript. Use '{1}' em uma anotação de tipo JSDoc.", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "'{0}' é um tipo e deve ser importado usando uma importação somente de tipo quando 'preserveValueImports' e 'isolatedModules' estiverem habilitados.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}' é uma renomeação não usada de '{1}'. Você pretendia usá-lo como uma anotação de tipo?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}' é atribuível à restrição do tipo '{1}', mas é possível criar uma instância de '{1}' com um subtipo diferente de restrição '{2}'.", + "_0_is_automatically_exported_here_18044": "'{0}' é exportado automaticamente aqui.", "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' é declarado, mas seu valor nunca é lido.", "_0_is_declared_but_never_used_6196": "'{0}' está declarado, mas nunca foi usado.", "_0_is_declared_here_2728": "'{0}' é declarado aqui.", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "um dos:", "one_or_more_Colon_6901": "um ou mais:", "options_6024": "opções", + "or_JSX_element_expected_1145": "'{' ou elemento JSX esperado.", "or_expected_1144": "'{' ou ';' esperado.", "package_json_does_not_have_a_0_field_6100": "'package.json' não tem um campo '{0}'.", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json' não tem uma entrada 'typesVersions' que corresponda à versão '{0}'.", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "O modificador 'readonly' pode aparecer somente em uma declaração de propriedade ou assinatura de índice.", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "O modificador de tipo 'readonly' só é permitido em tipos literais de matriz e tupla.", "require_call_may_be_converted_to_an_import_80005": "A chamada 'require' pode ser convertida em uma importação.", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "asserções de 'modo de resolução' são suportadas apenas quando 'moduleResolution' é 'node16' ou 'nodenext'.", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "asserções de 'modo de resolução' são instáveis. Use o TypeScript noturno para silenciar esse erro. Tente atualizar com 'npm install -D typescript@next'.", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "`resolution-mode` pode ser definido apenas para importações somente de tipo.", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "`resolution-mode` é a única chave válida para as asserções de importação de tipo.", "resolution_mode_should_be_either_require_or_import_1453": "'resolution-mode' deve ser 'require' ou 'import'.", diff --git a/tsserver/ru/diagnosticMessages.generated.json b/tsserver/ru/diagnosticMessages.generated.json index 8fb5288b..e3d29e39 100644 --- a/tsserver/ru/diagnosticMessages.generated.json +++ b/tsserver/ru/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "Тип this доступен только в нестатическом элементе класса или интерфейса.", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "Файл tsconfig.json уже определен в \"{0}\".", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Элемент кортежа не может быть одновременно элементом rest и необязательным элементом.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Тип кортежа нельзя индексировать с отрицательным значением.", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Выражение утверждения типа не допускается в левой части выражения, возводимого в степень. Попробуйте заключить выражение в скобки.", "A_type_literal_property_cannot_have_an_initializer_1247": "Свойство литерала типа не может иметь инициализатор.", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Импорт, затрагивающий только тип, может указывать либо только импорт по умолчанию, либо только именованные привязки.", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного назначения к свойству \"{0}\"", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного назначения ко всем неинициализированным свойствам", "Add_export_to_make_this_file_into_a_module_95097": "Добавить \"export {}\", чтобы превратить этот файл в модуль", + "Add_extends_constraint_2211": "Добавить ограничение \"extends\".", + "Add_extends_constraint_to_all_type_parameters_2212": "Добавить ограничение \"extends\" ко всем параметрам типа", "Add_import_from_0_90057": "Добавить импортировать из \"{0}\"", "Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"", "Add_initializer_to_property_0_95019": "Добавить инициализатор к свойству \"{0}\"", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "У параметра сигнатуры индекса должна быть аннотация типа.", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Тип параметра сигнатуры индекса не может быть типом литерала или универсальным типом. Рекомендуется использовать тип сопоставляемого объекта.", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Тип параметра сигнатуры индекса должен быть строкой, числом, символом или типом литерала шаблона.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "За выражением создания экземпляра не может следовать доступ к свойству.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Интерфейс может расширить только идентификатор или полное имя с дополнительными аргументами типа.", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Интерфейс может расширять только тип объекта или пересечение типов объектов со статическими известными членами.", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "Интерфейс не может расширять примитивный тип, например \"{0}\". Интерфейс может расширять только именованные типы и классы", "An_interface_property_cannot_have_an_initializer_1246": "Свойство интерфейса не может иметь инициализатор.", "An_iterator_must_have_a_next_method_2489": "Итератор должен иметь метод \"next()\".", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "При использовании директивы pragma @jsx с фрагментами JSX требуется директива pragma @jsxFrag.", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Класс \"{0}\" неправильно реализует класс \"{1}\". Вы хотели расширить \"{1}\" и унаследовать его члены в виде подкласса?", "Class_0_incorrectly_implements_interface_1_2420": "Класс \"{0}\" неправильно реализует интерфейс \"{1}\".", "Class_0_used_before_its_declaration_2449": "Класс \"{0}\" использован прежде, чем объявлен.", + "Class_constructor_may_not_be_a_generator_1360": "Конструктор класса не может быть генератором.", + "Class_constructor_may_not_be_an_accessor_1341": "Конструктор класса не может быть методом доступа.", "Class_declaration_cannot_implement_overload_list_for_0_2813": "Объявление класса не может реализовать список перегрузок для \"{0}\".", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "В объявлении класса не может использоваться более одного тега \"@augments\" или \"@extends\".", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Декораторы классов не могут использоваться со статическим частным идентификатором. Попробуйте удалить экспериментальный декоратор.", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "Файл \"{0}\" не найден.", "File_Management_6245": "Управление файлами", "File_change_detected_Starting_incremental_compilation_6032": "Обнаружено изменение в файле. Запускается инкрементная компиляция...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "Файл является модулем CommonJS, так как \"{0}\" не содержит поле \"type\"", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "Файл является модулем CommonJS, так как \"{0}\" содержит поле \"type\", значение которого отличается от \"module\"", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "Файл является модулем CommonJS, так как \"package.json\" не найден", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "Файл является модулем ECMAScript, так как \"{0}\" содержит поле \"type\" со значением \"module\"", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Файл является модулем CommonJS. Его можно преобразовать в модуль ES.", "File_is_default_library_for_target_specified_here_1426": "Файл является библиотекой по умолчанию для указанного здесь целевого объекта.", "File_is_entry_point_of_type_library_specified_here_1419": "Файл является точкой входа для указанной здесь библиотеки типов.", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Ожидается идентификатор. \"{0}\" — это зарезервированное слово, которое не может быть использовано здесь.", "Identifier_expected_1003": "Ожидался идентификатор.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Ожидался идентификатор. Значение \"__esModule\" зарезервировано как экспортируемый маркер при преобразовании модулей ECMAScript.", + "Identifier_or_string_literal_expected_1478": "Ожидался идентификатор или строковый литерал.", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "Если пакет \"{0}\" фактически предоставляет этот модуль, рекомендуется отправить запрос на вытягивание, чтобы изменить \"https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}\"", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "Если пакет \"{0}\" действительно предоставляет этот модуль, попробуйте добавить новый файл объявления (. d. TS), содержащий \"declare module\" \"{1}\";`", "Ignore_this_error_message_90019": "Пропустите это сообщение об ошибке", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "Недопустимый описатель импорта \"{0}\" не имеет возможных разрешений.", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Недопустимое имя модуля в приращении. Модуль \"{0}\" разрешается в модуль без типа в \"{1}\", который невозможно дополнить.", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Недопустимое имя модуля в улучшении, не удается найти модуль \"{0}\".", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Недопустимая необязательная цепочка из нового выражения. Вы хотели вызвать ''{0}()''?", "Invalid_reference_directive_syntax_1084": "Недопустимый синтаксис директивы reference.", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Недопустимое использование \"{0}\". Его нельзя использовать внутри статического блока класса.", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Недопустимое использование \"{0}\". Модули автоматически находятся в строгом режиме.", @@ -893,6 +906,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_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}\".", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "Член \"{0}\" неявно имеет тип \"{1}\", но из использования можно определить более подходящий тип.", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "Не удается собрать проект \"{0}\", так как его зависимость \"{1}\" содержит ошибки", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "Не удается собрать проект \"{0}\", так как его зависимость \"{1}\" не была собрана", "Project_0_is_being_forcibly_rebuilt_6388": "Проект \"{0}\" принудительно перестраивается", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "Проект \"{0}\" устарел, так как файл buildinfo \"{1}показывает, что некоторые изменения не переданы.", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "Проект \"{0}\" требует обновления, так как не обновлена его зависимость \"{1}\"", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "Проект \"{0}\" требует обновления, так как самые старые выходные данные \"{1}\" старше самых новых входных данных \"{2}\"", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "Проект \"{0}\" устарел, так как выходные данные \"{1}\" старше входных данных \"{2}\".", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Проект \"{0}\" требует обновления, так как выходного файла \"{1}\" не существует", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "Проект \"{0}\" устарел, так как выходные данные для него были созданы с помощью версии \"{1}\", которая отличается от текущей версии \"{2}\"", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "Проект \"{0}\" устарел, так как изменились выходные данные его зависимости \"{1}\"", "Project_0_is_up_to_date_6361": "Проект \"{0}\" не требует обновления", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "Проект \"{0}\" не требует обновления, так как самые новые входные данные \"{1}\" старее самых старых выходных данных \"{2}\"", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "Проект \"{0}\" актуален, так как новейшие входные данные \"{1}\" старше выходных данных \"{2}\".", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "Проект \"{0}\" актуален, но требуется обновить метки времени файлов вывода, которые старше файлов ввода.", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "Проект \"{0}\" не требует обновления с файлами .d.ts, взятыми из зависимостей проекта", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Ссылки на проект не могут формировать циклический граф. Обнаружен цикл: {0}", "Projects_6255": "Проекты", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Обязательные параметры типа не могут следовать за необязательными параметрами типа.", "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}\".", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Режимы разрешения поддерживаются только тогда, когда ''moduleResolution'' равно ''node16'' или ''nodenext''.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Разрешать \"keyof\" только в имена свойств со строковым значением (не числа и не символы).", "Resolving_module_0_from_1_6086": "======== Идет разрешение модуля \"{0}\" из \"{1}\". ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Идет разрешение имени модуля \"{0}\" относительного к базовому URL-адресу \"{1}\" — \"{2}\".", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Невозможно использовать модификатор \"type\" в именованном экпорте, когда в инструкции экспорта используется \"export type\".", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "Невозможно использовать модификатор \"type\" в именованном импорте, когда в инструкции импорта используется \"import type\".", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "Тип объявления функции должен соответствовать сигнатуре этой функции.", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "Тип этого выражения не может быть назван без утверждения \"режим разрешения\", что является нестабильной функцией. Используйте ночной TypeScript, чтобы отключить эту ошибку. Попробуйте обновить с помощью \"npm install -D typescript@next\".", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "Невозможно сериализовать тип этого узла, поскольку его свойство \"{0}\" не может быть сериализовано.", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Возвращаемый тип метода \"{0}()\" асинхронного итератора должен быть обещанием для типа со свойством \"value\".", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Тип, возвращаемый методом \"{0}()\" итератора, должен содержать свойство \"value\".", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "Оператор with не поддерживается. Все символы в блоке with получат тип any.", "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_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Это условие всегда будет возвращать ''{0}'', так как JavaScript сравнивает объекты по ссылке, а не по значению.", "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367": "Это условие всегда будет возвращать \"{0}\", так как типы \"{1}\" и \"{2}\" не перекрываются.", "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, поскольку функция всегда определена. Возможно, вы хотите вызвать ее?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Для этого синтаксиса требуется импортированный вспомогательный объект, но найти модуль \"{0}\" не удается.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Для этого синтаксиса требуется импортированный вспомогательный объект с именем \"{1}\", который не существует в \"{0}\". Рекомендуется обновить версию \"{0}\".", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Для этого синтаксиса требуется импортированный вспомогательный объект с именем \"{1}\" и параметрами ({2}), который не совместим с объектом в \"{0}\". Попробуйте обновить версию \"{0}\".", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Для этого параметра типа может потребоваться ограничение \"extends {0}\".", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "Недопустимое использование \"import\". Можно записывать вызовы \"import()\", но у них должны быть скобки и не должно быть аргументов типа.", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Выражения ожидания верхнего уровня разрешены только в том случае, если для параметра \"module\" установлено значение \"es2022\", \"esnext\", \"system\", \"node16\" или \"nodenext\", а для параметра \"цель\" установлено значение \"es2017\" или выше.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Объявления верхнего уровня в файлах .d.ts должны начинаться с модификатора \"declare\" или \"export\".", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "Библиотека типов, на которую осуществляется ссылка с помощью \"{0}\" из файла \"{1}\" с идентификатором пакета \"{2}\"", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "Тип операнда \"await\" должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Типом значения вычисляемого свойства является \"{0}\", который не может быть назначен типу \"{1}\".", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "Инициализатор переменной-элемента экземпляра \"{0}\" не может ссылаться на идентификатор \"{1}\", объявленный в конструкторе.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Тип элементов итерации для операнда \"yield*\" должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Тип свойства \"{0}\" циклически ссылается на самого себя в сопоставленном типе \"{1}\".", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Тип операнда \"yield\" в асинхронном генераторе должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== Директива ссылки на тип \"{0}\" не разрешена. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== Директива ссылки на тип \"{0}\" успешно разрешена в \"{1}\", первичный объект: {2}. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== Директива ссылки на тип \"{0}\" успешно разрешена в \"{1}\" с идентификатором пакета \"{2}\", первичный объект: {3}. ========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Типы не могут отображаться в объявлениях экспорта в файлах JavaScript.", "Types_have_separate_declarations_of_a_private_property_0_2442": "Типы имеют раздельные объявления закрытого свойства \"{0}\".", "Types_of_construct_signatures_are_incompatible_2419": "Типы сигнатур конструкций несовместимы.", "Types_of_parameters_0_and_1_are_incompatible_2328": "Типы параметров \"{0}\" и \"{1}\" несовместимы.", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "Режимы отслеживания и сборки", "Watch_input_files_6005": "Просмотр входных файлов.", "Watch_option_0_requires_a_value_of_type_1_5080": "Параметр \"{0}\" контрольного значения требует значение типа {1}.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "Записать тип для \"{0}\" можно, только добавив здесь тип для всего параметра.", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "При назначении функций убедитесь, что параметры и возвращаемые значения совместимы с подтипом.", "When_type_checking_take_into_account_null_and_undefined_6699": "При проверке типа учитывайте параметры \"null\" и \"undefined\".", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Сохранять ли устаревшие выходные данные консоли в режиме просмотра вместо очистки экрана.", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Заключить следующий текст в круглые скобки, которые должны быть литералом объекта", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Вы можете узнать обо всех параметрах компилятора на {0}", "You_cannot_rename_a_module_via_a_global_import_8031": "Вы не можете переименовать модуль с помощью глобального импорта.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Невозможно переименовать элементы, определенные в папке \"node_modules\".", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Невозможно переименовать элементы, определенные в другой папке \"node_modules\".", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Невозможно переименовать элементы, определенные в стандартной библиотеке TypeScript.", "You_cannot_rename_this_element_8000": "Этот элемент переименовать нельзя.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" принимает слишком мало аргументов для использования в качестве декоратора. Вы хотели сначала вызвать его и записать \"@{0}()\"?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "Сигнатуры индекса \"{0}\" несовместимы.", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "Тип индекса \"{0}\" \"{1}\" не может быть назначен типу индекса \"{2}\" \"{3}\".", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "\"{0}\" является примитивом, но \"{1}\" — объект оболочки. Предпочтительно использовать \"{0}\" по мере возможности.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "\"{0}\" является типом и не может импортироваться в файлы JavaScript. Используйте \"{1}\" в заметке типа JSDoc.", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "\"{0}\" является типом. Чтобы импортировать его, необходимо использовать импорт, распространяющийся только на тип, если включены параметры \"preserveValueImports\" и \"isolatedModules\".", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "\"{0}\" является неиспользуемым переименованием \"{1}\". Возможно, это должна была быть заметка для типа?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "\"{0}\" может быть назначен ограничению типа \"{1}\", но можно создать экземпляр \"{1}\" с другим подтипом ограничения \"{2}\".", + "_0_is_automatically_exported_here_18044": "\"{0}\" экспортирован автоматически.", "_0_is_declared_but_its_value_is_never_read_6133": "Свойство \"{0}\" объявлено, но его значение не было прочитано.", "_0_is_declared_but_never_used_6196": "\"{0}\" объявлен, но никогда не использовался.", "_0_is_declared_here_2728": "Здесь объявлен \"{0}\".", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "один из:", "one_or_more_Colon_6901": "один или более:", "options_6024": "параметры", + "or_JSX_element_expected_1145": "Ожидался элемент JSX или \"{\".", "or_expected_1144": "Ожидалось \"{\" или \";\".", "package_json_does_not_have_a_0_field_6100": "В package.json нет поля \"{0}\".", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "В файле \"package.json\" отсутствует запись \"typesVersions\", соответствующая версии \"{0}\".", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Модификатор readonly может отображаться только в объявлении свойства или сигнатуре индекса.", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "Модификатор типа \"readonly\" допускается только для типов литерала массива и кортежа.", "require_call_may_be_converted_to_an_import_80005": "Вызов \"require\" можно преобразовать в \"import\".", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Утверждения \"режим разрешения\" поддерживаются только тогда, когда \"moduleResolution\" имеет значение \"node16\" или \"nodenext\".", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "Утверждения ''режима разрешения'' нестабильны. Используйте ночной TypeScript, чтобы отключить эту ошибку. Попробуйте обновить с помощью ''npm install -D typescript@next''.", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "\"resolution-mode\" можно задать лишь для импорта, распространяющегося только на тип.", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "\"resolution-mode\" является единственным допустимым ключом для утверждений импорта типа.", "resolution_mode_should_be_either_require_or_import_1453": "\"resolution-mode\" должен иметь значение \"require\" или \"import\".", diff --git a/tsserver/tr/diagnosticMessages.generated.json b/tsserver/tr/diagnosticMessages.generated.json index 374354fc..5297519a 100644 --- a/tsserver/tr/diagnosticMessages.generated.json +++ b/tsserver/tr/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' türü, yalnızca bir sınıfın veya arabirimin statik olmayan bir üyesinde kullanılabilir.", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' dosyası şu konumda zaten tanımlanmış: '{0}'.", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "Demet üyesi hem isteğe bağlı hem de diğerleri olamaz.", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "Bir demet türünün negatif bir değerle dizini oluşturulamaz.", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "Üs ifadesinin sol tarafında tür onaylama ifadesine izin verilmez. İfadeyi parantez içine yazmayı düşünün.", "A_type_literal_property_cannot_have_an_initializer_1247": "Tür sabit değeri özelliği bir başlatıcıya sahip olamaz.", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "Yalnızca tür içeri aktarma işlemleri varsayılan bir içeri aktarmayı veya adlandırılan bağlamaları belirtebilir ancak ikisini birden belirtemez.", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "'{0}' özelliğine belirli atama onayı ekle", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Tüm başlatılmamış özelliklere kesin atama onayları ekle", "Add_export_to_make_this_file_into_a_module_95097": "Bu dosyayı bir modüle dönüştürmek için 'export {}' ekleyin", + "Add_extends_constraint_2211": "`extends` kısıtlaması ekleyin.", + "Add_extends_constraint_to_all_type_parameters_2212": "Tüm tür parametrelerine `extends` kısıtlaması ekleyin", "Add_import_from_0_90057": "\"{0}\" kaynağından içeri aktarma ekle", "Add_index_signature_for_property_0_90017": "'{0}' özelliği için dizin imzası ekle", "Add_initializer_to_property_0_95019": "'{0}' özelliğine başlatıcı ekle", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "Dizin imzası parametresi, bir tür ek açıklamasına sahip olmalıdır.", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "Dizin imzası parametre türü sabit değer veya genel tür olamaz. Bunun yerine eşlenen nesne türü kullanabilirsiniz.", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "Dizin imzası parametre türü 'dize', 'sayı', 'sembol' veya şablon sabit değeri olmalıdır.", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "Bir örnek oluşturma ifadesinin ardından özellik erişimi gelemez.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Bir arabirim, isteğe bağlı tür bağımsız değişkenleri ile yalnızca bir tanımlayıcıyı/tam adı genişletebilir.", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "Arabirim, yalnızca statik olarak bilinen üyelere sahip bir nesne türünü veya nesne türlerinin bir kesişimini genişletebilir.", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "Arabirim, '{0}' gibi temel bir türü genişletemez; arabirim yalnızca adlandırılmış türleri ve sınıfları genişletilebilir", "An_interface_property_cannot_have_an_initializer_1246": "Arabirim özelliği bir başlatıcıya sahip olamaz.", "An_iterator_must_have_a_next_method_2489": "Bir yineleyici 'next()' metoduna sahip olmalıdır.", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "JSX parçalarıyla @jsx pragması kullanılırken bir @jsxFrag pragması gerekir.", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "'{0}' sınıfı hatalı olarak '{1}' sınıfını uyguluyor. '{1}' sınıfını genişletip üyelerini bir alt sınıf olarak devralmak mı istiyordunuz?", "Class_0_incorrectly_implements_interface_1_2420": "'{0}' sınıfı, '{1}' arabirimini yanlış uyguluyor.", "Class_0_used_before_its_declaration_2449": "'{0}' sınıfı, bildiriminden önce kullanıldı.", + "Class_constructor_may_not_be_a_generator_1360": "Sınıf oluşturucu, program yönergeleri üreten bir oluşturucu olamaz.", + "Class_constructor_may_not_be_an_accessor_1341": "Sınıf oluşturucu, bir erişimci olamaz.", "Class_declaration_cannot_implement_overload_list_for_0_2813": "Sınıf bildirimi, '{0}' için aşırı yükleme listesi uygulayamaz.", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Sınıf bildirimlerinde birden fazla '@augments' veya '@extends' etiketi olamaz.", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "Sınıf dekoratörleri statik özel tanımlayıcıyla kullanılamaz. Deneysel dekoratörü kaldırmayı düşünün.", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "'{0}' dosyası bulunamadı.", "File_Management_6245": "Dosya Yönetimi", "File_change_detected_Starting_incremental_compilation_6032": "Dosya değişikliği algılandı. Artımlı derleme başlatılıyor...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "'{0}', \"type\" alanına sahip olmadığından dosya CommonJS modülüdür", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "'{0}', değeri \"module\" olmayan \"type\" alanına sahip olduğundan dosya CommonJS modülüdür", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "'package.json' bulunamadığından dosya CommonJS modülüdür", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "'{0}', değeri \"module\" olan \"type\" alanına sahip olduğundan dosya ECMAScript modülüdür", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Bir CommonJS modülü olan dosya bir ES modülüne dönüştürülebilir.", "File_is_default_library_for_target_specified_here_1426": "Burada dosya, belirtilen hedef için varsayılan kitaplıktır.", "File_is_entry_point_of_type_library_specified_here_1419": "Burada dosya, belirtilen tür kitaplığının giriş noktasıdır.", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "Tanımlayıcı bekleniyor. '{0}', burada kullanılamayan ayrılmış bir sözcüktür.", "Identifier_expected_1003": "Tanımlayıcı bekleniyor.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Tanımlayıcı bekleniyor. '__esModule', ECMAScript modülleri dönüştürülürken, dışarı aktarılan bir işaretçi olarak ayrılmış.", + "Identifier_or_string_literal_expected_1478": "Tanımlayıcı veya sabit değerli dize bekleniyor.", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "'{0}' paketi bu modülü gerçekten kullanıma sunarsa, 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}' öğesini düzeltmek için bir çekme isteği göndermeyi deneyin", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "‘{0}’ paketi bu modülü fiili olarak kullanıma sunuyorsa `'{1}' modülünü bildir;` ifadesini içeren yeni bir bildirim (.d.ts) dosyası eklemeyi deneyin", "Ignore_this_error_message_90019": "Bu hata iletisini yoksay", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "Geçersiz '{0}' içeri aktarma tanımlayıcısında olası çözünürlük yok.", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "Genişletmedeki modül adı geçersiz. '{0}' modülü, '{1}' konumundaki türü belirsiz ve genişletilemeyen bir modüle çözümleniyor.", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "Genişletmedeki modül adı geçersiz; '{0}' adlı modül bulunamıyor.", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "Yeni ifadeden geçersiz isteğe bağlı zincir. '{0}()' çağrısı mı yapmak istediniz?", "Invalid_reference_directive_syntax_1084": "Geçersiz 'reference' yönergesi söz dizimi.", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "Geçersiz '{0}' kullanımı. Bu ifade bir sınıf statik bloğu içinde kullanılamaz.", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "Geçersiz '{0}' kullanımı. Modüller otomatik olarak katı moddadır.", @@ -893,6 +906,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_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.", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "'{0}' üyesi örtük olarak bir '{1}' türüne sahip ancak kullanımdan daha iyi bir tür çıkarsanabilir.", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{0}' projesinin '{1}' bağımlılığında hatalar olduğundan proje derlenemiyor", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "'{0}' projesinin '{1}' bağımlılığı derlenmediğinden proje derlenemiyor", "Project_0_is_being_forcibly_rebuilt_6388": "'{0}' projesi zorla yeniden oluşturuluyor", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "'{1}' buildinfo dosyası bazı değişikliklerin gösterilmediğini belirttiğinden '{0}' projesi güncel değil", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "'{0}' projesinin '{1}' bağımlılığı güncel olmadığından proje güncel değil", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "En eski '{1}' çıkışı en yeni '{2}' girişinden daha eski olduğundan '{0}' projesi güncel değil", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "'{1}' çıkışı '{2}' girişinden daha eski olduğundan '{0}' projesi güncel değil", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "Çıkış dosyası '{1}' mevcut olmadığından '{0}' projesi güncel değil", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "'{0}' projesinin çıkışı geçerli '{2}' sürümünden farklı olan '{1}' sürümü ile oluşturulduğundan proje güncel değil", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "'{0}' projesinin '{1}' bağımlılığı değiştirildiğinden proje güncel değil", "Project_0_is_up_to_date_6361": "'{0}' projesi güncel", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "En yeni '{1}' girişi en eski '{2}' çıkışından daha eski olduğundan '{0}' projesi güncel", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "En yeni '{1}' girişi '{2}' çıkışından daha eski olduğundan '{0}' projesi güncel", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "'{0}' projesi güncel ancak giriş dosyalarından daha eski olan çıkış dosyalarına ait zaman damgalarının güncelleştirilmesi gerekiyor", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "'{0}' projesi bağımlılıklarından d.ts dosyaları ile güncel", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Proje başvuruları döngüsel bir grafik formu oluşturamaz. Döngü tespit edildi: {0}", "Projects_6255": "Projeler", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Gerekli tür parametreleri, isteğe bağlı tür parametrelerini takip edemez.", "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.", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "Çözünürlük modları yalnızca `moduleResolution` değeri `node16` veya `nodenext` olduğunda desteklenir.", "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_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.", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "Dışarı aktarma deyimindeki 'dışarı aktarma türü' kullanılırken 'tür' değiştiricisi adlandırılmış bir dışarı aktarma üzerinde kullanılamaz.", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "İçeri aktarma deyimindeki 'içeri aktarma türü' kullanılırken 'tür' değiştiricisi adlandırılmış bir içeri aktarma üzerinde kullanılamaz.", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "İşlev bildiriminin türü işlevin imzasıyla eşleşmelidir.", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "Bu ifadenin türü kararsız bir özellik olan 'resolution-mode' onaylaması olmadan adlandırılamaz. Bu hatayı sessize almak için gece TypeScript kullanın. 'npm install -D typescript@next' ile güncelleştirmeyi deneyin.", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "'{0}' özelliği seri hale getirilemediğinden bu düğüm türü seri hale getirilemiyor.", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "Asenkron yineleyicinin '{0}()' metodu tarafından döndürülen tür, 'value' özelliğine sahip bir tür için promise olmalıdır.", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "Bir yineleyicinin '{0}()' metodu tarafından döndürülen tür, 'value' özelliğine sahip olmalıdır.", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "'with' ifadesi desteklenmiyor. 'with' bloklarındaki tüm simgeler 'any' türüne sahip olacaktır.", "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_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_0_since_the_types_1_and_2_have_no_overlap_2367": "'{1}' ve '{2}' türleri çakışmadığından bu koşul her zaman '{0}' 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?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Bu söz dizimi, içeri aktarılan bir yardımcı gerektiriyor ancak '{0}' modülü bulunamıyor.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Bu söz dizimi, '{0}' içinde bulunmayan '{1}' adlı içeri aktarılmış bir yardımcı gerektirir. '{0}' sürümünüzü yükseltmeyi deneyin.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Bu söz dizimi, '{0}' içindeki yardımcı ile uyumlu olmayan, {2} parametreye sahip '{1}' adlı içeri aktarılan yardımcıyı gerektiriyor. '{0}' sürümünüzü yükseltmeyi düşünün.", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "Bu tür parametresinin bir `extends {0}` kısıtlamasına ihtiyacı olabilir.", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "'import' çağrısının bu kullanımı geçersiz. 'import()' çağrıları yazılabilir ancak ayraç içermeleri gerekir ve tür bağımsız değişkenleri içeremezler.", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "Üst düzey 'await' ifadelerine yalnızca 'module' seçeneği 'es2022', 'esnext', 'system', 'node16' veya 'nodenext' olarak ayarlandığında ve 'target' seçeneği 'es2017' veya üzeri olarak ayarlandığında izin verilir.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": ".d.ts dosyalarındaki üst düzey bildirimler bir 'declare' veya 'export' değiştiricisi ile başlamalıdır.", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "'{2}' paket kimliğine sahip '{1}' dosyasından '{0}' aracılığıyla başvurulan tür kitaplığı", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' işleneninin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "Hesaplanan özellik değerinin '{0}' türü, '{1}' türüne atanamıyor.", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "'{0}' örnek üyesi değişkeninin türü, oluşturucuda bildirilen '{1}' tanımlayıcısına başvuramaz.", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Bir 'yield*' işleneninin yinelenen öğelerinin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "'{0}' özelliğinin türü, '{1}' eşlenmiş türünde döngüsel olarak kendine başvuruyor.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Zaman uyumsuz bir oluşturucudaki 'yield' işleneninin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== '{0}' tür başvuru yönergesi çözümlenmedi. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== '{0}' tür başvuru yönergesi '{1}' olarak başarıyla çözümlendi, birincil: {2}. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== '{0}' tür başvuru yönergesi '{2}' Paket Kimliğine sahip '{1}' olarak başarıyla çözümlendi, birincil: {3}. ========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "Türler, JavaScript dosyalarında dışarı aktarma bildirimlerinde görünemez.", "Types_have_separate_declarations_of_a_private_property_0_2442": "Türler, '{0}' özel özelliğinin ayrı bildirimlerine sahip.", "Types_of_construct_signatures_are_incompatible_2419": "Yapı imzalarının türleri uyumsuz.", "Types_of_parameters_0_and_1_are_incompatible_2328": "'{0}' ve '{1}' parametre türleri uyumsuz.", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "İzleme ve Derleme Modları", "Watch_input_files_6005": "Giriş dosyalarını izleyin.", "Watch_option_0_requires_a_value_of_type_1_5080": "'{0}' izleme seçeneği, {1} türünde bir değer gerektiriyor.", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "'{0}' için bir türü yalnızca tüm parametre için buraya bir tür ekleyerek yazabiliriz.", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "İşlevler atanırken, parametrelerin ve dönüş değerlerinin alt tür ile uyumlu olduğundan emin olun.", "When_type_checking_take_into_account_null_and_undefined_6699": "Tür denetimi sırasında 'null' ve 'undefined' öğelerini hesaba kat.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Eski konsol çıktısının ekrandan kaldırılmak yerine izleme modunda tutulup tutulmayacağı.", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Nesne sabit değeri olması gereken aşağıdaki gövdeyi parantez içine alın", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "Tüm derleyici seçenekleri hakkında bilgi edinmek için bkz. {0}", "You_cannot_rename_a_module_via_a_global_import_8031": "Genel içeri aktarma aracılığıyla bir modülü yeniden adlandıramazsınız.", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "Bir 'node_modules' klasöründe tanımlanan öğeler yeniden adlandırılamaz.", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "Başka bir 'node_modules' klasöründe tanımlanan öğeler yeniden adlandırılamaz.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Standart TypeScript kitaplığında tanımlanmış öğeleri yeniden adlandıramazsınız.", "You_cannot_rename_this_element_8000": "Bu öğeyi yeniden adlandıramazsınız.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' burada dekoratör olarak kullanılmak için çok az bağımsız değişken kabul ediyor. Önce çağırıp '@{0}()' yazmak mı istediniz?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "'{0}' dizin imzaları uyumsuz.", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "'{0}' dizin türü '{1}' ' {2}' dizin türüne '{3}' atanamaz.", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' temel elemandır ancak '{1}' sarmalayıcı nesnedir. Mümkün olduğunda '{0}' kullanmayı tercih edin.", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' bir tür ve JavaScript dosyalarında içeri aktarılamaz. Bir JSDoc türü ek açıklamasında '{1}' kullanın.", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "'{0}' bir türdür ve 'preserveValueImports' ve 'isolatedModules' seçeneklerinin her ikisi de etkin olduğunda yalnızca türü içeri aktarma kullanılarak içeri aktarılmalıdır.", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}', '{1}' türünün kullanılmayan bir yeniden adlandırması. Tür ek açıklaması olarak mı kullanmak istediniz?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}', '{1}' türündeki kısıtlamaya atanabilir ancak '{1}' örneği, '{2}' kısıtlamasının farklı bir alt türüyle oluşturulabilir.", + "_0_is_automatically_exported_here_18044": "'{0}' burada otomatik olarak dışarı aktarılır.", "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' bildirildi ancak değeri hiç okunmadı.", "_0_is_declared_but_never_used_6196": "'{0}' bildirildi ancak hiç kullanılmadı.", "_0_is_declared_here_2728": "'{0}' burada bildirilir.", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "şunlardan biri:", "one_or_more_Colon_6901": "bir veya daha fazla:", "options_6024": "seçenekler", + "or_JSX_element_expected_1145": "'{' veya JSX öğesi bekleniyor.", "or_expected_1144": "'{' veya ';' bekleniyor.", "package_json_does_not_have_a_0_field_6100": "'package.json' geçerli bir '{0}' alanına sahip değil.", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json', '{0}' sürümüyle eşleşen bir 'typesVersions' girdisine sahip değil.", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' değiştiricisi yalnızca özellik bildiriminde ya da dizin imzasında görünebilir.", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "'readonly' tür değiştiricisine yalnızca dizide ve demet sabit değeri türlerinde izin verilir.", "require_call_may_be_converted_to_an_import_80005": "'require' çağrısı bir import olarak dönüştürülebilir.", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "'resolution-mode' onaylamaları yalnızca 'moduleResolution' değeri 'node16' veya 'nodenext' olduğunda desteklenir.", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "'resolution-mode' onaylamaları kararlı değil. Bu hatayı sessize almak için gecelik TypeScript kullanın. 'npm install -D typescript@next' ile güncelleştirmeyi deneyin.", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "`resolution-mode` yalnızca tür içeri aktarmaları için ayarlanabilir.", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "`resolution-mode`, tür içe aktarma iddiaları için tek geçerli anahtardır.", "resolution_mode_should_be_either_require_or_import_1453": "`resolution-mode`, `require` ya da `import` olmalıdır.", diff --git a/tsserver/tsc.js b/tsserver/tsc.js index 781b84ae..97db13aa 100644 --- a/tsserver/tsc.js +++ b/tsserver/tsc.js @@ -68,8 +68,8 @@ var __generator = (this && this.__generator) || function (thisArg, body) { }; var ts; (function (ts) { - ts.versionMajorMinor = "4.7"; - ts.version = "4.7.2"; + ts.versionMajorMinor = "4.8"; + ts.version = "4.8.2"; var NativeCollections; (function (NativeCollections) { var globals = typeof globalThis !== "undefined" ? globalThis : @@ -234,8 +234,10 @@ var ts; return true; } ts.every = every; - function find(array, predicate) { - for (var i = 0; i < array.length; i++) { + function find(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { var value = array[i]; if (predicate(value, i)) { return value; @@ -244,8 +246,10 @@ var ts; return undefined; } ts.find = find; - function findLast(array, predicate) { - for (var i = array.length - 1; i >= 0; i--) { + function findLast(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { var value = array[i]; if (predicate(value, i)) { return value; @@ -255,7 +259,9 @@ var ts; } ts.findLast = findLast; function findIndex(array, predicate, startIndex) { - for (var i = startIndex || 0; i < array.length; i++) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -264,7 +270,9 @@ var ts; } ts.findIndex = findIndex; function findLastIndex(array, predicate, startIndex) { - for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { if (predicate(array[i], i)) { return i; } @@ -970,7 +978,7 @@ var ts; } ts.elementAt = elementAt; function firstOrUndefined(array) { - return array.length === 0 ? undefined : array[0]; + return array === undefined || array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -979,7 +987,7 @@ var ts; } ts.first = first; function lastOrUndefined(array) { - return array.length === 0 ? undefined : array[array.length - 1]; + return array === undefined || array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -1270,6 +1278,41 @@ var ts; return createMultiMap(); } ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; + function createQueue(items) { + var elements = (items === null || items === void 0 ? void 0 : items.slice()) || []; + var headIndex = 0; + function isEmpty() { + return headIndex === elements.length; + } + function enqueue() { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + elements.push.apply(elements, items); + } + function dequeue() { + if (isEmpty()) { + throw new Error("Queue is empty"); + } + var result = elements[headIndex]; + elements[headIndex] = undefined; + headIndex++; + if (headIndex > 100 && headIndex > (elements.length >> 1)) { + var newLength = elements.length - headIndex; + elements.copyWithin(0, headIndex); + elements.length = newLength; + headIndex = 0; + } + return result; + } + return { + enqueue: enqueue, + dequeue: dequeue, + isEmpty: isEmpty, + }; + } + ts.createQueue = createQueue; function createSet(getHashCode, equals) { var multiMap = new ts.Map(); var size = 0; @@ -1441,6 +1484,10 @@ var ts; ts.cast = cast; function noop(_) { } ts.noop = noop; + ts.noopPush = { + push: noop, + length: 0 + }; function returnFalse() { return false; } @@ -1664,7 +1711,7 @@ var ts; } ts.compareBooleans = compareBooleans; function getSpellingSuggestion(name, candidates, getName) { - var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var maximumLengthDifference = Math.max(2, Math.floor(name.length * 0.34)); var bestDistance = Math.floor(name.length * 0.4) + 1; var bestCandidate; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -1862,6 +1909,7 @@ var ts; startsWith(candidate, prefix) && endsWith(candidate, suffix); } + ts.isPatternMatch = isPatternMatch; function and(f, g) { return function (arg) { return f(arg) && g(arg); }; } @@ -2023,6 +2071,7 @@ var ts; var currentAssertionLevel = 0; Debug.currentLogLevel = LogLevel.Warning; Debug.isDebugging = false; + Debug.enableDeprecationWarnings = true; function getTypeScriptVersion() { return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version)); } @@ -2230,7 +2279,7 @@ var ts; return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; } if (isFlags) { - var result = ""; + var result = []; var remainingFlags = value; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; @@ -2238,12 +2287,12 @@ var ts; break; } if (enumValue !== 0 && enumValue & value) { - result = "".concat(result).concat(result ? "|" : "").concat(enumName); + result.push(enumName); remainingFlags &= ~enumValue; } } if (remainingFlags === 0) { - return result; + return result.join("|"); } } else { @@ -2257,7 +2306,12 @@ var ts; return value.toString(); } Debug.formatEnum = formatEnum; + var enumMemberCache = new ts.Map(); function getEnumMembers(enumObject) { + var existing = enumMemberCache.get(enumObject); + if (existing) { + return existing; + } var result = []; for (var name in enumObject) { var value = enumObject[name]; @@ -2265,7 +2319,9 @@ var ts; result.push([value, name]); } } - return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + var sorted = ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + enumMemberCache.set(enumObject, sorted); + return sorted; } function formatSyntaxKind(kind) { return formatEnum(kind, ts.SyntaxKind, false); @@ -2311,6 +2367,22 @@ var ts; return formatEnum(flags, ts.FlowFlags, true); } Debug.formatFlowFlags = formatFlowFlags; + function formatRelationComparisonResult(result) { + return formatEnum(result, ts.RelationComparisonResult, true); + } + Debug.formatRelationComparisonResult = formatRelationComparisonResult; + function formatCheckMode(mode) { + return formatEnum(mode, ts.CheckMode, true); + } + Debug.formatCheckMode = formatCheckMode; + function formatSignatureCheckMode(mode) { + return formatEnum(mode, ts.SignatureCheckMode, true); + } + Debug.formatSignatureCheckMode = formatSignatureCheckMode; + function formatTypeFacts(facts) { + return formatEnum(facts, ts.TypeFacts, true); + } + Debug.formatTypeFacts = formatTypeFacts; var isDebugInfoEnabled = false; var extendedDebugModule; function extendedDebug() { @@ -2584,7 +2656,7 @@ var ts; function createWarningDeprecation(name, errorAfter, since, message) { var hasWrittenDeprecation = false; return function () { - if (!hasWrittenDeprecation) { + if (Debug.enableDeprecationWarnings && !hasWrittenDeprecation) { log.warn(formatDeprecationMessage(name, false, errorAfter, since, message)); hasWrittenDeprecation = true; } @@ -2603,6 +2675,7 @@ var ts; warn ? createWarningDeprecation(name, errorAfter, since, options.message) : ts.noop; } + Debug.createDeprecation = createDeprecation; function wrapFunction(deprecation, func) { return function () { deprecation(); @@ -2610,10 +2683,53 @@ var ts; }; } function deprecate(func, options) { - var deprecation = createDeprecation(getFunctionName(func), options); + var _a; + var deprecation = createDeprecation((_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : getFunctionName(func), options); return wrapFunction(deprecation, func); } Debug.deprecate = deprecate; + function formatVariance(varianceFlags) { + var variance = varianceFlags & 7; + var result = variance === 0 ? "in out" : + variance === 3 ? "[bivariant]" : + variance === 2 ? "in" : + variance === 1 ? "out" : + variance === 4 ? "[independent]" : ""; + if (varianceFlags & 8) { + result += " (unmeasurable)"; + } + else if (varianceFlags & 16) { + result += " (unreliable)"; + } + return result; + } + Debug.formatVariance = formatVariance; + var DebugTypeMapper = (function () { + function DebugTypeMapper() { + } + DebugTypeMapper.prototype.__debugToString = function () { + var _a; + type(this); + switch (this.kind) { + case 3: return ((_a = this.debugInfo) === null || _a === void 0 ? void 0 : _a.call(this)) || "(function mapper)"; + case 0: return "".concat(this.source.__debugTypeToString(), " -> ").concat(this.target.__debugTypeToString()); + case 1: return ts.zipWith(this.sources, this.targets || ts.map(this.sources, function () { return "any"; }), function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(typeof t === "string" ? t : t.__debugTypeToString()); }).join(", "); + case 2: return ts.zipWith(this.sources, this.targets, function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(t().__debugTypeToString()); }).join(", "); + case 5: + case 4: return "m1: ".concat(this.mapper1.__debugToString().split("\n").join("\n "), "\nm2: ").concat(this.mapper2.__debugToString().split("\n").join("\n ")); + default: return assertNever(this); + } + }; + return DebugTypeMapper; + }()); + Debug.DebugTypeMapper = DebugTypeMapper; + function attachDebugPrototypeIfDebug(mapper) { + if (Debug.isDebugging) { + return Object.setPrototypeOf(mapper, DebugTypeMapper.prototype); + } + return mapper; + } + Debug.attachDebugPrototypeIfDebug = attachDebugPrototypeIfDebug; })(Debug = ts.Debug || (ts.Debug = {})); })(ts || (ts = {})); var ts; @@ -3186,9 +3302,9 @@ var ts; eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } tracingEnabled.push = push; - function pop() { + function pop(results) { ts.Debug.assert(eventStack.length > 0); - writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); + writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp(), results); eventStack.length--; } tracingEnabled.pop = pop; @@ -3201,13 +3317,14 @@ var ts; } tracingEnabled.popAll = popAll; var sampleInterval = 1000 * 10; - function writeStackEvent(index, endTime) { + function writeStackEvent(index, endTime, results) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { + ts.Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`"); writeEvent("E", phase, name, args, undefined, endTime); } else if (sampleInterval - (time % sampleInterval) <= endTime - time) { - writeEvent("X", phase, name, args, "\"dur\":".concat(endTime - time), time); + writeEvent("X", phase, name, __assign(__assign({}, args), { results: results }), "\"dur\":".concat(endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { @@ -3745,7 +3862,7 @@ var ts; }; } function createDirectoryWatcher(dirName, dirPath, fallbackOptions) { - var watcher = fsWatch(dirName, 1, function (_eventName, relativeFileName) { + var watcher = fsWatch(dirName, 1, function (_eventName, relativeFileName, modifiedTime) { if (!ts.isString(relativeFileName)) return; var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); @@ -3753,7 +3870,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); + fileCallback(fileName, FileWatcherEventKind.Changed, modifiedTime); } } }, false, PollingInterval.Medium, fallbackOptions); @@ -3805,7 +3922,7 @@ var ts; } else { cache.set(path, { - watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options), + watcher: watchFile(fileName, function (fileName, eventKind, modifiedTime) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind, modifiedTime); }); }, pollingInterval, options), refCount: 1 }); } @@ -3829,7 +3946,7 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime), modifiedTime); return true; } return false; @@ -3854,7 +3971,7 @@ var ts; } ts.setSysLog = setSysLog; function createDirectoryWatcherSupportingRecursive(_a) { - var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, directoryExists = _a.directoryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, fileSystemEntryExists = _a.fileSystemEntryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; var cache = new ts.Map(); var callbackCache = ts.createMultiMap(); var cacheToUpdateChildWatches = new ts.Map(); @@ -3947,7 +4064,7 @@ var ts; } function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) { var parentWatcher = cache.get(dirPath); - if (parentWatcher && directoryExists(dirName)) { + if (parentWatcher && fileSystemEntryExists(dirName, 1)) { scheduleUpdateChildWatches(dirName, dirPath, fileName, options); return; } @@ -4015,7 +4132,7 @@ var ts; if (!parentWatcher) return false; var newChildWatches; - var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { + var hasChanges = ts.enumerateInsertsAndDeletes(fileSystemEntryExists(parentDir, 1) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); return !isIgnoredPath(childFullName, options) && filePathComparer(childFullName, ts.normalizePath(realpath(childFullName))) === 0 ? childFullName : undefined; }) : ts.emptyArray, parentWatcher.childWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); @@ -4043,16 +4160,17 @@ var ts; } ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive; function createFileWatcherCallback(callback) { - return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + return function (_fileName, eventKind, modifiedTime) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", "", modifiedTime); }; } ts.createFileWatcherCallback = createFileWatcherCallback; - function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) { - return function (eventName) { + function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime) { + return function (eventName, _relativeFileName, modifiedTime) { if (eventName === "rename") { - callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + modifiedTime || (modifiedTime = getModifiedTime(fileName) || ts.missingFileModifiedTime); + callback(fileName, modifiedTime !== ts.missingFileModifiedTime ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted, modifiedTime); } else { - callback(fileName, FileWatcherEventKind.Changed); + callback(fileName, FileWatcherEventKind.Changed, modifiedTime); } }; } @@ -4071,11 +4189,12 @@ var ts; }; } function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; + var pollingWatchFile = _a.pollingWatchFile, 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 dynamicPollingWatchFile; var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; + var hitSystemWatcherLimit = false; return { watchFile: watchFile, watchDirectory: watchDirectory @@ -4093,7 +4212,7 @@ var ts; case ts.WatchFileKind.FixedChunkSizePolling: return ensureFixedChunkSizePollingWatchFile()(fileName, callback, undefined, undefined); case ts.WatchFileKind.UseFsEvents: - return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), false, pollingInterval, ts.getFallbackOptions(options)); + return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime), false, pollingInterval, ts.getFallbackOptions(options)); case ts.WatchFileKind.UseFsEventsOnParentDirectory: if (!nonPollingWatchFile) { nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames); @@ -4146,7 +4265,7 @@ var ts; hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - directoryExists: directoryExists, + fileSystemEntryExists: fileSystemEntryExists, getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories, watchDirectory: nonRecursiveWatchDirectory, realpath: realpath, @@ -4191,6 +4310,94 @@ var ts; }; } } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { + var lastDirectoryPartWithDirectorySeparator; + var lastDirectoryPart; + if (inodeWatching) { + lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substring(fileOrDirectory.lastIndexOf(ts.directorySeparator)); + lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); + } + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + if (watcher) { + watcher.close(); + watcher = undefined; + } + } + }; + function updateWatcher(createWatcher) { + if (watcher) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); + watcher.close(); + watcher = createWatcher(); + } + } + function watchPresentFileSystemEntry() { + if (hitSystemWatcherLimit) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + try { + var presentWatcher = fsWatchWorker(fileOrDirectory, recursive, inodeWatching ? + callbackChangingToMissingFileSystemEntry : + callback); + presentWatcher.on("error", function () { + callback("rename", ""); + updateWatcher(watchMissingFileSystemEntry); + }); + return presentWatcher; + } + catch (e) { + hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + function callbackChangingToMissingFileSystemEntry(event, relativeName) { + var originalRelativeName; + if (relativeName && ts.endsWith(relativeName, "~")) { + originalRelativeName = relativeName; + relativeName = relativeName.slice(0, relativeName.length - 1); + } + if (event === "rename" && + (!relativeName || + relativeName === lastDirectoryPart || + ts.endsWith(relativeName, lastDirectoryPartWithDirectorySeparator))) { + var modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime; + if (originalRelativeName) + callback(event, originalRelativeName, modifiedTime); + callback(event, relativeName, modifiedTime); + if (inodeWatching) { + updateWatcher(modifiedTime === ts.missingFileModifiedTime ? watchMissingFileSystemEntry : watchPresentFileSystemEntry); + } + else if (modifiedTime === ts.missingFileModifiedTime) { + updateWatcher(watchMissingFileSystemEntry); + } + } + else { + if (originalRelativeName) + callback(event, originalRelativeName); + callback(event, relativeName); + } + } + function watchPresentFileSystemEntryWithFsWatchFile() { + return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); + } + function watchMissingFileSystemEntry() { + return watchFile(fileOrDirectory, function (_fileName, eventKind, modifiedTime) { + if (eventKind === FileWatcherEventKind.Created) { + modifiedTime || (modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime); + if (modifiedTime !== ts.missingFileModifiedTime) { + callback("rename", "", modifiedTime); + updateWatcher(watchPresentFileSystemEntry); + } + } + }, fallbackPollingInterval, fallbackOptions); + } + } } ts.createSystemWatchFunctions = createSystemWatchFunctions; function patchWriteFileEnsuringDirectory(sys) { @@ -4218,7 +4425,6 @@ var ts; ts.sys = (function () { var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { - var _a; var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/; var _fs = require("fs"); var _path = require("path"); @@ -4227,39 +4433,39 @@ var ts; try { _crypto = require("crypto"); } - catch (_b) { + catch (_a) { _crypto = undefined; } var activeSession; var profilePath = "./profile.cpuprofile"; - var hitSystemWatcherLimit = false; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; + var fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); - var _c = createSystemWatchFunctions({ + var _b = createSystemWatchFunctions({ pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames), getModifiedTime: getModifiedTime, setTimeout: setTimeout, clearTimeout: clearTimeout, - fsWatch: fsWatch, + fsWatchWorker: fsWatchWorker, useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - fileExists: fileExists, + fileSystemEntryExists: fileSystemEntryExists, fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch, - directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, realpath: realpath, 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); }, - }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; + inodeWatching: isLinuxOrMacOs, + sysLog: sysLog, + }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -4478,79 +4684,12 @@ var ts; else { eventKind = FileWatcherEventKind.Changed; } - callback(fileName, eventKind); + callback(fileName, eventKind, curr.mtime); } } - function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { - var options; - var lastDirectoryPartWithDirectorySeparator; - var lastDirectoryPart; - if (isLinuxOrMacOs) { - lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator)); - lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); - } - var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? - watchMissingFileSystemEntry() : - watchPresentFileSystemEntry(); - return { - close: function () { - watcher.close(); - watcher = undefined; - } - }; - function invokeCallbackAndUpdateWatcher(createWatcher) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); - callback("rename", ""); - if (watcher) { - watcher.close(); - watcher = createWatcher(); - } - } - function watchPresentFileSystemEntry() { - if (options === undefined) { - if (fsSupportsRecursiveFsWatch) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - } - if (hitSystemWatcherLimit) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - try { - var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ? - callbackChangingToMissingFileSystemEntry : - callback); - presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); - return presentWatcher; - } - catch (e) { - hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - } - function callbackChangingToMissingFileSystemEntry(event, relativeName) { - return event === "rename" && - (!relativeName || - relativeName === lastDirectoryPart || - (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && - !fileSystemEntryExists(fileOrDirectory, entryKind) ? - invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : - callback(event, relativeName); - } - function watchPresentFileSystemEntryWithFsWatchFile() { - return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); - } - function watchMissingFileSystemEntry() { - return watchFile(fileOrDirectory, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { - invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); - } - }, fallbackPollingInterval, fallbackOptions); - } + function fsWatchWorker(fileOrDirectory, recursive, callback) { + return _fs.watch(fileOrDirectory, fsSupportsRecursiveFsWatch ? + { persistent: true, recursive: !!recursive } : { persistent: true }, callback); } function readFileWorker(fileName, _encoding) { var buffer; @@ -4676,9 +4815,12 @@ var ts; function getDirectories(path) { return getAccessibleFileSystemEntries(path).directories.slice(); } + function fsRealPathHandlingLongPath(path) { + return path.length < 260 ? _fs.realpathSync.native(path) : _fs.realpathSync(path); + } function realpath(path) { try { - return realpathSync(path); + return fsRealpath(path); } catch (_a) { return path; @@ -4686,12 +4828,17 @@ var ts; } function getModifiedTime(path) { var _a; + var originalStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; try { return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime; } catch (e) { return undefined; } + finally { + Error.stackTraceLimit = originalStackTraceLimit; + } } function setModifiedTime(path, time) { try { @@ -5326,6 +5473,7 @@ var ts; String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + or_JSX_element_expected: diag(1145, ts.DiagnosticCategory.Error, "or_JSX_element_expected_1145", "'{' or JSX element expected."), Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), @@ -5379,6 +5527,7 @@ var ts; Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), _0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module: diag(1208, ts.DiagnosticCategory.Error, "_0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_imp_1208", "'{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module."), + Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0: diag(1209, ts.DiagnosticCategory.Error, "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209", "Invalid optional chain from new expression. Did you mean to call '{0}()'?"), Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode: diag(1210, ts.DiagnosticCategory.Error, "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210", "Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of '{0}'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode."), A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), @@ -5471,6 +5620,7 @@ var ts; infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Class_constructor_may_not_be_an_accessor: diag(1341, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_an_accessor_1341", "Class constructor may not be an accessor."), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), @@ -5489,6 +5639,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Class_constructor_may_not_be_a_generator: diag(1360, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_a_generator_1360", "Class constructor may not be a generator."), _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."), _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), @@ -5573,18 +5724,30 @@ var ts; Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, ts.DiagnosticCategory.Message, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."), Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments: diag(1450, ts.DiagnosticCategory.Message, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional assertion as arguments"), Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"), - Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "Resolution modes are only supported when `moduleResolution` is `node16` or `nodenext`."), + resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "'resolution-mode' assertions are only supported when `moduleResolution` is `node16` or `nodenext`."), resolution_mode_should_be_either_require_or_import: diag(1453, ts.DiagnosticCategory.Error, "resolution_mode_should_be_either_require_or_import_1453", "`resolution-mode` should be either `require` or `import`."), resolution_mode_can_only_be_set_for_type_only_imports: diag(1454, ts.DiagnosticCategory.Error, "resolution_mode_can_only_be_set_for_type_only_imports_1454", "`resolution-mode` can only be set for type-only imports."), resolution_mode_is_the_only_valid_key_for_type_import_assertions: diag(1455, ts.DiagnosticCategory.Error, "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455", "`resolution-mode` is the only valid key for type import assertions."), Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require: diag(1456, ts.DiagnosticCategory.Error, "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456", "Type import assertions should have exactly one key - `resolution-mode` - with value `import` or `require`."), + Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk: diag(1457, ts.DiagnosticCategory.Message, "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457", "Matched by default include pattern '**/*'"), + File_is_ECMAScript_module_because_0_has_field_type_with_value_module: diag(1458, ts.DiagnosticCategory.Message, "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458", "File is ECMAScript module because '{0}' has field \"type\" with value \"module\""), + File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module: diag(1459, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459", "File is CommonJS module because '{0}' has field \"type\" whose value is not \"module\""), + File_is_CommonJS_module_because_0_does_not_have_field_type: diag(1460, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_does_not_have_field_type_1460", "File is CommonJS module because '{0}' does not have field \"type\""), + File_is_CommonJS_module_because_package_json_was_not_found: diag(1461, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_package_json_was_not_found_1461", "File is CommonJS module because 'package.json' was not found"), The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."), - Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."), + Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported with 'require'. Use an ECMAScript import instead."), catch_or_finally_expected: diag(1472, ts.DiagnosticCategory.Error, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), An_import_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1473, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473", "An import declaration can only be used at the top level of a module."), An_export_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1474, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474", "An export declaration can only be used at the top level of a module."), Control_what_method_is_used_to_detect_module_format_JS_files: diag(1475, ts.DiagnosticCategory.Message, "Control_what_method_is_used_to_detect_module_format_JS_files_1475", "Control what method is used to detect module-format JS files."), auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules: diag(1476, ts.DiagnosticCategory.Message, "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476", "\"auto\": Treat files with imports, exports, import.meta, jsx (with jsx: react-jsx), or esm format (with module: node16+) as modules."), + An_instantiation_expression_cannot_be_followed_by_a_property_access: diag(1477, ts.DiagnosticCategory.Error, "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477", "An instantiation expression cannot be followed by a property access."), + Identifier_or_string_literal_expected: diag(1478, ts.DiagnosticCategory.Error, "Identifier_or_string_literal_expected_1478", "Identifier or string literal expected."), + The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead: diag(1479, ts.DiagnosticCategory.Error, "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479", "The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import(\"{0}\")' call instead."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module: diag(1480, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480", "To convert this file to an ECMAScript module, change its file extension to '{0}' or create a local package.json file with `{ \"type\": \"module\" }`."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1: diag(1481, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481", "To convert this file to an ECMAScript module, change its file extension to '{0}', or add the field `\"type\": \"module\"` to '{1}'."), + To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0: diag(1482, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482", "To convert this file to an ECMAScript module, add the field `\"type\": \"module\"` to '{0}'."), + To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module: diag(1483, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483", "To convert this file to an ECMAScript module, create a local package.json file with `{ \"type\": \"module\" }`."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", undefined, true), @@ -5593,8 +5756,11 @@ var ts; Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", undefined, true), The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."), The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."), + This_type_parameter_might_need_an_extends_0_constraint: diag(2208, ts.DiagnosticCategory.Error, "This_type_parameter_might_need_an_extends_0_constraint_2208", "This type parameter might need an `extends {0}` constraint."), The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2209, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209", "The project root is ambiguous, but is required to resolve export map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2210, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210", "The project root is ambiguous, but is required to resolve import map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), + Add_extends_constraint: diag(2211, ts.DiagnosticCategory.Message, "Add_extends_constraint_2211", "Add `extends` constraint."), + Add_extends_constraint_to_all_type_parameters: diag(2212, ts.DiagnosticCategory.Message, "Add_extends_constraint_to_all_type_parameters_2212", "Add `extends` constraint to all type parameters"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5795,6 +5961,7 @@ var ts; Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + A_tuple_type_cannot_be_indexed_with_a_negative_value: diag(2514, ts.DiagnosticCategory.Error, "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514", "A tuple type cannot be indexed with a negative value."), Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), @@ -6077,6 +6244,12 @@ var ts; Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls: diag(2836, ts.DiagnosticCategory.Error, "Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls_2836", "Import assertions are not allowed on statements that transpile to commonjs 'require' calls."), Import_assertion_values_must_be_string_literal_expressions: diag(2837, ts.DiagnosticCategory.Error, "Import_assertion_values_must_be_string_literal_expressions_2837", "Import assertion values must be string literal expressions."), All_declarations_of_0_must_have_identical_constraints: diag(2838, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_constraints_2838", "All declarations of '{0}' must have identical constraints."), + This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value: diag(2839, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839", "This condition will always return '{0}' since JavaScript compares objects by reference, not value."), + An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes: diag(2840, ts.DiagnosticCategory.Error, "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840", "An interface cannot extend a primitive type like '{0}'; an interface can only extend named types and classes"), + The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(2841, ts.DiagnosticCategory.Error, "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841", "The type of this expression cannot be named without a 'resolution-mode' assertion, which is an unstable feature. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + _0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation: diag(2842, ts.DiagnosticCategory.Error, "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842", "'{0}' is an unused renaming of '{1}'. Did you intend to use it as a type annotation?"), + We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here: diag(2843, ts.DiagnosticCategory.Error, "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843", "We can only write a type for '{0}' by adding a type for the entire parameter here."), + Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2844, ts.DiagnosticCategory.Error, "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844", "Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -6184,7 +6357,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), - Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "Resolution mode assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "'resolution-mode' assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -6487,8 +6660,8 @@ var ts; Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Referenced_project_0_may_not_disable_emit: diag(6310, ts.DiagnosticCategory.Error, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."), - Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), - Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_1_is_older_than_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350", "Project '{0}' is out of date because output '{1}' is older than input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than output '{2}'"), Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), @@ -6532,6 +6705,8 @@ var ts; Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6396, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6397, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."), + 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"), 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."), @@ -6772,6 +6947,8 @@ var ts; Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, ts.DiagnosticCategory.Error, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."), The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."), + You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder: diag(8035, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035", "You cannot rename elements that are defined in a 'node_modules' folder."), + You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -7042,6 +7219,9 @@ var ts; For_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, ts.DiagnosticCategory.Error, "For_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'For await' loops cannot be used inside a class static block."), Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, ts.DiagnosticCategory.Error, "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."), A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, ts.DiagnosticCategory.Error, "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."), + _0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation: diag(18042, ts.DiagnosticCategory.Error, "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042", "'{0}' is a type and cannot be imported in JavaScript files. Use '{1}' in a JSDoc type annotation."), + Types_cannot_appear_in_export_declarations_in_JavaScript_files: diag(18043, ts.DiagnosticCategory.Error, "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043", "Types cannot appear in export declarations in JavaScript files."), + _0_is_automatically_exported_here: diag(18044, ts.DiagnosticCategory.Message, "_0_is_automatically_exported_here_18044", "'{0}' is automatically exported here."), }; })(ts || (ts = {})); var ts; @@ -9563,6 +9743,18 @@ var ts; } } ts.getAssignedName = getAssignedName; + function getDecorators(node) { + if (ts.hasDecorators(node)) { + return ts.filter(node.modifiers, ts.isDecorator); + } + } + ts.getDecorators = getDecorators; + function getModifiers(node) { + if (ts.hasSyntacticModifier(node, 125951)) { + return ts.filter(node.modifiers, isModifier); + } + } + ts.getModifiers = getModifiers; function getJSDocParameterTagsWorker(param, noCache) { if (param.name) { if (ts.isIdentifier(param.name)) { @@ -9767,6 +9959,9 @@ var ts; if (node.typeParameters) { return node.typeParameters; } + if (ts.canHaveIllegalTypeParameters(node) && node.typeParameters) { + return node.typeParameters; + } if (ts.isInJSFile(node)) { var decls = ts.getJSDocTypeParameterDeclarations(node); if (decls.length) { @@ -9902,6 +10097,18 @@ var ts; return isLiteralKind(node.kind); } ts.isLiteralExpression = isLiteralExpression; + function isLiteralExpressionOfObject(node) { + switch (node.kind) { + case 205: + case 204: + case 13: + case 213: + case 226: + return true; + } + return false; + } + ts.isLiteralExpressionOfObject = isLiteralExpressionOfObject; function isTemplateLiteralKind(kind) { return 14 <= kind && kind <= 17; } @@ -10091,6 +10298,10 @@ var ts; } } ts.isMethodOrAccessor = isMethodOrAccessor; + function isModifierLike(node) { + return isModifier(node) || ts.isDecorator(node); + } + ts.isModifierLike = isModifierLike; function isTypeElement(node) { var kind = node.kind; return kind === 175 @@ -10614,7 +10825,6 @@ var ts; case 254: case 164: case 203: - case 166: case 167: case 296: case 299: @@ -10664,6 +10874,16 @@ var ts; return node.kind === 324 || node.kind === 325 || node.kind === 326; } ts.isJSDocLinkLike = isJSDocLinkLike; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 318; + } + ts.isRestParameter = isRestParameter; })(ts || (ts = {})); var ts; (function (ts) { @@ -11077,10 +11297,11 @@ var ts; } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { - if (nodeIsMissing(node) || !node.decorators) { + var lastDecorator = !nodeIsMissing(node) && ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + if (!lastDecorator) { return getTokenPosOfNode(node, sourceFile); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastDecorator.end); } ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { @@ -12332,7 +12553,7 @@ var ts; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { - return node.decorators !== undefined + return hasDecorators(node) && nodeCanBeDecorated(node, parent, grandparent); } ts.nodeIsDecorated = nodeIsDecorated; @@ -12408,6 +12629,8 @@ var ts; case 218: case 231: return true; + case 228: + return !ts.isHeritageClause(node.parent); case 161: while (node.parent.kind === 161) { node = node.parent; @@ -12571,9 +12794,6 @@ var ts; } ts.isVariableDeclarationInitializedToBareOrAccessedRequire = isVariableDeclarationInitializedToBareOrAccessedRequire; function isVariableDeclarationInitializedWithRequireHelper(node, allowAccessedRequire) { - if (node.kind === 203) { - node = node.parent.parent; - } return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, true); @@ -13158,16 +13378,6 @@ var ts; return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function hasRestParameter(s) { - var last = ts.lastOrUndefined(s.parameters); - return !!last && isRestParameter(last); - } - ts.hasRestParameter = hasRestParameter; - function isRestParameter(node) { - var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 318; - } - ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { return !!node.typeArguments; } @@ -13270,6 +13480,12 @@ var ts; return [child, node]; } ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild; + function skipTypeParentheses(node) { + while (ts.isParenthesizedTypeNode(node)) + node = node.type; + return node; + } + ts.skipTypeParentheses = skipTypeParentheses; function skipParentheses(node, excludeJSDocTypeAssertions) { var flags = excludeJSDocTypeAssertions ? 1 | 16 : @@ -14683,6 +14899,10 @@ var ts; return hasEffectiveModifier(node, 64); } ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier; + function hasDecorators(node) { + return hasSyntacticModifier(node, 131072); + } + ts.hasDecorators = hasDecorators; function getSelectedEffectiveModifierFlags(node, flags) { return getEffectiveModifierFlags(node) & flags; } @@ -14740,7 +14960,7 @@ var ts; } ts.getEffectiveModifierFlagsNoCache = getEffectiveModifierFlagsNoCache; function getSyntacticModifierFlagsNoCache(node) { - var flags = modifiersToFlags(node.modifiers); + var flags = ts.canHaveModifiers(node) ? modifiersToFlags(node.modifiers) : 0; if (node.flags & 4 || (node.kind === 79 && node.isInJSDocNamespace)) { flags |= 1; } @@ -14774,6 +14994,7 @@ var ts; case 159: return 16384; case 101: return 32768; case 144: return 65536; + case 165: return 131072; } return 0; } @@ -15108,14 +15329,16 @@ var ts; } ts.moveRangePos = moveRangePos; function moveRangePastDecorators(node) { - return node.decorators && node.decorators.length > 0 - ? moveRangePos(node, node.decorators.end) + var lastDecorator = ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + return lastDecorator && !positionIsSynthesized(lastDecorator.end) + ? moveRangePos(node, lastDecorator.end) : node; } ts.moveRangePastDecorators = moveRangePastDecorators; function moveRangePastModifiers(node) { - return node.modifiers && node.modifiers.length > 0 - ? moveRangePos(node, node.modifiers.end) + var lastModifier = ts.canHaveModifiers(node) ? ts.lastOrUndefined(node.modifiers) : undefined; + return lastModifier && !positionIsSynthesized(lastModifier.end) + ? moveRangePos(node, lastModifier.end) : moveRangePastDecorators(node); } ts.moveRangePastModifiers = moveRangePastModifiers; @@ -15221,7 +15444,8 @@ var ts; function getDeclarationModifierFlagsFromSymbol(s, isWrite) { if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 173; })) || s.valueDeclaration; + var declaration = (isWrite && s.declarations && ts.find(s.declarations, ts.isSetAccessorDeclaration)) + || (s.flags & 32768 && ts.find(s.declarations, ts.isGetAccessorDeclaration)) || s.valueDeclaration; var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 ? flags : flags & ~28; } @@ -15843,13 +16067,13 @@ var ts; return !file.isDeclarationFile ? walkTreeForJSXTags(file) : undefined; } function isFileForcedToBeModuleByFormat(file) { - return file.impliedNodeFormat === ts.ModuleKind.ESNext && !file.isDeclarationFile ? true : undefined; + return (file.impliedNodeFormat === ts.ModuleKind.ESNext || (ts.fileExtensionIsOneOf(file.fileName, [".cjs", ".cts", ".mjs", ".mts"]))) && !file.isDeclarationFile ? true : undefined; } function getSetExternalModuleIndicator(options) { switch (getEmitModuleDetectionKind(options)) { case ts.ModuleDetectionKind.Force: return function (file) { - file.externalModuleIndicator = !file.isDeclarationFile || ts.isFileProbablyExternalModule(file); + file.externalModuleIndicator = ts.isFileProbablyExternalModule(file) || !file.isDeclarationFile || undefined; }; case ts.ModuleDetectionKind.Legacy: return function (file) { @@ -15860,10 +16084,7 @@ var ts; if (options.jsx === 4 || options.jsx === 5) { checks.push(isFileModuleFromUsingJSXTag); } - var moduleKind = getEmitModuleKind(options); - if (moduleKind === ts.ModuleKind.Node16 || moduleKind === ts.ModuleKind.NodeNext) { - checks.push(isFileForcedToBeModuleByFormat); - } + checks.push(isFileForcedToBeModuleByFormat); var combined_1 = ts.or.apply(void 0, checks); var callback = function (file) { return void (file.externalModuleIndicator = combined_1(file)); }; return callback; @@ -15905,7 +16126,8 @@ var ts; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; function getEmitModuleDetectionKind(options) { - return options.moduleDetection || ts.ModuleDetectionKind.Auto; + return options.moduleDetection || + (getEmitModuleKind(options) === ts.ModuleKind.Node16 || getEmitModuleKind(options) === ts.ModuleKind.NodeNext ? ts.ModuleDetectionKind.Force : ts.ModuleDetectionKind.Auto); } ts.getEmitModuleDetectionKind = getEmitModuleDetectionKind; function hasJsonModuleEmitEnabled(options) { @@ -15988,6 +16210,10 @@ var ts; return optionsHaveChanges(oldOptions, newOptions, ts.affectsEmitOptionDeclarations); } ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit; + function compilerOptionsAffectDeclarationPath(newOptions, oldOptions) { + return optionsHaveChanges(oldOptions, newOptions, ts.affectsDeclarationPathOptionDeclarations); + } + ts.compilerOptionsAffectDeclarationPath = compilerOptionsAffectDeclarationPath; function getCompilerOptionValue(options, option) { return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; } @@ -16799,8 +17025,12 @@ var ts; return node.parent.templateSpans; case 233: return node.parent.templateSpans; - case 165: - return node.parent.decorators; + case 165: { + var parent_2 = node.parent; + return ts.canHaveDecorators(parent_2) ? parent_2.modifiers : + ts.canHaveIllegalDecorators(parent_2) ? parent_2.illegalDecorators : + undefined; + } case 291: return node.parent.heritageClauses; } @@ -17161,10 +17391,11 @@ var ts; } return parenthesizeLeftSideOfAccess(expression); } - function parenthesizeLeftSideOfAccess(expression) { + function parenthesizeLeftSideOfAccess(expression, optionalChain) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 209 || emittedExpression.arguments)) { + && (emittedExpression.kind !== 209 || emittedExpression.arguments) + && (optionalChain || !ts.isOptionalChain(emittedExpression))) { return expression; } return ts.setTextRange(factory.createParenthesizedExpression(expression), expression); @@ -17979,23 +18210,22 @@ var ts; function createBaseNode(kind) { return baseFactory.createBaseNode(kind); } - function createBaseDeclaration(kind, decorators, modifiers) { + function createBaseDeclaration(kind) { var node = createBaseNode(kind); - node.decorators = asNodeArray(decorators); - node.modifiers = asNodeArray(modifiers); - node.transformFlags |= - propagateChildrenFlags(node.decorators) | - propagateChildrenFlags(node.modifiers); node.symbol = undefined; node.localSymbol = undefined; node.locals = undefined; node.nextContainer = undefined; return node; } - function createBaseNamedDeclaration(kind, decorators, modifiers, name) { - var node = createBaseDeclaration(kind, decorators, modifiers); + function createBaseNamedDeclaration(kind, modifiers, name) { + var node = createBaseDeclaration(kind); name = asName(name); node.name = name; + if (ts.canHaveModifiers(node)) { + node.modifiers = asNodeArray(modifiers); + node.transformFlags |= propagateChildrenFlags(node.modifiers); + } if (name) { switch (node.kind) { case 169: @@ -18014,16 +18244,16 @@ var ts; } return node; } - function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.typeParameters = asNodeArray(typeParameters); node.transformFlags |= propagateChildrenFlags(node.typeParameters); if (typeParameters) node.transformFlags |= 1; return node; } - function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.parameters = createNodeArray(parameters); node.type = type; node.transformFlags |= @@ -18031,48 +18261,43 @@ var ts; propagateChildFlags(node.type); if (type) node.transformFlags |= 1; + node.typeArguments = undefined; return node; } - function updateBaseSignatureDeclaration(updated, original) { - if (original.typeArguments) + function finishUpdateBaseSignatureDeclaration(updated, original) { + if (updated !== original) { updated.typeArguments = original.typeArguments; + } return update(updated, original); } - function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { - var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); + function createBaseFunctionLikeDeclaration(kind, modifiers, name, typeParameters, parameters, type, body) { + var node = createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~16777216; + node.transformFlags |= propagateChildFlags(node.body) & ~67108864; if (!body) node.transformFlags |= 1; return node; } - function updateBaseFunctionLikeDeclaration(updated, original) { - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - if (original.typeArguments) - updated.typeArguments = original.typeArguments; - return updateBaseSignatureDeclaration(updated, original); - } - function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.heritageClauses = asNodeArray(heritageClauses); node.transformFlags |= propagateChildrenFlags(node.heritageClauses); return node; } - function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses); + function createBaseClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members); return node; } - function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseBindingLikeDeclaration(kind, modifiers, name, initializer) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.initializer = initializer; node.transformFlags |= propagateChildFlags(node.initializer); return node; } - function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) { - var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer); + function createBaseVariableLikeDeclaration(kind, modifiers, name, type, initializer) { + var node = createBaseBindingLikeDeclaration(kind, modifiers, name, initializer); node.type = type; node.transformFlags |= propagateChildFlags(type); if (type) @@ -18154,7 +18379,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 132) { - node.transformFlags |= 16777216; + node.transformFlags |= 67108864; } return node; } @@ -18197,7 +18422,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(80); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 8388608; + node.transformFlags |= 16777216; return node; } function createBaseToken(kind) { @@ -18240,13 +18465,13 @@ var ts; transformFlags = 1; break; case 106: - transformFlags = 1024 | 33554432; + transformFlags = 1024 | 134217728; break; case 124: transformFlags = 1024; break; case 108: - transformFlags = 8192; + transformFlags = 16384; break; } if (transformFlags) { @@ -18325,7 +18550,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 | - 65536; + 131072; return node; } function updateComputedPropertyName(node, expression) { @@ -18333,40 +18558,14 @@ var ts; ? update(createComputedPropertyName(expression), node) : node; } - function createTypeParameterDeclaration(modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } - var node = createBaseNamedDeclaration(163, undefined, modifiers, name); + function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) { + var node = createBaseNamedDeclaration(163, modifiers, name); node.constraint = constraint; node.default = defaultType; node.transformFlags = 1; return node; } - function updateTypeParameterDeclaration(node, modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } + function updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType) { return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint @@ -18374,8 +18573,8 @@ var ts; ? update(createTypeParameterDeclaration(modifiers, name, constraint, defaultType), node) : node; } - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(164, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(164, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -18388,30 +18587,30 @@ var ts; if (questionToken) node.transformFlags |= 1; if (ts.modifiersToFlags(node.modifiers) & 16476) - node.transformFlags |= 4096; + node.transformFlags |= 8192; if (initializer || dotDotDotToken) node.transformFlags |= 1024; } return node; } - function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } function createDecorator(expression) { var node = createBaseNode(165); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, false); node.transformFlags |= propagateChildFlags(node.expression) | 1 | - 4096; + 8192 | + 33554432; return node; } function updateDecorator(node, expression) { @@ -18420,10 +18619,11 @@ var ts; : node; } function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(166, undefined, modifiers, name); + var node = createBaseNamedDeclaration(166, modifiers, name); node.type = type; node.questionToken = questionToken; node.transformFlags = 1; + node.initializer = undefined; return node; } function updatePropertySignature(node, modifiers, name, questionToken, type) { @@ -18431,38 +18631,43 @@ var ts; || node.name !== name || node.questionToken !== questionToken || node.type !== type - ? update(createPropertySignature(modifiers, name, questionToken, type), node) + ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) : node; } - function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(167, decorators, modifiers, name, type, initializer); + function finishUpdatePropertySignature(updated, original) { + if (updated !== original) { + updated.initializer = original.initializer; + } + return update(updated, original); + } + function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(167, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 8388608; + 16777216; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 4096; + node.transformFlags |= 8192; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2) { node.transformFlags |= 1; } return node; } - function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.modifiers !== modifiers || node.name !== name || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer - ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node; } function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(168, undefined, modifiers, name, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(168, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1; return node; @@ -18474,11 +18679,11 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node; } - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(169, decorators, modifiers, name, typeParameters, parameters, type, body); + function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(169, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= @@ -18499,11 +18704,11 @@ var ts; else if (asteriskToken) { node.transformFlags |= 2048; } + node.exclamationToken = undefined; return node; } - function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.questionToken !== questionToken @@ -18511,62 +18716,101 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } - function createClassStaticBlockDeclaration(decorators, modifiers, body) { - var node = createBaseGenericNamedDeclaration(170, decorators, modifiers, undefined, undefined); + function finishUpdateMethodDeclaration(updated, original) { + if (updated !== original) { + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } + function createClassStaticBlockDeclaration(body) { + var node = createBaseGenericNamedDeclaration(170, undefined, undefined, undefined); node.body = body; - node.transformFlags = propagateChildFlags(body) | 8388608; + node.transformFlags = propagateChildFlags(body) | 16777216; + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } - function updateClassStaticBlockDeclaration(node, decorators, modifiers, body) { - return node.decorators !== decorators - || node.modifier !== modifiers - || node.body !== body - ? update(createClassStaticBlockDeclaration(decorators, modifiers, body), node) + function updateClassStaticBlockDeclaration(node, body) { + return node.body !== body + ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) : node; } - function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(171, decorators, modifiers, undefined, undefined, parameters, undefined, body); + function finishUpdateClassStaticBlockDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } + function createConstructorDeclaration(modifiers, parameters, body) { + var node = createBaseFunctionLikeDeclaration(171, modifiers, undefined, undefined, parameters, undefined, body); node.transformFlags |= 1024; + node.illegalDecorators = undefined; + node.typeParameters = undefined; + node.type = undefined; return node; } - function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateConstructorDeclaration(node, modifiers, parameters, body) { + return node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node) + ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) : node; } - function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(172, decorators, modifiers, name, undefined, parameters, type, body); + function finishUpdateConstructorDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); } - function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function createGetAccessorDeclaration(modifiers, name, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(172, modifiers, name, undefined, parameters, type, body); + node.typeParameters = undefined; + return node; + } + function updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node) + ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) : node; } - function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(173, decorators, modifiers, name, undefined, parameters, undefined, body); + function finishUpdateGetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + } + return finishUpdateBaseSignatureDeclaration(updated, original); } - function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function createSetAccessorDeclaration(modifiers, name, parameters, body) { + var node = createBaseFunctionLikeDeclaration(173, modifiers, name, undefined, parameters, undefined, body); + node.typeParameters = undefined; + node.type = undefined; + return node; + } + function updateSetAccessorDeclaration(node, modifiers, name, parameters, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node) + ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) : node; } + function finishUpdateSetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } function createCallSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(174, undefined, undefined, undefined, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(174, undefined, undefined, typeParameters, parameters, type); node.transformFlags = 1; return node; } @@ -18574,11 +18818,11 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node; } function createConstructSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(175, undefined, undefined, undefined, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(175, undefined, undefined, typeParameters, parameters, type); node.transformFlags = 1; return node; } @@ -18586,20 +18830,19 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node; } - function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(176, decorators, modifiers, undefined, undefined, parameters, type); + function createIndexSignature(modifiers, parameters, type) { + var node = createBaseSignatureDeclaration(176, modifiers, undefined, undefined, parameters, type); node.transformFlags = 1; return node; } - function updateIndexSignature(node, decorators, modifiers, parameters, type) { + function updateIndexSignature(node, modifiers, parameters, type) { return node.parameters !== parameters || node.type !== type - || node.decorators !== decorators || node.modifiers !== modifiers - ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node; } function createTemplateLiteralTypeSpan(type, literal) { @@ -18647,17 +18890,24 @@ var ts; : node; } function createFunctionTypeNode(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(179, undefined, undefined, undefined, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(179, undefined, undefined, typeParameters, parameters, type); node.transformFlags = 1; + node.modifiers = undefined; return node; } function updateFunctionTypeNode(node, typeParameters, parameters, type) { return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node) + ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) : node; } + function finishUpdateFunctionTypeNode(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } function createConstructorTypeNode() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -18668,7 +18918,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(180, undefined, modifiers, undefined, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(180, modifiers, undefined, typeParameters, parameters, type); node.transformFlags = 1; return node; } @@ -18689,7 +18939,7 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node; } function updateConstructorTypeNode2(node, typeParameters, parameters, type) { @@ -18844,33 +19094,25 @@ var ts; ? update(createTemplateLiteralType(head, templateSpans), node) : node; } - function createImportTypeNode(argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : false; + function createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = false; } var node = createBaseNode(200); node.argument = argument; - node.assertions = assertion; + node.assertions = assertions; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.isTypeOf = isTypeOf; node.transformFlags = 1; return node; } - function updateImportTypeNode(node, argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : node.isTypeOf; + function updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; } return node.argument !== argument - || node.assertions !== assertion + || node.assertions !== assertions || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf - ? update(createImportTypeNode(argument, assertion, qualifier, typeArguments, isTypeOf), node) + ? update(createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf), node) : node; } function createParenthesizedType(type) { @@ -18954,11 +19196,11 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 | - 262144; - if (node.transformFlags & 16384) { + 524288; + if (node.transformFlags & 32768) { node.transformFlags |= 128 | - 32768; + 65536; } return node; } @@ -18973,7 +19215,7 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 | - 262144; + 524288; return node; } function updateArrayBindingPattern(node, elements) { @@ -18982,7 +19224,7 @@ var ts; : node; } function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createBaseBindingLikeDeclaration(203, undefined, undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + var node = createBaseBindingLikeDeclaration(203, undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= @@ -18994,7 +19236,7 @@ var ts; propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 16384; + node.transformFlags |= 32768; return node; } function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { @@ -19037,13 +19279,13 @@ var ts; } function createPropertyAccessExpression(expression, name) { var node = createBaseExpression(206); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, false); node.name = asName(name); node.transformFlags = propagateChildFlags(node.expression) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912); if (ts.isSuperKeyword(expression)) { node.transformFlags |= 256 | @@ -19063,7 +19305,7 @@ var ts; function createPropertyAccessChain(expression, questionDotToken, name) { var node = createBaseExpression(206); node.flags |= 32; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, true); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= @@ -19072,7 +19314,7 @@ var ts; propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912); return node; } function updatePropertyAccessChain(node, expression, questionDotToken, name) { @@ -19085,7 +19327,7 @@ var ts; } function createElementAccessExpression(expression, index) { var node = createBaseExpression(207); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, false); node.argumentExpression = asExpression(index); node.transformFlags |= propagateChildFlags(node.expression) | @@ -19109,7 +19351,7 @@ var ts; function createElementAccessChain(expression, questionDotToken, index) { var node = createBaseExpression(207); node.flags |= 32; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, true); node.questionDotToken = questionDotToken; node.argumentExpression = asExpression(index); node.transformFlags |= @@ -19129,7 +19371,7 @@ var ts; } function createCallExpression(expression, typeArguments, argumentsArray) { var node = createBaseExpression(208); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, false); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); node.transformFlags |= @@ -19140,10 +19382,10 @@ var ts; node.transformFlags |= 1; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 4194304; + node.transformFlags |= 8388608; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192; + node.transformFlags |= 16384; } return node; } @@ -19160,7 +19402,7 @@ var ts; function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { var node = createBaseExpression(208); node.flags |= 32; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, true); node.questionDotToken = questionDotToken; node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -19174,7 +19416,7 @@ var ts; node.transformFlags |= 1; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192; + node.transformFlags |= 16384; } return node; } @@ -19211,7 +19453,7 @@ var ts; } function createTaggedTemplateExpression(tag, typeArguments, template) { var node = createBaseExpression(210); - node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); + node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, false); node.typeArguments = asNodeArray(typeArguments); node.template = template; node.transformFlags |= @@ -19262,7 +19504,7 @@ var ts; : node; } function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(213, undefined, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(213, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); if (node.typeParameters) { @@ -19289,17 +19531,17 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(214, undefined, modifiers, undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); + var node = createBaseFunctionLikeDeclaration(214, modifiers, undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | 1024; if (ts.modifiersToFlags(node.modifiers) & 256) { - node.transformFlags |= 256 | 8192; + node.transformFlags |= 256 | 16384; } return node; } @@ -19310,7 +19552,7 @@ var ts; || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } function createDeleteExpression(expression) { @@ -19353,7 +19595,7 @@ var ts; propagateChildFlags(node.expression) | 256 | 128 | - 1048576; + 2097152; return node; } function updateAwaitExpression(node, expression) { @@ -19370,7 +19612,7 @@ var ts; ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864; + node.transformFlags |= 268435456; } return node; } @@ -19387,7 +19629,7 @@ var ts; if (ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864; + node.transformFlags |= 268435456; } return node; } @@ -19431,18 +19673,21 @@ var ts; else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { node.transformFlags |= 16; } + if (operatorKind === 101 && ts.isPrivateIdentifier(node.left)) { + node.transformFlags |= 536870912; + } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 32768) - return 32768; + if (node.transformFlags & 65536) + return 65536; if (node.transformFlags & 128) { for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) { var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 32768) { - return 32768; + if (target.transformFlags & 65536) { + return 65536; } if (target.transformFlags & 128) { var flags_1 = propagateAssignmentPatternFlags(target); @@ -19555,7 +19800,7 @@ var ts; propagateChildFlags(node.asteriskToken) | 1024 | 128 | - 524288; + 1048576; return node; } function updateYieldExpression(node, asteriskToken, expression) { @@ -19570,7 +19815,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 | - 16384; + 32768; return node; } function updateSpreadElement(node, expression) { @@ -19578,19 +19823,18 @@ var ts; ? update(createSpreadElement(expression), node) : node; } - function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(226, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(226, modifiers, name, typeParameters, heritageClauses, members); node.transformFlags |= 1024; return node; } - function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; } function createOmittedExpression() { @@ -19598,7 +19842,7 @@ var ts; } function createExpressionWithTypeArguments(expression, typeArguments) { var node = createBaseNode(228); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | @@ -19630,7 +19874,7 @@ var ts; } function createNonNullExpression(expression) { var node = createBaseExpression(230); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, false); node.transformFlags |= propagateChildFlags(node.expression) | 1; @@ -19647,7 +19891,7 @@ var ts; function createNonNullChain(expression) { var node = createBaseExpression(230); node.flags |= 32; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, true); node.transformFlags |= propagateChildFlags(node.expression) | 1; @@ -19715,10 +19959,12 @@ var ts; : node; } function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(237, undefined, modifiers); + var node = createBaseDeclaration(237); + node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= - propagateChildFlags(node.declarationList); + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.declarationList); if (ts.modifiersToFlags(node.modifiers) & 2) { node.transformFlags = 1; } @@ -19860,7 +20106,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152; + 4194304; return node; } function updateContinueStatement(node, label) { @@ -19873,7 +20119,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152; + 4194304; return node; } function updateBreakStatement(node, label) { @@ -19887,7 +20133,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 | - 2097152; + 4194304; return node; } function updateReturnStatement(node, expression) { @@ -19973,7 +20219,7 @@ var ts; return createBaseNode(253); } function createVariableDeclaration(name, exclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(254, undefined, undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + var node = createBaseVariableLikeDeclaration(254, undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; node.transformFlags |= propagateChildFlags(node.exclamationToken); if (exclamationToken) { @@ -19996,11 +20242,11 @@ var ts; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 2097152; + 4194304; if (flags & 3) { node.transformFlags |= 1024 | - 131072; + 262144; } return node; } @@ -20009,8 +20255,8 @@ var ts; ? update(createVariableDeclarationList(declarations, node.flags), node) : node; } - function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(256, decorators, modifiers, name, typeParameters, parameters, type, body); + function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(256, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2) { node.transformFlags = 1; @@ -20018,7 +20264,7 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 2097152; + 4194304; if (ts.modifiersToFlags(node.modifiers) & 256) { if (node.asteriskToken) { node.transformFlags |= 128; @@ -20031,94 +20277,118 @@ var ts; node.transformFlags |= 2048; } } + node.illegalDecorators = undefined; return node; } - function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } - function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(257, decorators, modifiers, name, typeParameters, heritageClauses, members); + function finishUpdateFunctionDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } + function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(257, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2) { node.transformFlags = 1; } else { node.transformFlags |= 1024; - if (node.transformFlags & 4096) { + if (node.transformFlags & 8192) { node.transformFlags |= 1; } } return node; } - function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } - function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(258, decorators, modifiers, name, typeParameters, heritageClauses); + function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(258, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1; + node.illegalDecorators = undefined; return node; } - function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? finishUpdateInterfaceDeclaration(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } - function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(259, decorators, modifiers, name, typeParameters); + function finishUpdateInterfaceDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } + function createTypeAliasDeclaration(modifiers, name, typeParameters, type) { + var node = createBaseGenericNamedDeclaration(259, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1; + node.illegalDecorators = undefined; return node; } - function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type - ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + ? finishUpdateTypeAliasDeclaration(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; } - function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(260, decorators, modifiers, name); + function finishUpdateTypeAliasDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } + function createEnumDeclaration(modifiers, name, members) { + var node = createBaseNamedDeclaration(260, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1; - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; + node.illegalDecorators = undefined; return node; } - function updateEnumDeclaration(node, decorators, modifiers, name, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateEnumDeclaration(node, modifiers, name, members) { + return node.modifiers !== modifiers || node.name !== name || node.members !== members - ? update(createEnumDeclaration(decorators, modifiers, name, members), node) + ? finishUpdateEnumDeclaration(createEnumDeclaration(modifiers, name, members), node) : node; } - function createModuleDeclaration(decorators, modifiers, name, body, flags) { + function finishUpdateEnumDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } + function createModuleDeclaration(modifiers, name, body, flags) { if (flags === void 0) { flags = 0; } - var node = createBaseDeclaration(261, decorators, modifiers); + var node = createBaseDeclaration(261); + node.modifiers = asNodeArray(modifiers); node.flags |= flags & (16 | 4 | 1024); node.name = name; node.body = body; @@ -20127,21 +20397,28 @@ var ts; } else { node.transformFlags |= - propagateChildFlags(node.name) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1; } - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; + node.illegalDecorators = undefined; return node; } - function updateModuleDeclaration(node, decorators, modifiers, name, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateModuleDeclaration(node, modifiers, name, body) { + return node.modifiers !== modifiers || node.name !== name || node.body !== body - ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + ? finishUpdateModuleDeclaration(createModuleDeclaration(modifiers, name, body, node.flags), node) : node; } + function finishUpdateModuleDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } function createModuleBlock(statements) { var node = createBaseNode(262); node.statements = createNodeArray(statements); @@ -20165,54 +20442,76 @@ var ts; : node; } function createNamespaceExportDeclaration(name) { - var node = createBaseNamedDeclaration(264, undefined, undefined, name); + var node = createBaseNamedDeclaration(264, undefined, name); node.transformFlags = 1; + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } function updateNamespaceExportDeclaration(node, name) { return node.name !== name - ? update(createNamespaceExportDeclaration(name), node) + ? finishUpdateNamespaceExportDeclaration(createNamespaceExportDeclaration(name), node) : node; } - function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(265, decorators, modifiers, name); + function finishUpdateNamespaceExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } + function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) { + var node = createBaseNamedDeclaration(265, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1; - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; + node.illegalDecorators = undefined; return node; } - function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference - ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node) + ? finishUpdateImportEqualsDeclaration(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; } - function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(266, decorators, modifiers); + function finishUpdateImportEqualsDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } + function createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(266); + node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; + node.illegalDecorators = undefined; return node; } - function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause), node) + ? finishUpdateImportDeclaration(createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateImportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } function createImportClause(isTypeOnly, name, namedBindings) { var node = createBaseNode(267); node.isTypeOnly = isTypeOnly; @@ -20224,7 +20523,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1; } - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; return node; } function updateImportClause(node, isTypeOnly, name, namedBindings) { @@ -20276,7 +20575,7 @@ var ts; var node = createBaseNode(268); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; return node; } function updateNamespaceImport(node, name) { @@ -20290,7 +20589,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.name) | 4; - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; return node; } function updateNamespaceExport(node, name) { @@ -20302,7 +20601,7 @@ var ts; var node = createBaseNode(269); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; return node; } function updateNamedImports(node, elements) { @@ -20318,7 +20617,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; return node; } function updateImportSpecifier(node, isTypeOnly, propertyName, name) { @@ -20328,50 +20627,65 @@ var ts; ? update(createImportSpecifier(isTypeOnly, propertyName, name), node) : node; } - function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(271, decorators, modifiers); + function createExportAssignment(modifiers, isExportEquals, expression) { + var node = createBaseDeclaration(271); + node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(63, undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); - node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216; + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); + node.transformFlags &= ~67108864; + node.illegalDecorators = undefined; return node; } - function updateExportAssignment(node, decorators, modifiers, expression) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportAssignment(node, modifiers, expression) { + return node.modifiers !== modifiers || node.expression !== expression - ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + ? finishUpdateExportAssignment(createExportAssignment(modifiers, node.isExportEquals, expression), node) : node; } - function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(272, decorators, modifiers); + function finishUpdateExportAssignment(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } + function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(272); + node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= - propagateChildFlags(node.exportClause) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; + node.illegalDecorators = undefined; return node; } - function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) + ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } function createNamedExports(elements) { var node = createBaseNode(273); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; return node; } function updateNamedExports(node, elements) { @@ -20387,7 +20701,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; return node; } function updateExportSpecifier(node, isTypeOnly, propertyName, name) { @@ -20398,14 +20712,14 @@ var ts; : node; } function createMissingDeclaration() { - var node = createBaseDeclaration(276, undefined, undefined); + var node = createBaseDeclaration(276); return node; } function createExternalModuleReference(expression) { var node = createBaseNode(277); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216; + node.transformFlags &= ~67108864; return node; } function updateExternalModuleReference(node, expression) { @@ -20438,7 +20752,7 @@ var ts; : node; } function createJSDocFunctionType(parameters, type) { - var node = createBaseSignatureDeclaration(317, undefined, undefined, undefined, undefined, parameters, type); + var node = createBaseSignatureDeclaration(317, undefined, undefined, undefined, parameters, type); return node; } function updateJSDocFunctionType(node, parameters, type) { @@ -20977,64 +21291,68 @@ var ts; : node; } function createPropertyAssignment(name, initializer) { - var node = createBaseNamedDeclaration(296, undefined, undefined, name); + var node = createBaseNamedDeclaration(296, undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer); + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdatePropertyAssignment(updated, original) { - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } function updatePropertyAssignment(node, name, initializer) { return node.name !== name || node.initializer !== initializer ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) : node; } + function finishUpdatePropertyAssignment(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createBaseNamedDeclaration(297, undefined, undefined, name); + var node = createBaseNamedDeclaration(297, undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | 1024; + node.equalsToken = undefined; + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdateShorthandPropertyAssignment(updated, original) { - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.equalsToken) - updated.equalsToken = original.equalsToken; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { return node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) : node; } + function finishUpdateShorthandPropertyAssignment(updated, original) { + if (updated !== original) { + updated.equalsToken = original.equalsToken; + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } function createSpreadAssignment(expression) { var node = createBaseNode(298); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | 128 | - 32768; + 65536; return node; } function updateSpreadAssignment(node, expression) { @@ -21278,10 +21596,10 @@ var ts; return createVoidExpression(createNumericLiteral("0")); } function createExportDefault(expression) { - return createExportAssignment(undefined, undefined, false, expression); + return createExportAssignment(undefined, false, expression); } function createExternalModuleExport(exportName) { - return createExportDeclaration(undefined, undefined, false, createNamedExports([ + return createExportDeclaration(undefined, false, createNamedExports([ createExportSpecifier(false, undefined, exportName) ])); } @@ -21416,7 +21734,7 @@ var ts; } else if (ts.getEmitFlags(callee) & 4096) { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee, false); } else if (ts.isPropertyAccessExpression(callee)) { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { @@ -21442,13 +21760,13 @@ var ts; } else { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, false); } return { target: target, thisArg: thisArg }; } function createAssignmentTargetWrapper(paramName, expression) { return createPropertyAccessExpression(createParenthesizedExpression(createObjectLiteralExpression([ - createSetAccessorDeclaration(undefined, undefined, "value", [createParameterDeclaration(undefined, undefined, undefined, paramName, undefined, undefined, undefined)], createBlock([ + createSetAccessorDeclaration(undefined, "value", [createParameterDeclaration(undefined, undefined, paramName, undefined, undefined, undefined)], createBlock([ createExpressionStatement(expression) ])) ])), "value"); @@ -21624,30 +21942,32 @@ var ts; else { modifierArray = modifiers; } - return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : - ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : - ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : - ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifierArray, node.parameters, node.body) : - ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.type, node.body) : - ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.body) : - ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifierArray, node.parameters, node.type) : - ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : - ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : - ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.type) : - ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifierArray, node.name, node.members) : - ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifierArray, node.name, node.body) : - ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : - ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : - ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifierArray, node.expression) : - ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : - ts.Debug.assertNever(node); + return ts.isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : + ts.isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : + ts.isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : + ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : + ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : + ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : + ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : + ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : + ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : + ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : + ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : + ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : + ts.isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : + ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : + ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : + ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : + ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : + ts.isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : + ts.isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : + ts.isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : + ts.Debug.assertNever(node); } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -21752,10 +22072,10 @@ var ts; return tokenValue; } function propagateIdentifierNameFlags(node) { - return propagateChildFlags(node) & ~16777216; + return propagateChildFlags(node) & ~67108864; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 33562624); + return transformFlags | (node.transformFlags & 134234112); } function propagateChildFlags(child) { if (!child) @@ -21782,29 +22102,29 @@ var ts; case 208: case 209: case 204: - return 536887296; + return -2147450880; case 261: - return 589443072; + return -1941676032; case 164: - return 536870912; + return -2147483648; case 214: - return 557748224; + return -2072174592; case 213: case 256: - return 591310848; + return -1937940480; case 255: - return 537165824; + return -2146893824; case 257: case 226: - return 536940544; + return -2147344384; case 171: - return 591306752; + return -1937948672; case 167: - return 570433536; + return -2013249536; case 169: case 172: case 173: - return 574529536; + return -2005057536; case 130: case 147: case 158: @@ -21824,23 +22144,23 @@ var ts; case 259: return -2; case 205: - return 536973312; + return -2147278848; case 292: - return 536903680; + return -2147418112; case 201: case 202: - return 536887296; + return -2147450880; case 211: case 229: case 350: case 212: case 106: - return 536870912; + return -2147483648; case 206: case 207: - return 536870912; + return -2147483648; default: - return 536870912; + return -2147483648; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -22897,6 +23217,10 @@ var ts; return node.kind === 126; } ts.isAbstractModifier = isAbstractModifier; + function isOverrideModifier(node) { + return node.kind === 159; + } + ts.isOverrideModifier = isOverrideModifier; function isSuperKeyword(node) { return node.kind === 106; } @@ -23341,6 +23665,10 @@ var ts; return node.kind === 267; } ts.isImportClause = isImportClause; + function isImportTypeAssertionContainer(node) { + return node.kind === 295; + } + ts.isImportTypeAssertionContainer = isImportTypeAssertionContainer; function isAssertClause(node) { return node.kind === 293; } @@ -23657,7 +23985,7 @@ var ts; var ts; (function (ts) { function createEmptyExports(factory) { - return factory.createExportDeclaration(undefined, undefined, false, factory.createNamedExports([]), undefined); + return factory.createExportDeclaration(undefined, false, factory.createNamedExports([]), undefined); } ts.createEmptyExports = createEmptyExports; function createMemberAccessForPropertyName(factory, target, memberName, location) { @@ -23791,8 +24119,8 @@ var ts; return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({ enumerable: factory.createFalse(), configurable: true, - get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body), getAccessor), getAccessor), - set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body), setAccessor), setAccessor) + get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(getAccessor), undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body), getAccessor), getAccessor), + set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(setAccessor), undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body), setAccessor), setAccessor) }, !multiLine)), firstAccessor); } return undefined; @@ -23804,7 +24132,7 @@ var ts; return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, property.name), factory.cloneNode(property.name)), property), property); } function createExpressionForMethodDeclaration(factory, method, receiver) { - return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body), method), method)), method), method); + return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(ts.getModifiers(method), method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body), method), method)), method), method); } function createExpressionForObjectLiteralElementLike(factory, node, property, receiver) { if (property.name && ts.isPrivateIdentifier(property.name)) { @@ -23982,7 +24310,7 @@ var ts; } } if (namedBindings) { - var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration(undefined, undefined, nodeFactory.createImportClause(false, undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText), undefined); + var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration(undefined, nodeFactory.createImportClause(false, undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText), undefined); ts.addEmitFlags(externalHelpersImportDeclaration, 67108864); return externalHelpersImportDeclaration; } @@ -24191,33 +24519,50 @@ var ts; } } ts.getJSDocTypeAliasName = getJSDocTypeAliasName; - function canHaveModifiers(node) { + function canHaveIllegalType(node) { var kind = node.kind; - return kind === 164 - || kind === 166 - || kind === 167 - || kind === 168 - || kind === 169 - || kind === 171 + return kind === 171 + || kind === 173; + } + ts.canHaveIllegalType = canHaveIllegalType; + function canHaveIllegalTypeParameters(node) { + var kind = node.kind; + return kind === 171 || kind === 172 - || kind === 173 + || kind === 173; + } + ts.canHaveIllegalTypeParameters = canHaveIllegalTypeParameters; + function canHaveIllegalDecorators(node) { + var kind = node.kind; + return kind === 296 + || kind === 297 + || kind === 256 + || kind === 171 || kind === 176 - || kind === 213 - || kind === 214 - || kind === 226 + || kind === 170 + || kind === 276 || kind === 237 - || kind === 256 - || kind === 257 || kind === 258 || kind === 259 || kind === 260 || kind === 261 || kind === 265 || kind === 266 - || kind === 271 - || kind === 272; + || kind === 264 + || kind === 272 + || kind === 271; } - ts.canHaveModifiers = canHaveModifiers; + ts.canHaveIllegalDecorators = canHaveIllegalDecorators; + function canHaveIllegalModifiers(node) { + var kind = node.kind; + return kind === 170 + || kind === 296 + || kind === 297 + || kind === 179 + || kind === 276 + || kind === 264; + } + ts.canHaveIllegalModifiers = canHaveIllegalModifiers; ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); @@ -24440,6 +24785,14 @@ var ts; } } ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; + function elideNodes(factory, nodes) { + if (nodes === undefined) + return undefined; + if (nodes.length === 0) + return nodes; + return ts.setTextRange(factory.createNodeArray([], nodes.hasTrailingComma), nodes); + } + ts.elideNodes = elideNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -24447,6 +24800,46 @@ var ts; return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range; } ts.setTextRange = setTextRange; + function canHaveModifiers(node) { + var kind = node.kind; + return kind === 163 + || kind === 164 + || kind === 166 + || kind === 167 + || kind === 168 + || kind === 169 + || kind === 171 + || kind === 172 + || kind === 173 + || kind === 176 + || kind === 180 + || kind === 213 + || kind === 214 + || kind === 226 + || kind === 237 + || kind === 256 + || kind === 257 + || kind === 258 + || kind === 259 + || kind === 260 + || kind === 261 + || kind === 265 + || kind === 266 + || kind === 271 + || kind === 272; + } + ts.canHaveModifiers = canHaveModifiers; + function canHaveDecorators(node) { + var kind = node.kind; + return kind === 164 + || kind === 167 + || kind === 169 + || kind === 172 + || kind === 173 + || kind === 226 + || kind === 257; + } + ts.canHaveDecorators = canHaveDecorators; })(ts || (ts = {})); var ts; (function (ts) { @@ -24492,7 +24885,7 @@ var ts; } ts.isFileProbablyExternalModule = isFileProbablyExternalModule; function isAnExternalModuleIndicatorNode(node) { - return hasModifierOfKind(node, 93) + return ts.canHaveModifiers(node) && hasModifierOfKind(node, 93) || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) || ts.isImportDeclaration(node) || ts.isExportAssignment(node) @@ -24527,7 +24920,7 @@ var ts; visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); case 297: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || @@ -24537,79 +24930,128 @@ var ts; case 298: return visitNode(cbNode, node.expression); case 164: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 167: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 166: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 296: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.initializer); case 254: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || + return visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 203: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.dotDotDotToken) || + return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 179: - case 180: - case 174: - case 175: case 176: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); + case 180: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 179: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 174: + case 175: + return visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 169: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 168: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 171: + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 172: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 173: - case 213: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 256: - case 214: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 213: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 214: + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); case 170: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.body); case 178: @@ -24737,7 +25179,7 @@ var ts; return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); case 237: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); case 255: @@ -24802,27 +25244,26 @@ var ts; return visitNode(cbNode, node.expression); case 257: case 226: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 258: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 259: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); case 260: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); @@ -24830,17 +25271,17 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 261: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); case 265: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); case 266: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -24854,7 +25295,8 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.value); case 264: - return visitNode(cbNode, node.name); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNode(cbNode, node.name); case 268: return visitNode(cbNode, node.name); case 274: @@ -24863,7 +25305,7 @@ var ts; case 273: return visitNodes(cbNode, cbNodes, node.elements); case 272: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -24873,17 +25315,21 @@ var ts; return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); case 271: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); case 223: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 233: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.literal); case 198: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 199: - return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.literal); case 162: return visitNode(cbNode, node.expression); case 291: @@ -24894,7 +25340,8 @@ var ts; case 277: return visitNode(cbNode, node.expression); case 276: - return visitNodes(cbNode, cbNodes, node.decorators); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers); case 351: return visitNodes(cbNode, cbNodes, node.elements); case 278: @@ -25431,7 +25878,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768) - && !!(node.transformFlags & 16777216); + && !!(node.transformFlags & 67108864); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -25465,7 +25912,7 @@ var ts; var sourceFile = factory.createSourceFile(statements, endOfFileToken, flags); ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setFields(sourceFile); - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864) { sourceFile = reparseTopLevelAwait(sourceFile); setFields(sourceFile); } @@ -26253,11 +26700,11 @@ var ts; } return parseElement(); } - function currentNode(parsingContext) { + function currentNode(parsingContext, pos) { if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } - var node = syntaxCursor.currentNode(scanner.getStartPos()); + var node = syntaxCursor.currentNode(pos !== null && pos !== void 0 ? pos : scanner.getStartPos()); if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) { return undefined; } @@ -26455,7 +26902,9 @@ var ts; case 23: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 13: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 14: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - default: return [undefined]; + case 24: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_or_string_literal_expected); + case 25: return ts.Debug.fail("ParsingContext.Count used as a context"); + default: ts.Debug.assertNever(context); } } function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { @@ -26710,7 +27159,7 @@ var ts; name = parseIdentifierName(); parseExpected(58); } - return finishNode(factory.createParameterDeclaration(undefined, undefined, undefined, name, undefined, parseJSDocType(), undefined), pos); + return finishNode(factory.createParameterDeclaration(undefined, undefined, name, undefined, parseJSDocType(), undefined), pos); } function parseJSDocType() { scanner.setInJSDocType(true); @@ -26801,9 +27250,9 @@ var ts; if (allowAmbiguity === void 0) { allowAmbiguity = true; } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : doOutsideOfAwaitContext(parseDecorators); if (token() === 108) { - var node_1 = factory.createParameterDeclaration(decorators, undefined, undefined, createIdentifier(true), undefined, parseTypeAnnotation(), undefined); + var node_1 = factory.createParameterDeclaration(decorators, undefined, createIdentifier(true), undefined, parseTypeAnnotation(), undefined); if (decorators) { parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); } @@ -26811,12 +27260,12 @@ var ts; } var savedTopLevel = topLevel; topLevel = false; - var modifiers = parseModifiers(); + var modifiers = combineDecoratorsAndModifiers(decorators, parseModifiers()); var dotDotDotToken = parseOptionalToken(25); if (!allowAmbiguity && !isParameterNameStart()) { return undefined; } - var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createParameterDeclaration(modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); topLevel = savedTopLevel; return node; } @@ -26914,7 +27363,8 @@ var ts; var parameters = parseBracketedList(16, function () { return parseParameter(false); }, 22, 23); var type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - var node = factory.createIndexSignature(decorators, modifiers, parameters, type); + var node = factory.createIndexSignature(modifiers, parameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) { @@ -26976,10 +27426,10 @@ var ts; var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); if (parseContextualModifier(136)) { - return parseAccessorDeclaration(pos, hasJSDoc, undefined, modifiers, 172); + return parseAccessorDeclaration(pos, hasJSDoc, undefined, modifiers, 172, 4); } if (parseContextualModifier(149)) { - return parseAccessorDeclaration(pos, hasJSDoc, undefined, modifiers, 173); + return parseAccessorDeclaration(pos, hasJSDoc, undefined, modifiers, 173, 4); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, undefined, modifiers); @@ -27581,10 +28031,10 @@ var ts; setDecoratorContext(false); } var pos = getNodePos(); - var expr = parseAssignmentExpressionOrHigher(); + var expr = parseAssignmentExpressionOrHigher(true); var operatorToken; while ((operatorToken = parseOptionalToken(27))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos); + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(true), pos); } if (saveDecoratorContext) { setDecoratorContext(true); @@ -27592,25 +28042,25 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(63) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(63) ? parseAssignmentExpressionOrHigher(true) : undefined; } - function parseAssignmentExpressionOrHigher() { + function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) { if (isYieldExpression()) { return parseYieldExpression(); } - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + var arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction); if (arrowExpression) { return arrowExpression; } var pos = getNodePos(); var expr = parseBinaryExpressionOrHigher(0); if (expr.kind === 79 && token() === 38) { - return parseSimpleArrowFunctionExpression(pos, expr, undefined); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, undefined); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos); + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); } - return parseConditionalExpressionRest(expr, pos); + return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction); } function isYieldExpression() { if (token() === 125) { @@ -27630,30 +28080,30 @@ var ts; nextToken(); if (!scanner.hasPrecedingLineBreak() && (token() === 41 || isStartOfExpression())) { - return finishNode(factory.createYieldExpression(parseOptionalToken(41), parseAssignmentExpressionOrHigher()), pos); + return finishNode(factory.createYieldExpression(parseOptionalToken(41), parseAssignmentExpressionOrHigher(true)), pos); } else { return finishNode(factory.createYieldExpression(undefined, undefined), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { ts.Debug.assert(token() === 38, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var parameter = factory.createParameterDeclaration(undefined, undefined, undefined, identifier, undefined, undefined, undefined); + var parameter = factory.createParameterDeclaration(undefined, undefined, identifier, undefined, undefined, undefined); finishNode(parameter, identifier.pos); var parameters = createNodeArray([parameter], parameter.pos, parameter.end); var equalsGreaterThanToken = parseExpectedToken(38); - var body = parseArrowFunctionExpressionBody(!!asyncModifier); + var body = parseArrowFunctionExpressionBody(!!asyncModifier, allowReturnTypeInArrowFunction); var node = factory.createArrowFunction(asyncModifier, undefined, parameters, undefined, equalsGreaterThanToken, body); return addJSDocComment(finishNode(node, pos)); } - function tryParseParenthesizedArrowFunctionExpression() { + function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var triState = isParenthesizedArrowFunctionExpression(); if (triState === 0) { return undefined; } return triState === 1 ? - parseParenthesizedArrowFunctionExpression(true) : - tryParse(parsePossibleParenthesizedArrowFunctionExpression); + parseParenthesizedArrowFunctionExpression(true, true) : + tryParse(function () { return parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction); }); } function isParenthesizedArrowFunctionExpression() { if (token() === 20 || token() === 29 || token() === 131) { @@ -27695,7 +28145,7 @@ var ts; return 1; } if (ts.isModifierKind(second) && second !== 131 && lookAhead(nextTokenIsIdentifier)) { - if (lookAhead(function () { return nextToken() === 127; })) { + if (nextToken() === 127) { return 0; } return 1; @@ -27750,24 +28200,24 @@ var ts; return 2; } } - function parsePossibleParenthesizedArrowFunctionExpression() { + function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var tokenPos = scanner.getTokenPos(); if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) { return undefined; } - var result = parseParenthesizedArrowFunctionExpression(false); + var result = parseParenthesizedArrowFunctionExpression(false, allowReturnTypeInArrowFunction); if (!result) { (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos); } return result; } - function tryParseAsyncSimpleArrowFunctionExpression() { + function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) { if (token() === 131) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1) { var pos = getNodePos(); var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0); - return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); } } return undefined; @@ -27785,7 +28235,7 @@ var ts; } return 0; } - function parseParenthesizedArrowFunctionExpression(allowAmbiguity) { + function parseParenthesizedArrowFunctionExpression(allowAmbiguity, allowReturnTypeInArrowFunction) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiersForArrowFunction(); @@ -27813,6 +28263,7 @@ var ts; return undefined; } } + var hasReturnColon = token() === 58; var type = parseReturnType(58, false); if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) { return undefined; @@ -27828,12 +28279,17 @@ var ts; var lastToken = token(); var equalsGreaterThanToken = parseExpectedToken(38); var body = (lastToken === 38 || lastToken === 18) - ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier)) + ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier(); + if (!allowReturnTypeInArrowFunction && hasReturnColon) { + if (token() !== 58) { + return undefined; + } + } var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseArrowFunctionExpressionBody(isAsync) { + function parseArrowFunctionExpressionBody(isAsync, allowReturnTypeInArrowFunction) { if (token() === 18) { return parseFunctionBlock(isAsync ? 2 : 0); } @@ -27847,19 +28303,19 @@ var ts; var savedTopLevel = topLevel; topLevel = false; var node = isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + ? doInAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }) + : doOutsideOfAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }); topLevel = savedTopLevel; return node; } - function parseConditionalExpressionRest(leftOperand, pos) { + function parseConditionalExpressionRest(leftOperand, pos, allowReturnTypeInArrowFunction) { var questionToken = parseOptionalToken(57); if (!questionToken) { return leftOperand; } var colonToken; - return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58), ts.nodeIsPresent(colonToken) - ? parseAssignmentExpressionOrHigher() + return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, function () { return parseAssignmentExpressionOrHigher(false); }), colonToken = parseExpectedToken(58), ts.nodeIsPresent(colonToken) + ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(79, false, ts.Diagnostics._0_expected, ts.tokenToString(58))), pos); } function parseBinaryExpressionOrHigher(precedence) { @@ -28056,6 +28512,9 @@ var ts; var typeArguments = tryParse(parseTypeArgumentsInExpression); if (typeArguments !== undefined) { parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments); + if (!isTemplateStartOfTaggedTemplate()) { + expression = factory.createExpressionWithTypeArguments(expression, typeArguments); + } } } if (token() === 20 || token() === 24 || token() === 22) { @@ -28234,9 +28693,22 @@ var ts; } scanJsxIdentifier(); var pos = getNodePos(); - return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 63 ? undefined : - scanJsxAttributeValue() === 10 ? parseLiteralNode() : - parseJsxExpression(true)), pos); + return finishNode(factory.createJsxAttribute(parseIdentifierName(), parseJsxAttributeValue()), pos); + } + function parseJsxAttributeValue() { + if (token() === 63) { + if (scanJsxAttributeValue() === 10) { + return parseLiteralNode(); + } + if (token() === 18) { + return parseJsxExpression(true); + } + if (token() === 29) { + return parseJsxElementOrSelfClosingElementOrFragment(true); + } + parseErrorAtCurrentToken(ts.Diagnostics.or_JSX_element_expected); + } + return undefined; } function parseJsxSpreadAttribute() { var pos = getNodePos(); @@ -28322,6 +28794,11 @@ var ts; if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) { parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers); } + if (ts.isExpressionWithTypeArguments(expression) && expression.typeArguments) { + var pos_2 = expression.typeArguments.pos - 1; + var end = ts.skipTrivia(sourceText, expression.typeArguments.end) + 1; + parseErrorAt(pos_2, end, ts.Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access); + } return finishNode(propertyAccess, pos); } function parseElementAccessExpressionRest(pos, expression, questionDotToken) { @@ -28442,9 +28919,10 @@ var ts; } nextToken(); var typeArguments = parseDelimitedList(20, parseType); - if (!parseExpected(31)) { + if (reScanGreaterToken() !== 31) { return undefined; } + nextToken(); return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments : undefined; } function canFollowTypeArgumentsInExpression() { @@ -28453,8 +28931,13 @@ var ts; case 14: case 15: return true; + case 29: + case 31: + case 39: + case 40: + return false; } - return !isStartOfExpression(); + return scanner.hasPrecedingLineBreak() || isBinaryOperator() || !isStartOfExpression(); } function parsePrimaryExpression() { switch (token()) { @@ -28510,13 +28993,13 @@ var ts; function parseSpreadElement() { var pos = getNodePos(); parseExpected(25); - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(true); return finishNode(factory.createSpreadElement(expression), pos); } function parseArgumentOrArrayLiteralElement() { return token() === 25 ? parseSpreadElement() : token() === 27 ? finishNode(factory.createOmittedExpression(), getNodePos()) : - parseAssignmentExpressionOrHigher(); + parseAssignmentExpressionOrHigher(true); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); @@ -28534,16 +29017,16 @@ var ts; var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); if (parseOptionalToken(25)) { - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(true); return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc); } var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(136)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172, 0); } if (parseContextualModifier(149)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173, 0); } var asteriskToken = parseOptionalToken(41); var tokenIsIdentifier = isIdentifier(); @@ -28557,16 +29040,16 @@ var ts; var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58); if (isShorthandPropertyAssignment) { var equalsToken = parseOptionalToken(63); - var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined; + var objectAssignmentInitializer = equalsToken ? allowInAnd(function () { return parseAssignmentExpressionOrHigher(true); }) : undefined; node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer); node.equalsToken = equalsToken; } else { parseExpected(58); - var initializer = allowInAnd(parseAssignmentExpressionOrHigher); + var initializer = allowInAnd(function () { return parseAssignmentExpressionOrHigher(true); }); node = factory.createPropertyAssignment(name, initializer); } - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; node.questionToken = questionToken; node.exclamationToken = exclamationToken; @@ -28620,6 +29103,9 @@ var ts; typeArguments = expression.typeArguments; expression = expression.expression; } + if (token() === 28) { + parseErrorAtCurrentToken(ts.Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, ts.getTextOfNodeFromSourceText(sourceText, expression)); + } var argumentList = token() === 20 ? parseArgumentList() : undefined; return finishNode(factory.createNewExpression(expression, typeArguments, argumentList), pos); } @@ -28723,7 +29209,7 @@ var ts; } var node; if (awaitToken ? parseExpected(160) : parseOptional(160)) { - var expression = allowInAnd(parseAssignmentExpressionOrHigher); + var expression = allowInAnd(function () { return parseAssignmentExpressionOrHigher(true); }); parseExpected(21); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); } @@ -29081,18 +29567,16 @@ var ts; return modifier.kind === 135; } function parseDeclaration() { - var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier); - if (isAmbient) { - var node = tryReuseAmbientDeclaration(); - if (node) { - return node; - } - } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var decorators = parseDecorators(); var modifiers = parseModifiers(); + var isAmbient = ts.some(modifiers, isDeclareModifier); if (isAmbient) { + var node = tryReuseAmbientDeclaration(pos); + if (node) { + return node; + } for (var _i = 0, _a = modifiers; _i < _a.length; _i++) { var m = _a[_i]; m.flags |= 16777216; @@ -29103,9 +29587,9 @@ var ts; return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); } } - function tryReuseAmbientDeclaration() { + function tryReuseAmbientDeclaration(pos) { return doInsideOfContext(16777216, function () { - var node = currentNode(parsingContext); + var node = currentNode(parsingContext, pos); if (node) { return consumeNode(node); } @@ -29148,7 +29632,7 @@ var ts; if (decorators || modifiers) { var missing = createMissingNode(276, true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); - missing.decorators = decorators; + missing.illegalDecorators = decorators; missing.modifiers = modifiers; return missing; } @@ -29160,9 +29644,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 18 && canParseSemicolon()) { - parseSemicolon(); - return; + if (token() !== 18) { + if (flags & 4) { + parseTypeMemberSemicolon(); + return; + } + if (canParseSemicolon()) { + parseSemicolon(); + return; + } } return parseFunctionBlock(flags, diagnosticMessage); } @@ -29274,7 +29764,7 @@ var ts; var declarationList = parseVariableDeclarationList(false); parseSemicolon(); var node = factory.createVariableStatement(modifiers, declarationList); - node.decorators = decorators; + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -29292,7 +29782,8 @@ var ts; var type = parseReturnType(58, false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); setAwaitContext(savedAwaitContext); - var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + var node = factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseConstructorName() { @@ -29313,7 +29804,8 @@ var ts; var parameters = parseParameters(0); var type = parseReturnType(58, false); var body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); - var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body); + var node = factory.createConstructorDeclaration(modifiers, parameters, body); + node.illegalDecorators = decorators; node.typeParameters = typeParameters; node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -29327,7 +29819,7 @@ var ts; var parameters = parseParameters(isGenerator | isAsync); var type = parseReturnType(58, false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + var node = factory.createMethodDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); node.exclamationToken = exclamationToken; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -29336,7 +29828,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = doOutsideOfContext(8192 | 32768 | 4096, parseInitializer); parseSemicolonAfterPropertyName(name, type, initializer); - var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer); + var node = factory.createPropertyDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, questionToken || exclamationToken, type, initializer); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -29348,17 +29840,17 @@ var ts; } return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken); } - function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) { + function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind, flags) { var name = parsePropertyName(); var typeParameters = parseTypeParameters(); var parameters = parseParameters(0); var type = parseReturnType(58, false); - var body = parseFunctionBlockOrSemicolon(0); + var body = parseFunctionBlockOrSemicolon(flags); var node = kind === 172 - ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) - : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); + ? factory.createGetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, type, body) + : factory.createSetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, body); node.typeParameters = typeParameters; - if (type && node.kind === 173) + if (ts.isSetAccessorDeclaration(node)) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -29405,7 +29897,10 @@ var ts; function parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers) { parseExpectedToken(124); var body = parseClassStaticBlockBody(); - return withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(decorators, modifiers, body), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(body), pos), hasJSDoc); + node.illegalDecorators = decorators; + node.modifiers = modifiers; + return node; } function parseClassStaticBlockBody() { var savedYieldContext = inYieldContext(); @@ -29464,6 +29959,15 @@ var ts; } return finishNode(factory.createToken(kind), pos); } + function combineDecoratorsAndModifiers(decorators, modifiers) { + if (!decorators) + return modifiers; + if (!modifiers) + return decorators; + var decoratorsAndModifiers = factory.createNodeArray(ts.concatenate(decorators, modifiers)); + ts.setTextRangePosEnd(decoratorsAndModifiers, decorators.pos, modifiers.end); + return decoratorsAndModifiers; + } function parseModifiers(permitInvalidConstAsModifier, stopOnStartOfClassStaticBlock) { var pos = getNodePos(); var list, modifier, hasSeenStatic = false; @@ -29497,10 +30001,10 @@ var ts; return parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers); } if (parseContextualModifier(136)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172, 0); } if (parseContextualModifier(149)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173, 0); } if (token() === 134 || token() === 10) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -29558,8 +30062,8 @@ var ts; } setAwaitContext(savedAwaitContext); var node = kind === 257 - ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) - : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); + ? factory.createClassDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members) + : factory.createClassExpression(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseNameOfClassDeclarationOrExpression() { @@ -29609,7 +30113,8 @@ var ts; var typeParameters = parseTypeParameters(); var heritageClauses = parseHeritageClauses(); var members = parseObjectTypeMembers(); - var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = factory.createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -29619,7 +30124,8 @@ var ts; parseExpected(63); var type = token() === 138 && tryParse(parseKeywordAndNoDot) || parseType(); parseSemicolon(); - var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type); + var node = factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseEnumMember() { @@ -29640,7 +30146,8 @@ var ts; else { members = createMissingList(); } - var node = factory.createEnumDeclaration(decorators, modifiers, name, members); + var node = factory.createEnumDeclaration(modifiers, name, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleBlock() { @@ -29661,7 +30168,8 @@ var ts; var body = parseOptional(24) ? parseModuleOrNamespaceDeclaration(getNodePos(), false, undefined, undefined, 4 | namespaceFlag) : parseModuleBlock(); - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -29682,7 +30190,8 @@ var ts; else { parseSemicolon(); } - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -29720,7 +30229,7 @@ var ts; var name = parseIdentifier(); parseSemicolon(); var node = factory.createNamespaceExportDeclaration(name); - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -29754,14 +30263,15 @@ var ts; assertClause = parseAssertClause(); } parseSemicolon(); - var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause); + var node = factory.createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAssertEntry() { var pos = getNodePos(); var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10); parseExpected(58); - var value = parseAssignmentExpressionOrHigher(); + var value = parseAssignmentExpressionOrHigher(true); return finishNode(factory.createAssertEntry(name, value), pos); } function parseAssertClause(skipAssertKeyword) { @@ -29796,7 +30306,8 @@ var ts; parseExpected(63); var moduleReference = parseModuleReference(); parseSemicolon(); - var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference); + var node = factory.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference); + node.illegalDecorators = decorators; var finished = withJSDoc(finishNode(node, pos), hasJSDoc); return finished; } @@ -29942,7 +30453,8 @@ var ts; } parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + var node = factory.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) { @@ -29955,10 +30467,11 @@ var ts; else { parseExpected(88); } - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(true); parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression); + var node = factory.createExportAssignment(modifiers, isExportEquals, expression); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } var JSDocParser; @@ -30667,7 +31180,7 @@ var ts; var typeNameOrNamespaceName = parseJSDocIdentifierName(); if (parseOptional(24)) { var body = parseJSDocTypeNameWithNamespace(true); - var jsDocNamespaceNode = factory.createModuleDeclaration(undefined, undefined, typeNameOrNamespaceName, body, nested ? 4 : undefined); + var jsDocNamespaceNode = factory.createModuleDeclaration(undefined, typeNameOrNamespaceName, body, nested ? 4 : undefined); return finishNode(jsDocNamespaceNode, pos); } if (nested) { @@ -30986,10 +31499,10 @@ var ts; } function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { - var pos_2 = node.pos; + var pos_3 = node.pos; var visitNode_1 = function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; + ts.Debug.assert(child.pos >= pos_3); + pos_3 = child.end; }; if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -30998,7 +31511,7 @@ var ts; } } forEachChild(node, visitNode_1); - ts.Debug.assert(pos_2 <= node.end); + ts.Debug.assert(pos_3 <= node.end); } } function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { @@ -31485,6 +31998,7 @@ var ts; ["es2022.error", "lib.es2022.error.d.ts"], ["es2022.intl", "lib.es2022.intl.d.ts"], ["es2022.object", "lib.es2022.object.d.ts"], + ["es2022.sharedmemory", "lib.es2022.sharedmemory.d.ts"], ["es2022.string", "lib.es2022.string.d.ts"], ["esnext.array", "lib.es2022.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], @@ -31684,6 +32198,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, defaultValueDescription: false, @@ -31717,12 +32232,39 @@ var ts; affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, defaultValueDescription: 0, }; + ts.moduleOptionDeclaration = { + name: "module", + shortName: "m", + type: new ts.Map(ts.getEntries({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + es2020: ts.ModuleKind.ES2020, + es2022: ts.ModuleKind.ES2022, + esnext: ts.ModuleKind.ESNext, + node16: ts.ModuleKind.Node16, + nodenext: ts.ModuleKind.NodeNext, + })), + affectsModuleResolution: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Modules, + description: ts.Diagnostics.Specify_what_module_code_is_generated, + defaultValueDescription: undefined, + }; var commandOptionsWithoutBuild = [ { name: "all", @@ -31783,36 +32325,13 @@ var ts; category: ts.Diagnostics.Command_line_Options, affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, isCommandLineOnly: true, description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, defaultValueDescription: false, }, ts.targetOptionDeclaration, - { - name: "module", - shortName: "m", - type: new ts.Map(ts.getEntries({ - none: ts.ModuleKind.None, - commonjs: ts.ModuleKind.CommonJS, - amd: ts.ModuleKind.AMD, - system: ts.ModuleKind.System, - umd: ts.ModuleKind.UMD, - es6: ts.ModuleKind.ES2015, - es2015: ts.ModuleKind.ES2015, - es2020: ts.ModuleKind.ES2020, - es2022: ts.ModuleKind.ES2022, - esnext: ts.ModuleKind.ESNext, - node16: ts.ModuleKind.Node16, - nodenext: ts.ModuleKind.NodeNext, - })), - affectsModuleResolution: true, - affectsEmit: true, - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Modules, - description: ts.Diagnostics.Specify_what_module_code_is_generated, - defaultValueDescription: undefined, - }, + ts.moduleOptionDeclaration, { name: "lib", type: "list", @@ -31849,6 +32368,7 @@ var ts; type: jsxOptionMap, affectsSourceFile: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -31861,6 +32381,7 @@ var ts; shortName: "d", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -31871,6 +32392,7 @@ var ts; name: "declarationMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -31881,6 +32403,7 @@ var ts; name: "emitDeclarationOnly", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, @@ -31891,6 +32414,7 @@ var ts; name: "sourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -31900,6 +32424,9 @@ var ts; name: "outFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, showInSimplifiedHelpView: true, @@ -31911,6 +32438,8 @@ var ts; name: "outDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, showInSimplifiedHelpView: true, @@ -31921,6 +32450,8 @@ var ts; name: "rootDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Modules, @@ -31931,6 +32462,8 @@ var ts; name: "composite", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isTSConfigOnly: true, category: ts.Diagnostics.Projects, transpileOptionValue: undefined, @@ -31941,6 +32474,8 @@ var ts; name: "tsBuildInfoFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, category: ts.Diagnostics.Projects, @@ -31952,6 +32487,7 @@ var ts; name: "removeComments", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -31970,6 +32506,7 @@ var ts; name: "importHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, defaultValueDescription: false, @@ -31983,6 +32520,7 @@ var ts; })), affectsEmit: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, defaultValueDescription: 0, @@ -31991,6 +32529,7 @@ var ts; name: "downlevelIteration", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, defaultValueDescription: false, @@ -32006,6 +32545,7 @@ var ts; { name: "strict", type: "boolean", + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_all_strict_type_checking_options, @@ -32015,6 +32555,7 @@ var ts; name: "noImplicitAny", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, @@ -32024,6 +32565,7 @@ var ts; name: "strictNullChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_type_checking_take_into_account_null_and_undefined, @@ -32032,6 +32574,8 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, @@ -32040,6 +32584,8 @@ var ts; { name: "strictBindCallApply", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, @@ -32049,6 +32595,7 @@ var ts; name: "strictPropertyInitialization", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, @@ -32058,6 +32605,7 @@ var ts; name: "noImplicitThis", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, @@ -32067,6 +32615,7 @@ var ts; name: "useUnknownInCatchVariables", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, @@ -32076,6 +32625,8 @@ var ts; name: "alwaysStrict", type: "boolean", affectsSourceFile: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_use_strict_is_always_emitted, @@ -32085,6 +32636,7 @@ var ts; name: "noUnusedLocals", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, defaultValueDescription: false, @@ -32093,6 +32645,7 @@ var ts; name: "noUnusedParameters", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, defaultValueDescription: false, @@ -32101,6 +32654,7 @@ var ts; name: "exactOptionalPropertyTypes", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, defaultValueDescription: false, @@ -32109,6 +32663,7 @@ var ts; name: "noImplicitReturns", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, defaultValueDescription: false, @@ -32118,6 +32673,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, defaultValueDescription: false, @@ -32126,6 +32682,7 @@ var ts; name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, defaultValueDescription: false, @@ -32134,6 +32691,7 @@ var ts; name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, defaultValueDescription: false, @@ -32141,6 +32699,8 @@ var ts; { name: "noPropertyAccessFromIndexSignature", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: false, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, @@ -32221,6 +32781,7 @@ var ts; name: "allowSyntheticDefaultImports", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, defaultValueDescription: ts.Diagnostics.module_system_or_esModuleInterop @@ -32230,6 +32791,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, @@ -32246,6 +32808,7 @@ var ts; name: "allowUmdGlobalAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules, defaultValueDescription: false, @@ -32266,6 +32829,7 @@ var ts; name: "sourceRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code, @@ -32274,6 +32838,7 @@ var ts; name: "mapRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, @@ -32282,6 +32847,7 @@ var ts; name: "inlineSourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -32290,6 +32856,7 @@ var ts; name: "inlineSources", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -32298,6 +32865,7 @@ var ts; name: "experimentalDecorators", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, defaultValueDescription: false, @@ -32307,6 +32875,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, defaultValueDescription: false, @@ -32330,6 +32899,7 @@ var ts; type: "string", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, @@ -32347,6 +32917,9 @@ var ts; name: "out", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: false, category: ts.Diagnostics.Backwards_Compatibility, paramType: ts.Diagnostics.FILE, @@ -32357,6 +32930,7 @@ var ts; name: "reactNamespace", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, defaultValueDescription: "`React`", @@ -32364,6 +32938,7 @@ var ts; { name: "skipDefaultLibCheck", type: "boolean", + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, defaultValueDescription: false, @@ -32379,6 +32954,7 @@ var ts; name: "emitBOM", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, defaultValueDescription: false, @@ -32390,6 +32966,7 @@ var ts; lf: 1 })), affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Set_the_newline_character_for_emitting_files, @@ -32399,6 +32976,7 @@ var ts; name: "noErrorTruncation", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_truncating_types_in_error_messages, defaultValueDescription: false, @@ -32425,6 +33003,7 @@ var ts; name: "stripInternal", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, defaultValueDescription: false, @@ -32465,6 +33044,7 @@ var ts; name: "noImplicitUseStrict", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, defaultValueDescription: false, @@ -32473,6 +33053,7 @@ var ts; name: "noEmitHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, defaultValueDescription: false, @@ -32481,6 +33062,7 @@ var ts; name: "noEmitOnError", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, @@ -32490,6 +33072,7 @@ var ts; name: "preserveConstEnums", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, defaultValueDescription: false, @@ -32498,6 +33081,8 @@ var ts; name: "declarationDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, category: ts.Diagnostics.Emit, @@ -32507,6 +33092,7 @@ var ts; { name: "skipLibCheck", type: "boolean", + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_all_d_ts_files, defaultValueDescription: false, @@ -32516,6 +33102,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unused_labels, defaultValueDescription: undefined, @@ -32525,6 +33112,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code, defaultValueDescription: undefined, @@ -32533,6 +33121,7 @@ var ts; name: "suppressExcessPropertyErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, defaultValueDescription: false, @@ -32541,6 +33130,7 @@ var ts; name: "suppressImplicitAnyIndexErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, defaultValueDescription: false, @@ -32565,6 +33155,7 @@ var ts; name: "noStrictGenericChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, defaultValueDescription: false, @@ -32574,6 +33165,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, defaultValueDescription: ts.Diagnostics.true_for_ES2022_and_above_including_ESNext @@ -32582,6 +33174,7 @@ var ts; name: "preserveValueImports", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, defaultValueDescription: false, @@ -32620,6 +33213,7 @@ var ts; ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild, true), commandOptionsWithoutBuild, true); ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; }); + ts.affectsDeclarationPathOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsDeclarationPath; }); ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; @@ -33360,7 +33954,7 @@ var ts; return undefined; if (ts.length(specs) !== 1) return specs; - if (specs[0] === "**/*") + if (specs[0] === ts.defaultIncludeSpec) return undefined; return specs; } @@ -33399,6 +33993,7 @@ var ts; } }); } + ts.getNameOfCompilerOptionValue = getNameOfCompilerOptionValue; function serializeCompilerOptions(options, pathOptions) { return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); } @@ -33594,6 +34189,7 @@ var ts; function directoryOfCombinedPath(fileName, basePath) { return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } + ts.defaultIncludeSpec = "**/*"; function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } @@ -33646,6 +34242,7 @@ var ts; } var includeSpecs = toPropValue(getSpecsFromRaw("include")); var excludeOfRaw = getSpecsFromRaw("exclude"); + var isDefaultIncludeSpec = false; var excludeSpecs = toPropValue(excludeOfRaw); if (excludeOfRaw === "no-prop" && raw.compilerOptions) { var outDir = raw.compilerOptions.outDir; @@ -33655,7 +34252,8 @@ var ts; } } if (filesSpecs === undefined && includeSpecs === undefined) { - includeSpecs = ["**/*"]; + includeSpecs = [ts.defaultIncludeSpec]; + isDefaultIncludeSpec = true; } var validatedIncludeSpecs, validatedExcludeSpecs; if (includeSpecs) { @@ -33672,6 +34270,7 @@ var ts; validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, pathPatterns: undefined, + isDefaultIncludeSpec: isDefaultIncludeSpec, }; } function getFileNames(basePath) { @@ -34231,7 +34830,7 @@ var ts; } if (ts.isImplicitGlob(spec.substring(spec.lastIndexOf(ts.directorySeparator) + 1))) { return { - key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec), + key: ts.removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec)), flags: 1 }; } @@ -34375,16 +34974,18 @@ var ts; ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, diagnostics, resultFromCache) { - var _a; + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache) { + var _a, _b; if (resultFromCache) { (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = resultFromCache.affectingLocations).push.apply(_b, affectingLocations); return resultFromCache; } return { resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations, - resolutionDiagnostics: diagnostics + affectingLocations: affectingLocations, + resolutionDiagnostics: diagnostics, }; } function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { @@ -34560,6 +35161,7 @@ var ts; } } var failedLookupLocations = []; + var affectingLocations = []; var features = getDefaultNodeResolutionFeatures(options); if (resolutionMode === ts.ModuleKind.ESNext && (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext)) { features |= NodeResolutionFeatures.EsmMode; @@ -34571,6 +35173,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -34587,15 +35190,16 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + var pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host); resolvedTypeReferenceDirective = { primary: primary, - resolvedFileName: resolvedFileName, - originalPath: arePathsEqual(fileName, resolvedFileName, host) ? undefined : fileName, + resolvedFileName: pathsAreEqual ? fileName : resolvedFileName, + originalPath: pathsAreEqual ? undefined : fileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName), }; } - result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, resolutionDiagnostics: diagnostics }; + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, affectingLocations: affectingLocations, resolutionDiagnostics: diagnostics }; perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, resolutionMode, result); if (traceEnabled) traceResult(result); @@ -34664,17 +35268,7 @@ var ts; NodeResolutionFeatures.None; } function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ts.emptyArray, - features: NodeResolutionFeatures.None, - requestContainingDirectory: containingDirectory, - reportDiagnostic: ts.noop - }; + var moduleResolutionState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); return ts.forEachAncestorDirectory(containingDirectory, function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var nodeModulesFolder = ts.combinePaths(ancestorDirectory, "node_modules"); @@ -34754,7 +35348,7 @@ var ts; ts.createCacheWithRedirects = createCacheWithRedirects; function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { var cache; - return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries }; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries, getInternalMap: getInternalMap }; function getPackageJsonInfo(packageJsonPath) { return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); } @@ -34768,6 +35362,9 @@ var ts; var iter = cache === null || cache === void 0 ? void 0 : cache.entries(); return iter ? ts.arrayFrom(iter) : []; } + function getInternalMap() { + return cache; + } } function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); @@ -34866,15 +35463,18 @@ var ts; } ts.zipToModeAwareCache = zipToModeAwareCache; function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; }, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); - moduleNameToDirectoryMap.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + } function update(options) { updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); } @@ -34931,13 +35531,16 @@ var ts; } ts.createModuleResolutionCache = createModuleResolutionCache; function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { clear: clear, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + } } ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { @@ -35164,15 +35767,19 @@ var ts; function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.NodeNextDefault, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } - function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var esmMode = resolutionMode === ts.ModuleKind.ESNext ? NodeResolutionFeatures.EsmMode : 0; - return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions, redirectedReference); - } var jsOnlyExtensions = [Extensions.JavaScript]; var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); var tsconfigExtensions = [Extensions.TSConfig]; + function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var esmMode = resolutionMode === ts.ModuleKind.ESNext ? NodeResolutionFeatures.EsmMode : 0; + var extensions = compilerOptions.noDtsResolution ? [Extensions.TsOnly, Extensions.JavaScript] : tsExtensions; + if (compilerOptions.resolveJsonModule) { + extensions = __spreadArray(__spreadArray([], extensions, true), [Extensions.Json], false); + } + return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference); + } function tryResolveJSModuleWorker(moduleName, initialDir, host) { return nodeModuleNameResolverWorker(NodeResolutionFeatures.None, moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, jsOnlyExtensions, undefined); } @@ -35198,6 +35805,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; var conditions = features & NodeResolutionFeatures.EsmMode ? ["node", "import", "types"] : ["node", "require", "types"]; if (compilerOptions.noDtsResolution) { conditions.pop(); @@ -35208,6 +35816,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -35215,7 +35824,7 @@ var ts; reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; 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, diagnostics, state.resultFromCache); + 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) { var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); @@ -35241,8 +35850,9 @@ var ts; var resolvedValue = resolved_1.value; if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - var originalPath = arePathsEqual(path, resolvedValue.path, host) ? undefined : resolvedValue.path; - resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath }); + var pathsAreEqual = arePathsEqual(path, resolvedValue.path, host); + var originalPath = pathsAreEqual ? undefined : resolvedValue.path; + resolvedValue = __assign(__assign({}, resolvedValue), { path: pathsAreEqual ? resolvedValue.path : path, originalPath: originalPath }); } return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } @@ -35468,17 +36078,9 @@ var ts; var entrypoints; var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript; var features = getDefaultNodeResolutionFeatures(options); - var requireState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ["node", "require", "types"], - features: features, - requestContainingDirectory: packageJsonInfo.packageDirectory, - reportDiagnostic: ts.noop - }; + var requireState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); + requireState.conditions = ["node", "require", "types"]; + requireState.requestContainingDirectory = packageJsonInfo.packageDirectory; var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths); entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path); if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) { @@ -35548,18 +36150,22 @@ var ts; } } } - function getPackageScopeForPath(fileName, packageJsonInfoCache, host, options) { - var state = { + function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) { + return { host: host, compilerOptions: options, traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], + failedLookupLocations: ts.noopPush, + affectingLocations: ts.noopPush, packageJsonInfoCache: packageJsonInfoCache, - features: 0, - conditions: [], + features: NodeResolutionFeatures.None, + conditions: ts.emptyArray, requestContainingDirectory: undefined, reportDiagnostic: ts.noop }; + } + ts.getTemporaryModuleResolutionState = getTemporaryModuleResolutionState; + function getPackageScopeForPath(fileName, state) { var parts = ts.getPathComponents(fileName); parts.pop(); while (parts.length > 0) { @@ -35585,6 +36191,7 @@ var ts; if (typeof existing !== "boolean") { if (traceEnabled) trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + state.affectingLocations.push(packageJsonPath); return existing; } else { @@ -35603,6 +36210,7 @@ var ts; var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined }; (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + state.affectingLocations.push(packageJsonPath); return result; } else { @@ -35714,7 +36322,7 @@ var ts; var _a, _b; var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope || !scope.packageJsonContent.exports) { return undefined; } @@ -35773,7 +36381,7 @@ var ts; } var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath); @@ -35795,13 +36403,33 @@ var ts; } return toSearchResult(undefined); } + function comparePatternKeys(a, b) { + var aPatternIndex = a.indexOf("*"); + var bPatternIndex = b.indexOf("*"); + var baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + var baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + if (baseLenA > baseLenB) + return -1; + if (baseLenB > baseLenA) + return 1; + if (aPatternIndex === -1) + return 1; + if (bPatternIndex === -1) + return -1; + if (a.length > b.length) + return -1; + if (b.length > a.length) + return 1; + return 0; + } + ts.comparePatternKeys = comparePatternKeys; function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { 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); } - var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), function (a, b) { return a.length - b.length; }); + 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++) { var potentialTarget = expandingKeys_1[_i]; if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) { @@ -36076,8 +36704,7 @@ var ts; var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths); if (!pathAndExtension && packageInfo - && packageInfo.packageJsonContent.exports === undefined - && packageInfo.packageJsonContent.main === undefined + && (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null) && state.features & NodeResolutionFeatures.EsmMode) { pathAndExtension = loadModuleFromFile(extensions, ts.combinePaths(candidate, "index.js"), onlyRecordFailures, state); } @@ -36175,11 +36802,23 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: cache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: containingDirectory, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { @@ -36215,10 +36854,22 @@ var ts; trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; + var affectingLocations = []; var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: undefined, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: packageJsonInfoCache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: undefined, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, false, undefined, undefined); - return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; function toSearchResult(value) { @@ -36512,7 +37163,7 @@ var ts; case 317: return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); case 164: - ts.Debug.assert(node.parent.kind === 317, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind, ", expected JSDocFunctionType"); }); + ts.Debug.assert(node.parent.kind === 317, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind), ", expected JSDocFunctionType"); }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -37547,8 +38198,6 @@ var ts; } function bindBindingElementFlow(node) { if (ts.isBindingPattern(node.name)) { - bindEach(node.decorators); - bindEach(node.modifiers); bind(node.dotDotDotToken); bind(node.propertyName); bind(node.initializer); @@ -37831,24 +38480,6 @@ var ts; typeLiteralSymbol.members.set(symbol.escapedName, symbol); } function bindObjectLiteralExpression(node) { - if (inStrictMode && !ts.isAssignmentTarget(node)) { - var seen = new ts.Map(); - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 298 || prop.name.kind !== 79) { - continue; - } - var identifier = prop.name; - var currentKind = prop.kind === 296 || prop.kind === 297 || prop.kind === 169 - ? 1 - : 2; - var existingKind = seen.get(identifier.escapedText); - if (!existingKind) { - seen.set(identifier.escapedText, currentKind); - continue; - } - } - } return bindAnonymousDeclaration(node, 4096, "__object"); } function bindJsxAttributes(node) { @@ -38419,7 +39050,7 @@ var ts; } } function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { + if (ts.some(node.modifiers)) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level @@ -38452,12 +39083,14 @@ var ts; } } function setCommonJsModuleIndicator(node) { - if (file.externalModuleIndicator) { + if (file.externalModuleIndicator && file.externalModuleIndicator !== true) { return false; } if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } return true; } @@ -38810,7 +39443,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) && !ts.getJSDocTypeTag(node) && !(ts.getCombinedModifierFlags(node) & 1)) { + var possibleVariableDecl = node.kind === 254 ? node : node.parent.parent; + if (ts.isInJSFile(node) && + ts.isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && + !ts.getJSDocTypeTag(node) && + !(ts.getCombinedModifierFlags(node) & 1)) { declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); } else if (ts.isBlockOrCatchScoped(node)) { @@ -38970,10 +39607,11 @@ var ts; } function isExportsOrModuleExportsOrAlias(sourceFile, node) { var i = 0; - var q = [node]; - while (q.length && i < 100) { + var q = ts.createQueue(); + q.enqueue(node); + while (!q.isEmpty() && i < 100) { i++; - node = q.shift(); + node = q.dequeue(); if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) { return true; } @@ -38981,10 +39619,10 @@ var ts; var symbol = lookupSymbolForName(sourceFile, node.escapedText); if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) { var init = symbol.valueDeclaration.initializer; - q.push(init); + q.enqueue(init); if (ts.isAssignmentExpression(init, true)) { - q.push(init.left); - q.push(init.right); + q.enqueue(init.left); + q.enqueue(init.right); } } } @@ -39174,16 +39812,6 @@ var ts; var nextNodeId = 1; var nextMergeId = 1; var nextFlowId = 1; - var typeofEQFacts = new ts.Map(ts.getEntries({ - string: 1, - number: 2, - bigint: 4, - boolean: 8, - symbol: 16, - undefined: 65536, - object: 32, - function: 64 - })); var typeofNEFacts = new ts.Map(ts.getEntries({ string: 256, number: 512, @@ -39438,7 +40066,7 @@ var ts; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); - return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + return node ? getContextualTypeForObjectLiteralElement(node, undefined) : undefined; }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -39446,7 +40074,7 @@ var ts; }, getContextualTypeForJsxAttribute: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); - return node && getContextualTypeForJsxAttribute(node); + return node && getContextualTypeForJsxAttribute(node, undefined); }, isContextSensitive: isContextSensitive, getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, @@ -39558,9 +40186,9 @@ var ts; return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, true); }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, - tryGetThisTypeAt: function (nodeIn, includeGlobalThis) { + tryGetThisTypeAt: function (nodeIn, includeGlobalThis, container) { var node = ts.getParseTreeNode(nodeIn); - return node && tryGetThisTypeAt(node, includeGlobalThis); + return node && tryGetThisTypeAt(node, includeGlobalThis, container); }, getTypeArgumentConstraint: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); @@ -39646,6 +40274,7 @@ var ts; var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); var subtypeReductionCache = new ts.Map(); + var cachedTypes = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var markerTypes = new ts.Set(); @@ -39654,11 +40283,10 @@ var ts; var unresolvedSymbols = new ts.Map(); var errorTypes = new ts.Map(); var anyType = createIntrinsicType(1, "any"); - var autoType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any", 262144); var wildcardType = createIntrinsicType(1, "any"); var errorType = createIntrinsicType(1, "error"); var unresolvedType = createIntrinsicType(1, "unresolved"); - var nonInferrableAnyType = createIntrinsicType(1, "any", 65536); var intrinsicMarkerType = createIntrinsicType(1, "intrinsic"); var unknownType = createIntrinsicType(2, "unknown"); var nonNullUnknownType = createIntrinsicType(2, "unknown"); @@ -39687,8 +40315,7 @@ var ts; var esSymbolType = createIntrinsicType(4096, "symbol"); var voidType = createIntrinsicType(16384, "void"); var neverType = createIntrinsicType(131072, "never"); - var silentNeverType = createIntrinsicType(131072, "never"); - var nonInferrableType = createIntrinsicType(131072, "never", 262144); + var silentNeverType = createIntrinsicType(131072, "never", 262144); var implicitNeverType = createIntrinsicType(131072, "never"); var unreachableNeverType = createIntrinsicType(131072, "never"); var nonPrimitiveType = createIntrinsicType(67108864, "object"); @@ -39698,16 +40325,30 @@ var ts; var numberOrBigIntType = getUnionType([numberType, bigintType]); var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]); var numericStringType = getTemplateLiteralType(["", ""], [numberType]); - var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 ? getRestrictiveTypeParameter(t) : t; }); - var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 ? wildcardType : t; }); + var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 ? getRestrictiveTypeParameter(t) : t; }, function () { return "(restrictive mapper)"; }); + var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 ? wildcardType : t; }, function () { return "(permissive mapper)"; }); var uniqueLiteralType = createIntrinsicType(131072, "never"); - var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 ? uniqueLiteralType : t; }); + var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 ? uniqueLiteralType : t; }, function () { return "(unique literal mapper)"; }); + var outofbandVarianceMarkerHandler; + var reportUnreliableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(true); + } + return t; + }, function () { return "(unmeasurable reporter)"; }); + var reportUnmeasurableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(false); + } + return t; + }, function () { return "(unreliable reporter)"; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyJsxObjectType.objectFlags |= 2048; var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray)]) : unknownType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyGenericType.instantiations = new ts.Map(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); @@ -39719,6 +40360,9 @@ var ts; var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); + var markerSuperTypeForCheck = createTypeParameter(); + var markerSubTypeForCheck = createTypeParameter(); + markerSubTypeForCheck.constraint = markerSuperTypeForCheck; var noTypePredicate = createTypePredicate(1, "<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, 0); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, undefined, 0, 0); @@ -39839,21 +40483,13 @@ var ts; var potentialNewTargetCollisions = []; var potentialWeakMapSetCollisions = []; var potentialReflectCollisions = []; + var potentialUnusedRenamedBindingElementsInTypes = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); - var typeofTypesByName = new ts.Map(ts.getEntries({ - string: stringType, - number: numberType, - bigint: bigintType, - boolean: booleanType, - symbol: esSymbolType, - undefined: undefinedType - })); var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var outofbandVarianceMarkerHandler; var subtypeRelation = new ts.Map(); var strictSubtypeRelation = new ts.Map(); var assignableRelation = new ts.Map(); @@ -39875,6 +40511,14 @@ var ts; ]; initializeTypeChecker(); return checker; + function getCachedType(key) { + return key ? cachedTypes.get(key) : undefined; + } + function setCachedType(key, type) { + if (key) + cachedTypes.set(key, type); + return type; + } function getJsxNamespace(location) { if (location) { var file = ts.getSourceFileOfNode(location); @@ -40614,6 +41258,7 @@ var ts; var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 111551)) { + ts.Debug.assertNode(location, ts.isPropertyDeclaration); propertyWithInvalidInitializer = location; } } @@ -40759,11 +41404,21 @@ var ts; } } } + function checkAndReportErrorForInvalidInitializer() { + if (propertyWithInvalidInitializer && !(useDefineForClassFields && ts.getEmitScriptTarget(compilerOptions) >= 9)) { + error(errorLocation, errorLocation && propertyWithInvalidInitializer.type && ts.textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) + ? ts.Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor + : ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg)); + return true; + } + return false; + } if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(function () { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForInvalidInitializer() && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && @@ -40771,7 +41426,14 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { + var suggestedLib = void 0; + if (nameArg) { + suggestedLib = getSuggestedLibForNonExistentName(nameArg); + if (suggestedLib) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib); + } + } + if (!suggestedLib && getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -40790,16 +41452,8 @@ var ts; } } } - if (!suggestion) { - if (nameArg) { - var lib = getSuggestedLibForNonExistentName(nameArg); - if (lib) { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib); - } - else { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); - } - } + if (!suggestion && !suggestedLib && nameArg) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); } suggestionCount++; } @@ -40807,9 +41461,7 @@ var ts; } return undefined; } - if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 && useDefineForClassFields)) { - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + else if (checkAndReportErrorForInvalidInitializer()) { return undefined; } if (nameNotFoundMessage) { @@ -40994,7 +41646,12 @@ var ts; function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (111551 & ~1024)) { if (isPrimitiveTypeName(name)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(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)); + } + else { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + } return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 & ~111551, undefined, undefined, false)); @@ -41014,6 +41671,16 @@ var ts; } return false; } + function isExtendedByInterface(node) { + var grandparent = node.parent.parent; + var parentOfGrandparent = grandparent.parent; + if (grandparent && parentOfGrandparent) { + var isExtending = ts.isHeritageClause(grandparent) && grandparent.token === 94; + var isInterface = ts.isInterfaceDeclaration(parentOfGrandparent); + return isExtending && isInterface; + } + return false; + } function maybeMappedType(node, symbol) { var container = ts.findAncestor(node.parent, function (n) { return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit"; @@ -41123,7 +41790,8 @@ var ts; && isAliasableOrJsExpression(node.parent.right) || node.kind === 297 || node.kind === 296 && isAliasableOrJsExpression(node.initializer) - || ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node); + || node.kind === 254 && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) + || node.kind === 203 && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -41204,7 +41872,7 @@ var ts; if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } - return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), undefined, dontResolveAlias); + return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { var _a; @@ -41461,10 +42129,6 @@ var ts; checkExpressionCached(expression); return getNodeLinks(expression).resolvedSymbol; } - function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) { - var expression = node.initializer; - return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve); - } function getTargetOfAccessExpression(node, dontRecursivelyResolve) { if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63)) { return undefined; @@ -41496,7 +42160,7 @@ var ts; case 297: return resolveEntityName(node.name, 111551 | 788968 | 1920, true, dontRecursivelyResolve); case 296: - return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); + return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); case 207: case 206: return getTargetOfAccessExpression(node, dontRecursivelyResolve); @@ -41834,7 +42498,34 @@ var ts; var overrideClauseHost = ts.findAncestor(location, function (l) { return ts.isImportTypeNode(l) || ts.isExportDeclaration(l) || ts.isImportDeclaration(l); }); var overrideClause = overrideClauseHost && ts.isImportTypeNode(overrideClauseHost) ? (_g = overrideClauseHost.assertions) === null || _g === void 0 ? void 0 : _g.assertClause : overrideClauseHost === null || overrideClauseHost === void 0 ? void 0 : overrideClauseHost.assertClause; if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext && !ts.getResolutionModeOverrideForClause(overrideClause)) { - error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); + if (ts.findAncestor(location, ts.isImportEqualsDeclaration)) { + error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); + } + else { + var diagnosticDetails = void 0; + var ext = ts.tryGetExtensionFromPath(currentSourceFile.fileName); + if (ext === ".ts" || ext === ".js" || ext === ".tsx" || ext === ".jsx") { + var scope = currentSourceFile.packageJsonScope; + var targetExt = ext === ".ts" ? ".mts" : ext === ".js" ? ".mjs" : undefined; + if (scope && !scope.packageJsonContent.type) { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json")); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, ts.combinePaths(scope.packageDirectory, "package.json")); + } + } + else { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, targetExt); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module); + } + } + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(diagnosticDetails, ts.Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, moduleReference))); + } } } return getMergedSymbol(sourceFile.symbol); @@ -42291,8 +42982,9 @@ var ts; function getExportSymbolOfValueSymbolIfExported(symbol) { return getMergedSymbol(symbol && (symbol.flags & 1048576) !== 0 && symbol.exportSymbol || symbol); } - function symbolIsValue(symbol) { - return !!(symbol.flags & 111551 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 111551 && !getTypeOnlyAliasDeclaration(symbol)); + function symbolIsValue(symbol, includeTypeOnlyMembers) { + return !!(symbol.flags & 111551 || + symbol.flags & 2097152 && resolveAlias(symbol).flags & 111551 && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -42332,7 +43024,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getStringLiteralType)); + return getUnionType(ts.arrayFrom(typeofNEFacts.keys(), getStringLiteralType)); } function createTypeParameter(symbol) { var type = createType(262144); @@ -42666,13 +43358,25 @@ var ts; && isDeclarationVisible(declaration.parent)) { return addVisibleAlias(declaration, declaration); } - else if (symbol.flags & 2097152 && ts.isBindingElement(declaration) && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) - && ts.isVariableDeclaration(declaration.parent.parent) - && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) - && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1) - && declaration.parent.parent.parent.parent.parent - && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { - return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + else if (ts.isBindingElement(declaration)) { + if (symbol.flags & 2097152 && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) + && ts.isVariableDeclaration(declaration.parent.parent) + && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) + && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1) + && declaration.parent.parent.parent.parent.parent + && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + } + else if (symbol.flags & 2) { + var variableStatement = ts.findAncestor(declaration, ts.isVariableStatement); + if (ts.hasSyntacticModifier(variableStatement, 1)) { + return true; + } + if (!isDeclarationVisible(variableStatement.parent)) { + return false; + } + return addVisibleAlias(declaration, variableStatement); + } } return false; } @@ -42705,6 +43409,9 @@ var ts; if (symbol && symbol.flags & 262144 && meaning & 788968) { return { accessibility: 0 }; } + if (!symbol && ts.isThisIdentifier(firstIdentifier) && isSymbolAccessible(getSymbolOfNode(ts.getThisContainer(firstIdentifier, false)), firstIdentifier, meaning, false).accessibility === 0) { + return { accessibility: 0 }; + } return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, errorSymbolName: ts.getTextOfNode(firstIdentifier), @@ -42789,7 +43496,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0; } - return flags & 814775659; + return flags & 848330091; } function isClassInstanceSide(type) { return !!type.symbol && !!(type.symbol.flags & 32) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288) && !!(ts.getObjectFlags(type) & 16777216))); @@ -42890,6 +43597,12 @@ var ts; return context.truncating = context.approximateLength > ((context.flags & 1) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { + var savedFlags = context.flags; + var typeNode = typeToTypeNodeWorker(type, context); + context.flags = savedFlags; + return typeNode; + } + function typeToTypeNodeWorker(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); } @@ -43029,6 +43742,9 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32)) return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes); + if (ts.length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) { + return ts.factory.createArrayTypeNode(typeArgumentNodes[0]); + } return symbolToTypeNode(type.aliasSymbol, context, 788968, typeArgumentNodes); } var objectFlags = ts.getObjectFlags(type); @@ -43060,8 +43776,8 @@ var ts; if (type.symbol) { return symbolToTypeNode(type.symbol, context, 788968); } - var name = (type === markerSuperType || type === markerSubType) && varianceTypeParameter && varianceTypeParameter.symbol ? - (type === markerSubType ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; + var name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? + (type === markerSubTypeForCheck ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name), undefined); } if (type.flags & 1048576 && type.origin) { @@ -43126,7 +43842,7 @@ var ts; var name = typeParameterToName(newParam, context); var newTypeVariable = ts.factory.createTypeReferenceNode(name); context.approximateLength += 37; - var newMapper = prependTypeMapping(type.root.checkType, newParam, type.combinedMapper || type.mapper); + var newMapper = prependTypeMapping(type.root.checkType, newParam, type.mapper); var saveInferTypeParameters_1 = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode_1 = typeToTypeNodeHelper(instantiateType(type.root.extendsType, newMapper), context); @@ -43157,6 +43873,10 @@ var ts; } return typeToTypeNodeHelper(type, context); } + function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) { + return isMappedTypeWithKeyofConstraintDeclaration(type) + && !(getModifiersTypeFromMappedType(type).flags & 262144); + } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 524288)); var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -43164,7 +43884,7 @@ var ts; var appropriateConstraintTypeNode; var newTypeVariable; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { - if (!(getModifiersTypeFromMappedType(type).flags & 262144) && context.flags & 4) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4) { var newParam = createTypeParameter(createSymbol(262144, "T")); var name = typeParameterToName(newParam, context); newTypeVariable = ts.factory.createTypeReferenceNode(name); @@ -43180,8 +43900,9 @@ var ts; var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, undefined); context.approximateLength += 10; var result = ts.setEmitFlags(mappedTypeNode, 1); - if (isMappedTypeWithKeyofConstraintDeclaration(type) && !(getModifiersTypeFromMappedType(type).flags & 262144) && context.flags & 4) { - return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(undefined, ts.factory.cloneNode(newTypeVariable.typeName))), result, ts.factory.createKeywordTypeNode(143)); + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4) { + var originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type.declaration.typeParameter.constraint.type)) || unknownType, type.mapper); + return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(undefined, ts.factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 ? undefined : typeToTypeNodeHelper(originalConstraint, context))), result, ts.factory.createKeywordTypeNode(143)); } return result; } @@ -43196,7 +43917,7 @@ var ts; } else if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) - && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 226 && context.flags & 2048) || + && !(symbol.valueDeclaration && ts.isClassLike(symbol.valueDeclaration) && context.flags & 2048 && (!ts.isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, false).accessibility !== 0)) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -43442,7 +44163,7 @@ var ts; var id = ids_1[_i]; qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id; } - return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf); + return ts.factory.updateImportTypeNode(root, root.argument, root.assertions, qualifier, typeArguments, root.isTypeOf); } else { var typeArguments = root.typeArguments; @@ -43538,7 +44259,7 @@ var ts; anyType : getNonMissingTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 && isLateBoundName(propertySymbol.escapedName)) { + if (context.tracker.trackSymbol && isLateBoundName(propertySymbol.escapedName)) { if (propertySymbol.declarations) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { @@ -43673,7 +44394,7 @@ var ts; function indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, typeNode) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context); - var indexingParameter = ts.factory.createParameterDeclaration(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); + var indexingParameter = ts.factory.createParameterDeclaration(undefined, undefined, name, undefined, indexerTypeNode, undefined); if (!typeNode) { typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); } @@ -43681,7 +44402,7 @@ var ts; context.encounteredError = true; } context.approximateLength += (name.length + 4); - return ts.factory.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.factory.createToken(145)] : undefined, [indexingParameter], typeNode); + return ts.factory.createIndexSignature(indexInfo.isReadonly ? [ts.factory.createToken(145)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { var _a, _b, _c, _d; @@ -43699,7 +44420,7 @@ var ts; } var expandedParams = getExpandedParameters(signature, true)[0]; var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 171, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); - var thisParameter = tryGetThisParameterDeclaration(signature, context); + var thisParameter = context.flags & 33554432 ? undefined : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { parameters.unshift(thisParameter); } @@ -43732,15 +44453,15 @@ var ts; var node = kind === 174 ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 175 ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 168 ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 169 ? ts.factory.createMethodDeclaration(undefined, modifiers, undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), undefined, typeParameters, parameters, returnTypeNode, undefined) : - kind === 171 ? ts.factory.createConstructorDeclaration(undefined, modifiers, parameters, undefined) : - kind === 172 ? ts.factory.createGetAccessorDeclaration(undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, undefined) : - kind === 173 ? ts.factory.createSetAccessorDeclaration(undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, undefined) : - kind === 176 ? ts.factory.createIndexSignature(undefined, modifiers, parameters, returnTypeNode) : + kind === 169 ? ts.factory.createMethodDeclaration(modifiers, undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), undefined, typeParameters, parameters, returnTypeNode, undefined) : + kind === 171 ? ts.factory.createConstructorDeclaration(modifiers, parameters, undefined) : + kind === 172 ? ts.factory.createGetAccessorDeclaration(modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, undefined) : + kind === 173 ? ts.factory.createSetAccessorDeclaration(modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, undefined) : + kind === 176 ? ts.factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 317 ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 179 ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : kind === 180 ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 256 ? ts.factory.createFunctionDeclaration(undefined, modifiers, undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, undefined) : + kind === 256 ? ts.factory.createFunctionDeclaration(modifiers, undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, undefined) : kind === 213 ? ts.factory.createFunctionExpression(modifiers, undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : kind === 214 ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); @@ -43756,7 +44477,7 @@ var ts; if (signature.declaration) { var thisTag = ts.getJSDocThisTag(signature.declaration); if (thisTag && thisTag.typeExpression) { - return ts.factory.createParameterDeclaration(undefined, undefined, undefined, "this", undefined, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); + return ts.factory.createParameterDeclaration(undefined, undefined, "this", undefined, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); } } } @@ -43785,7 +44506,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); - var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined; + var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && ts.canHaveModifiers(parameterDeclaration) ? ts.map(ts.getModifiers(parameterDeclaration), ts.factory.cloneNode) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768; var dotDotDotToken = isRest ? ts.factory.createToken(25) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -43796,18 +44517,23 @@ var ts; ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384; var questionToken = isOptional ? ts.factory.createToken(57) : undefined; - var parameterNode = ts.factory.createParameterDeclaration(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); + var parameterNode = ts.factory.createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { - return elideInitializerAndSetEmitFlags(node); - function elideInitializerAndSetEmitFlags(node) { + return elideInitializerAndPropertyRenamingAndSetEmitFlags(node); + function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) { if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { trackComputedName(node.expression, context.enclosingDeclaration, context); } - var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); + var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags); if (ts.isBindingElement(visited)) { - visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, undefined); + if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, undefined, visited.propertyName, undefined); + } + else { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, undefined); + } } if (!ts.nodeIsSynthesized(visited)) { visited = ts.factory.cloneNode(visited); @@ -43994,6 +44720,7 @@ var ts; return symbol.parent ? ts.factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var _a, _b, _c, _d; var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384)); var isTypeOf = meaning === 111551; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { @@ -44009,6 +44736,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral("import")) ]))); + (_b = (_a = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _b === void 0 ? void 0 : _b.call(_a); } } if (!specifier) { @@ -44026,6 +44754,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral(swappedMode === ts.ModuleKind.ESNext ? "import" : "require")) ]))); + (_d = (_c = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _d === void 0 ? void 0 : _d.call(_c); } } if (!assertion) { @@ -44401,15 +45130,15 @@ var ts; return ts.setOriginalNode(ts.factory.createKeywordTypeNode(130), node); } if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { - return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(undefined, undefined, [ts.factory.createParameterDeclaration(undefined, undefined, undefined, "x", undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); + return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(undefined, [ts.factory.createParameterDeclaration(undefined, undefined, "x", undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); } if (ts.isJSDocFunctionType(node)) { if (ts.isJSDocConstructSignature(node)) { var newTypeNode_1; - return ts.factory.createConstructorTypeNode(node.modifiers, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration(undefined, undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130)); + return ts.factory.createConstructorTypeNode(undefined, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration(undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130)); } else { - return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration(undefined, undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130)); + return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration(undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130)); } } if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(node, 788968, true))) { @@ -44423,7 +45152,7 @@ var ts; !(ts.length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) { return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); } - return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.assertions, node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { var _a = trackExistingEntityName(node, context, includePrivateSymbol), introducesError = _a.introducesError, result = _a.node; @@ -44474,7 +45203,7 @@ var ts; } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 169, true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168, false); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168, false); var enclosingDeclaration = context.enclosingDeclaration; var results = []; var visitedSymbols = new ts.Set(); @@ -44526,7 +45255,7 @@ var ts; var name_3 = ns.name; var body = ns.body; if (ts.length(excessExports)) { - ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(false, undefined, id); })), undefined)], false)))); + ns = ts.factory.updateModuleDeclaration(ns, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration(undefined, false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(false, undefined, id); })), undefined)], false)))); statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, nsIndex), true), [ns], false), statements.slice(nsIndex + 1), true); } if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, name_3); })) { @@ -44544,7 +45273,7 @@ var ts; var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); }); if (ts.length(exports) > 1) { var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; }); - statements = __spreadArray(__spreadArray([], nonExports, true), [ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), undefined)], false); + statements = __spreadArray(__spreadArray([], nonExports, true), [ts.factory.createExportDeclaration(undefined, false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), undefined)], false); } var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); }); if (ts.length(reexports) > 1) { @@ -44553,7 +45282,7 @@ var ts; var _loop_9 = function (group_1) { if (group_1.length > 1) { statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), true), [ - ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier) + ts.factory.createExportDeclaration(undefined, false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier) ], false); } }; @@ -44587,7 +45316,7 @@ var ts; ts.orderedRemoveItemAt(statements, index); } else { - statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); + statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); } } return statements; @@ -44644,12 +45373,11 @@ var ts; if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) { var oldContext = context; context = cloneNodeBuilderContext(context); - var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); + serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); if (context.reportedDiagnostic) { oldcontext.reportedDiagnostic = context.reportedDiagnostic; } context = oldContext; - return result; } } function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { @@ -44712,7 +45440,7 @@ var ts; if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right) && ((_d = type.symbol) === null || _d === void 0 ? void 0 : _d.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; - addResult(ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, alias, localName)])), 0); + addResult(ts.factory.createExportDeclaration(undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, alias, localName)])), 0); context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551); } else { @@ -44721,7 +45449,7 @@ var ts; ], flags)), textRange); addResult(statement, name !== localName ? modifierFlags & ~1 : modifierFlags); if (name !== localName && !isPrivate) { - addResult(ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, name, localName)])), 0); + addResult(ts.factory.createExportDeclaration(undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, name, localName)])), 0); needsExportDeclaration = false; needsPostExportDefault = false; } @@ -44762,15 +45490,15 @@ var ts; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); if (!resolvedModule) continue; - addResult(ts.factory.createExportDeclaration(undefined, undefined, false, undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0); + addResult(ts.factory.createExportDeclaration(undefined, false, undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0); } } } if (needsPostExportDefault) { - addResult(ts.factory.createExportAssignment(undefined, undefined, false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0); + addResult(ts.factory.createExportAssignment(undefined, false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0); } else if (needsExportDeclaration) { - addResult(ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, getInternalSymbolName(symbol, symbolName), symbolName)])), 0); + addResult(ts.factory.createExportDeclaration(undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, getInternalSymbolName(symbol, symbolName), symbolName)])), 0); } } function includePrivateSymbol(symbol) { @@ -44828,7 +45556,7 @@ var ts; && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); - addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(undefined, undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); + addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; context.enclosingDeclaration = oldEnclosingDecl; } @@ -44843,7 +45571,7 @@ var ts; var constructSignatures = serializeSignatures(1, interfaceType, baseType, 175); var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(94, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551); }))]; - addResult(ts.factory.createInterfaceDeclaration(undefined, undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), constructSignatures, true), callSignatures, true), members, true)), modifierFlags); + addResult(ts.factory.createInterfaceDeclaration(undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), constructSignatures, true), callSignatures, true), members, true)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); @@ -44863,7 +45591,7 @@ var ts; if (ts.length(mergedMembers)) { var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); - var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export="; }), function (s) { + var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration(undefined, false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export="; }), function (s) { var _a, _b; var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); @@ -44877,11 +45605,11 @@ var ts; var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; return ts.factory.createExportSpecifier(false, name === targetName ? undefined : targetName, name); })))]); - addResult(ts.factory.createModuleDeclaration(undefined, undefined, ts.factory.createIdentifier(localName), nsBody, 16), 0); + addResult(ts.factory.createModuleDeclaration(undefined, ts.factory.createIdentifier(localName), nsBody, 16), 0); } } function serializeEnum(symbol, symbolName, modifierFlags) { - addResult(ts.factory.createEnumDeclaration(undefined, ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8); }), function (p) { + addResult(ts.factory.createEnumDeclaration(ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8); }), function (p) { var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) ? getConstantValue(p.declarations[0]) : undefined; return ts.factory.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined : typeof initializedValue === "string" ? ts.factory.createStringLiteral(initializedValue) : @@ -44919,7 +45647,7 @@ var ts; }) ? "local" : "remote"; }); var localProps = localVsRemoteMap.get("local") || ts.emptyArray; - var fakespace = ts.parseNodeFactory.createModuleDeclaration(undefined, undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16); + var fakespace = ts.parseNodeFactory.createModuleDeclaration(undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16); ts.setParent(fakespace, enclosingDeclaration); fakespace.locals = ts.createSymbolTable(props); fakespace.symbol = props[0].parent; @@ -44935,9 +45663,9 @@ var ts; addingDeclare = oldAddingDeclare; var declarations = results; results = oldResults; - var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, d.expression, ts.factory.createIdentifier("default"))])) : d; }); + var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration(undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, d.expression, ts.factory.createIdentifier("default"))])) : d; }); var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced; - fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); + fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); addResult(fakespace, modifierFlags); } } @@ -44993,7 +45721,7 @@ var ts; ? getBaseConstructorTypeOfClass(staticType) : anyType; var heritageClauses = __spreadArray(__spreadArray([], !ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(94, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], true), !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(117, implementsExpressions)], true); - var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); + var symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { var valueDecl = s.valueDeclaration; return !!valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); @@ -45003,7 +45731,7 @@ var ts; return !!valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); var privateProperties = hasPrivateIdentifier ? - [ts.factory.createPropertyDeclaration(undefined, undefined, ts.factory.createPrivateIdentifier("#private"), undefined, undefined, undefined)] : + [ts.factory.createPropertyDeclaration(undefined, ts.factory.createPrivateIdentifier("#private"), undefined, undefined, undefined)] : ts.emptyArray; var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, false, baseTypes[0]); }); var staticMembers = ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304) && p.escapedName !== "prototype" && !isNamespaceMember(p); }), function (p) { return serializePropertySymbolForClass(p, true, staticBaseType); }); @@ -45012,11 +45740,11 @@ var ts; ts.isInJSFile(symbol.valueDeclaration) && !ts.some(getSignaturesOfType(staticType, 1)); var constructors = isNonConstructableClassLikeInJsFile ? - [ts.factory.createConstructorDeclaration(undefined, ts.factory.createModifiersFromModifierFlags(8), [], undefined)] : + [ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(8), [], undefined)] : serializeSignatures(1, staticType, staticBaseType, 171); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; - addResult(ts.setTextRange(ts.factory.createClassDeclaration(undefined, undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), staticMembers, true), constructors, true), publicProperties, true), privateProperties, true)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags); + addResult(ts.setTextRange(ts.factory.createClassDeclaration(undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), staticMembers, true), constructors, true), publicProperties, true), privateProperties, true)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags); } function getSomeTargetNameFromDeclarations(declarations) { return ts.firstDefined(declarations, function (d) { @@ -45058,7 +45786,7 @@ var ts; if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 254) { var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); var propertyName = node.propertyName; - addResult(ts.factory.createImportDeclaration(undefined, undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier(false, propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1), undefined), 0); + addResult(ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier(false, propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1), undefined), 0); break; } ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); @@ -45073,8 +45801,8 @@ var ts; var initializer = node.initializer; var uniqueName = ts.factory.createUniqueName(localName); var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); - addResult(ts.factory.createImportEqualsDeclaration(undefined, undefined, false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0); - addResult(ts.factory.createImportEqualsDeclaration(undefined, undefined, false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); + addResult(ts.factory.createImportEqualsDeclaration(undefined, false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0); + addResult(ts.factory.createImportEqualsDeclaration(undefined, false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); break; } case 265: @@ -45083,7 +45811,7 @@ var ts; break; } var isLocalImport = !(target.flags & 512) && !ts.isVariableDeclaration(node); - addResult(ts.factory.createImportEqualsDeclaration(undefined, undefined, false, ts.factory.createIdentifier(localName), isLocalImport + addResult(ts.factory.createImportEqualsDeclaration(undefined, false, ts.factory.createIdentifier(localName), isLocalImport ? symbolToName(target, context, 67108863, false) : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0); break; @@ -45091,16 +45819,16 @@ var ts; addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0); break; case 267: - addResult(ts.factory.createImportDeclaration(undefined, undefined, ts.factory.createImportClause(false, ts.factory.createIdentifier(localName), undefined), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context)), undefined), 0); + addResult(ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(false, ts.factory.createIdentifier(localName), undefined), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context)), undefined), 0); break; case 268: - addResult(ts.factory.createImportDeclaration(undefined, undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), undefined), 0); + addResult(ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), undefined), 0); break; case 274: - addResult(ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0); + addResult(ts.factory.createExportDeclaration(undefined, false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0); break; case 270: - addResult(ts.factory.createImportDeclaration(undefined, undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports([ + addResult(ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports([ ts.factory.createImportSpecifier(false, localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName)) ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context)), undefined), 0); break; @@ -45126,7 +45854,7 @@ var ts; } } function serializeExportSpecifier(localName, targetName, specifier) { - addResult(ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, localName !== targetName ? targetName : undefined, localName)]), specifier), 0); + addResult(ts.factory.createExportDeclaration(undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(false, localName !== targetName ? targetName : undefined, localName)]), specifier), 0); } function serializeMaybeAliasAssignment(symbol) { if (symbol.flags & 4194304) { @@ -45148,7 +45876,7 @@ var ts; var oldTrack = context.tracker.trackSymbol; context.tracker.trackSymbol = function () { return false; }; if (isExportAssignmentCompatibleSymbolName) { - results.push(ts.factory.createExportAssignment(undefined, undefined, isExportEquals, symbolToExpression(target, context, 67108863))); + results.push(ts.factory.createExportAssignment(undefined, isExportEquals, symbolToExpression(target, context, 67108863))); } else { if (first_1 === expr && first_1) { @@ -45159,7 +45887,7 @@ var ts; } else { var varName = getUnusedName(name, symbol); - addResult(ts.factory.createImportEqualsDeclaration(undefined, undefined, false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863, false)), 0); + addResult(ts.factory.createImportEqualsDeclaration(undefined, false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863, false)), 0); serializeExportSpecifier(name, varName); } } @@ -45181,7 +45909,7 @@ var ts; : 0); } if (isExportAssignmentCompatibleSymbolName) { - results.push(ts.factory.createExportAssignment(undefined, undefined, isExportEquals, ts.factory.createIdentifier(varName))); + results.push(ts.factory.createExportAssignment(undefined, isExportEquals, ts.factory.createIdentifier(varName))); return true; } else if (name !== varName) { @@ -45225,22 +45953,22 @@ var ts; if (p.flags & 98304 && useAccessors) { var result = []; if (p.flags & 65536) { - result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration(undefined, undefined, undefined, "arg", undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], undefined), ((_b = p.declarations) === null || _b === void 0 ? void 0 : _b.find(ts.isSetAccessor)) || firstPropertyLikeDecl)); + result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration(undefined, undefined, "arg", undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], undefined), ((_b = p.declarations) === null || _b === void 0 ? void 0 : _b.find(ts.isSetAccessor)) || firstPropertyLikeDecl)); } if (p.flags & 32768) { var isPrivate_1 = modifierFlags & 8; - result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); + result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; } else if (p.flags & (4 | 3 | 98304)) { - return ts.setTextRange(createProperty(undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 : 0) | flag), name, p.flags & 16777216 ? ts.factory.createToken(57) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 : 0) | flag), name, p.flags & 16777216 ? ts.factory.createToken(57) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); } if (p.flags & (8192 | 16)) { var type = getTypeOfSymbol(p); var signatures = getSignaturesOfType(type, 0); if (flag & 8) { - return ts.setTextRange(createProperty(undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 : 0) | flag), name, p.flags & 16777216 ? ts.factory.createToken(57) : undefined, undefined, undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 : 0) | flag), name, p.flags & 16777216 ? ts.factory.createToken(57) : undefined, undefined, undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } var results_1 = []; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { @@ -45293,7 +46021,7 @@ var ts; } } if (privateProtected) { - return [ts.setTextRange(ts.factory.createConstructorDeclaration(undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), [], undefined), signatures[0].declaration)]; + return [ts.setTextRange(ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(privateProtected), [], undefined), signatures[0].declaration)]; } } var results = []; @@ -45907,7 +46635,7 @@ var ts; return type; } if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration, 0)) & 32768) ? getNonUndefinedType(type) : type; + return strictNullChecks && !(getTypeFacts(checkDeclarationInitializer(declaration, 0)) & 16777216) ? getNonUndefinedType(type) : type; } return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0)], 2)); } @@ -46270,7 +46998,7 @@ var ts; (resolvedSymbol || symbol).exports.forEach(function (s, name) { var _a; var exportedMember = members_4.get(name); - if (exportedMember && exportedMember !== s) { + if (exportedMember && exportedMember !== s && !(s.flags & 2097152)) { if (s.flags & 111551 && exportedMember.flags & 111551) { if (s.valueDeclaration && exportedMember.valueDeclaration && ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); @@ -46293,6 +47021,17 @@ var ts; } }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.indexInfos); + if (initialSize === members_4.size) { + if (type.aliasSymbol) { + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = type.aliasTypeArguments; + } + if (ts.getObjectFlags(type) & 4) { + result.aliasSymbol = type.symbol; + var args = getTypeArguments(type); + result.aliasTypeArguments = ts.length(args) ? args : undefined; + } + } result.objectFlags |= (ts.getObjectFlags(type) & 4096); if (result.symbol && result.symbol.flags & 32 && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { result.objectFlags |= 16777216; @@ -46336,7 +47075,7 @@ var ts; if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAny(element, anyType); } - return includePatternInType ? nonInferrableAnyType : anyType; + return anyType; } function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); @@ -47223,7 +47962,7 @@ var ts; error(declaration.typeExpression.type, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } else { - error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + error(ts.isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } } links.declaredType = type; @@ -48347,6 +49086,9 @@ var ts; else if (type.objectFlags & 32) { resolveMappedTypeMembers(type); } + else { + ts.Debug.fail("Unhandled object type " + ts.Debug.formatObjectFlags(type.objectFlags)); + } } else if (type.flags & 1048576) { resolveUnionTypeMembers(type); @@ -48354,6 +49096,9 @@ var ts; else if (type.flags & 2097152) { resolveIntersectionTypeMembers(type); } + else { + ts.Debug.fail("Unhandled type " + ts.Debug.formatTypeFlags(type.flags)); + } } return type; } @@ -48515,7 +49260,7 @@ var ts; } } } - else if (t.flags & 469892092) { + else if (t.flags & 469892092 || isEmptyAnonymousObjectType(t)) { hasDisjointDomainType = true; } } @@ -48523,12 +49268,12 @@ var ts; if (hasDisjointDomainType) { for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { var t = types_6[_a]; - if (t.flags & 469892092) { + if (t.flags & 469892092 || isEmptyAnonymousObjectType(t)) { constraints = ts.append(constraints, t); } } } - return getIntersectionType(constraints); + return getNormalizedType(getIntersectionType(constraints), false); } return undefined; } @@ -48624,7 +49369,7 @@ var ts; } if (t.flags & 268435456) { var constraint = getBaseConstraint(t.type); - return constraint ? getStringMappingType(t.symbol, constraint) : stringType; + return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType; } if (t.flags & 8388608) { if (isMappedTypeGenericIndexedAccess(t)) { @@ -48695,7 +49440,7 @@ var ts; var objectType; return !!(type.flags & 8388608 && ts.getObjectFlags(objectType = type.objectType) & 32 && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && - !objectType.declaration.questionToken && !objectType.declaration.nameType); + !(getMappedTypeModifiers(objectType) & 8) && !objectType.declaration.nameType); } function getApparentType(type) { var t = !(type.flags & 465829888) ? type : getBaseConstraintOfType(type) || unknownType; @@ -48928,12 +49673,12 @@ var ts; } return errorInfo; } - function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment) { + function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) { type = getReducedApparentType(type); if (type.flags & 524288) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { + if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) { return symbol; } if (skipObjectFunctionPropertyAugment) @@ -49023,12 +49768,15 @@ var ts; return getApplicableIndexInfo(type, isLateBoundName(name) ? esSymbolType : getStringLiteralType(ts.unescapeLeadingUnderscores(name))); } function getTypeParametersFromDeclaration(declaration) { + var _a; var result; - for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { - var node = _a[_i]; + for (var _i = 0, _b = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _b.length; _i++) { + var node = _b[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); } - return result; + return (result === null || result === void 0 ? void 0 : result.length) ? result + : ts.isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) === null || _a === void 0 ? void 0 : _a.typeParameters + : undefined; } function symbolsToArray(symbols) { var result = []; @@ -49531,19 +50279,20 @@ var ts; var _a; var inferences; if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { - for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; + var _loop_15 = function (declaration) { if (declaration.parent.kind === 190) { var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; if (grandParent.kind === 178 && !omitTypeReferences) { - var typeReference = grandParent; - var typeParameters = getTypeParametersForTypeReference(typeReference); - if (typeParameters) { - var index = typeReference.typeArguments.indexOf(childTypeParameter); - if (index < typeParameters.length) { - var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + var typeReference_1 = grandParent; + var typeParameters_1 = getTypeParametersForTypeReference(typeReference_1); + if (typeParameters_1) { + var index = typeReference_1.typeArguments.indexOf(childTypeParameter); + if (index < typeParameters_1.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters_1[index]); if (declaredConstraint) { - var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var mapper = makeDeferredTypeMapper(typeParameters_1, typeParameters_1.map(function (_, index) { return function () { + return getEffectiveTypeArgumentAtIndex(typeReference_1, typeParameters_1, index); + }; })); var constraint = instantiateType(declaredConstraint, mapper); if (constraint !== typeParameter) { inferences = ts.append(inferences, constraint); @@ -49572,6 +50321,10 @@ var ts; inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); } } + }; + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + _loop_15(declaration); } } return inferences && getIntersectionType(inferences); @@ -49633,7 +50386,7 @@ var ts; var result = 0; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type = types_8[_i]; - if (!(type.flags & excludeKinds)) { + if (excludeKinds === undefined || !(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } } @@ -49645,7 +50398,7 @@ var ts; if (!type) { type = createObjectType(4, target.symbol); target.instantiations.set(id, type); - type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; + type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0; type.target = target; type.resolvedTypeArguments = typeArguments; } @@ -50379,7 +51132,7 @@ var ts; var lastRequiredIndex = -1; var firstRestIndex = -1; var lastOptionalOrRestIndex = -1; - var _loop_15 = function (i) { + var _loop_16 = function (i) { var type = elementTypes[i]; var flags = target.elementFlags[i]; if (flags & 8) { @@ -50405,7 +51158,7 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - var state_4 = _loop_15(i); + var state_4 = _loop_16(i); if (typeof state_4 === "object") return state_4.value; } @@ -50582,7 +51335,7 @@ var ts; var templates = ts.filter(types, isPatternLiteralType); if (templates.length) { var i = types.length; - var _loop_16 = function () { + var _loop_17 = function () { i--; var t = types[i]; if (t.flags & 128 && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { @@ -50590,7 +51343,7 @@ var ts; } }; while (i > 0) { - _loop_16(); + _loop_17(); } } } @@ -50660,14 +51413,14 @@ var ts; var namedUnions = []; addNamedUnions(namedUnions, types); var reducedTypes = []; - var _loop_17 = function (t) { + var _loop_18 = function (t) { if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) { reducedTypes.push(t); } }; for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) { var t = typeSet_1[_i]; - _loop_17(t); + _loop_18(t); } if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) { return namedUnions[0]; @@ -50793,7 +51546,7 @@ var ts; } return includes; } - function removeRedundantPrimitiveTypes(types, includes) { + function removeRedundantSupertypes(types, includes) { var i = types.length; while (i > 0) { i--; @@ -50801,7 +51554,9 @@ var ts; var remove = t.flags & 4 && includes & (128 | 134217728 | 268435456) || t.flags & 8 && includes & 256 || t.flags & 64 && includes & 2048 || - t.flags & 4096 && includes & 8192; + t.flags & 4096 && includes & 8192 || + t.flags & 16384 && includes & 32768 || + isEmptyAnonymousObjectType(t) && includes & 470302716; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -50896,7 +51651,7 @@ var ts; result.aliasTypeArguments = aliasTypeArguments; return result; } - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types, aliasSymbol, aliasTypeArguments, noSupertypeReduction) { var typeMembershipMap = new ts.Map(); var includes = addTypesToIntersection(typeMembershipMap, 0, types); var typeSet = ts.arrayFrom(typeMembershipMap.values()); @@ -50924,11 +51679,11 @@ var ts; if (includes & 4 && includes & (128 | 134217728 | 268435456) || includes & 8 && includes & 256 || includes & 64 && includes & 2048 || - includes & 4096 && includes & 8192) { - removeRedundantPrimitiveTypes(typeSet, includes); - } - if (includes & 16777216 && includes & 524288) { - ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + includes & 4096 && includes & 8192 || + includes & 16384 && includes & 32768 || + includes & 16777216 && includes & 470302716) { + if (!noSupertypeReduction) + removeRedundantSupertypes(typeSet, includes); } if (includes & 262144) { typeSet[typeSet.indexOf(undefinedType)] = missingType; @@ -50960,7 +51715,7 @@ var ts; return errorType; } var constituents = getCrossProductIntersections(typeSet); - var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152); }) ? createOriginUnionOrIntersectionType(2097152, typeSet) : undefined; + var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152); }) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152, typeSet) : undefined; result = getUnionType(constituents, 1, aliasSymbol, aliasTypeArguments, origin); } } @@ -51003,11 +51758,21 @@ var ts; } return intersections; } + function getConstituentCount(type) { + return !(type.flags & 3145728) || type.aliasSymbol ? 1 : + type.flags & 1048576 && type.origin ? getConstituentCount(type.origin) : + getConstituentCountOfTypes(type.types); + } + function getConstituentCountOfTypes(types) { + return ts.reduceLeft(types, function (n, t) { return n + getConstituentCount(t); }, 0); + } function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var aliasSymbol = getAliasSymbolForTypeNode(node); - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var types = ts.map(node.types, getTypeFromTypeNode); + var noSupertypeReduction = types.length === 2 && !!(types[0].flags & (4 | 8 | 64)) && types[1] === emptyTypeLiteralType; + links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); } return links.resolvedType; } @@ -51105,19 +51870,22 @@ var ts; return getUnionType(ts.concatenate(propertyTypes, indexKeyTypes), 1, undefined, undefined, origin); } function isPossiblyReducibleByInstantiation(type) { - return ts.some(type.types, function (t) { - var uniqueFilled = getUniqueLiteralFilledInstantiation(t); - return getReducedType(uniqueFilled) !== uniqueFilled; - }); + var uniqueFilled = getUniqueLiteralFilledInstantiation(type); + return getReducedType(uniqueFilled) !== uniqueFilled; + } + function shouldDeferIndexType(type) { + return !!(type.flags & 58982400 || + isGenericTupleType(type) || + isGenericMappedType(type) && !hasDistributiveNameType(type) || + type.flags & 1048576 && ts.some(type.types, isPossiblyReducibleByInstantiation) || + type.flags & 2097152 && maybeTypeOfKind(type, 465829888) && ts.some(type.types, isEmptyAnonymousObjectType)); } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } type = getReducedType(type); - return type.flags & 1048576 ? isPossiblyReducibleByInstantiation(type) - ? getIndexTypeForGenericType(type, stringsOnly) - : getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 2097152 ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 58982400 || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + return shouldDeferIndexType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + type.flags & 1048576 ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : + type.flags & 2097152 ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : ts.getObjectFlags(type) & 32 ? getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) : type === wildcardType ? wildcardType : type.flags & 2 ? neverType : @@ -51243,9 +52011,11 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 | 131072) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : - type.flags & 128 ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type; + 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; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -51256,6 +52026,15 @@ var ts; } return str; } + function applyTemplateStringMapping(symbol, texts, types) { + switch (intrinsicTypeKinds.get(symbol.escapedName)) { + case 0: return [texts.map(function (t) { return t.toUpperCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 1: return [texts.map(function (t) { return t.toLowerCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 2: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toUpperCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + case 3: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toLowerCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + } + return [texts, types]; + } function getStringMappingTypeForGenericType(symbol, type) { var id = "".concat(getSymbolId(symbol), ",").concat(getTypeId(type)); var result = stringMappingTypes.get(id); @@ -51347,21 +52126,28 @@ var ts; getFlowTypeOfReference(accessExpression, propType) : propType; } - if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName) && +propName >= 0) { + if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName)) { + var index = +propName; if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 16)) { var indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { + if (index < 0) { + error(indexNode, ts.Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); + return undefinedType; + } error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); } else { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } } - errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, function (t) { - var restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 ? getUnionType([restType, undefinedType]) : restType; - }); + if (index >= 0) { + errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); + return mapType(objectType, function (t) { + var restType = getRestTypeOfTupleType(t) || undefinedType; + return accessFlags & 1 ? getUnionType([restType, undefinedType]) : restType; + }); + } } } if (!(indexType.flags & 98304) && isTypeAssignableToKind(indexType, 402653316 | 296 | 12288)) { @@ -51485,7 +52271,7 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 | 4 | 8 | 64)); + return !!(type.flags & (1 | 4 | 8 | 64)) || !!(type.flags & 268435456 && isPatternLiteralPlaceholderType(type.type)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -51595,7 +52381,7 @@ var ts; function substituteIndexedMappedType(objectType, index) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]); var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return instantiateType(getTemplateTypeFromMappedType(objectType.target || objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) { if (accessFlags === void 0) { accessFlags = 0; } @@ -51720,7 +52506,7 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_18 = function () { + var _loop_19 = function () { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; @@ -51794,7 +52580,7 @@ var ts; return "break"; }; while (true) { - var state_5 = _loop_18(); + var state_5 = _loop_19(); if (typeof state_5 === "object") return state_5.value; if (state_5 === "break") @@ -51891,6 +52677,7 @@ var ts; } } function getTypeFromImportTypeNode(node) { + var _a; var links = getNodeLinks(node); if (!links.resolvedType) { if (node.isTypeOf && node.typeArguments) { @@ -51909,6 +52696,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } + var isExportEquals = !!((_a = innerModuleSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("export=")); var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); @@ -51917,9 +52705,11 @@ var ts; while (current = nameStack.shift()) { var meaning = nameStack.length ? 1920 : targetMeaning; var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace)); - var next = node.isTypeOf - ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText) - : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var symbolFromVariable = node.isTypeOf || ts.isInJSFile(node) && isExportEquals + ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText, false, true) + : undefined; + var symbolFromModule = node.isTypeOf ? undefined : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var next = symbolFromModule !== null && symbolFromModule !== void 0 ? symbolFromModule : symbolFromVariable; if (!next) { error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); return links.resolvedType = errorType; @@ -52395,7 +53185,7 @@ var ts; switch (mapper.kind) { case 0: return type === mapper.source ? mapper.target : type; - case 1: + case 1: { var sources = mapper.sources; var targets = mapper.targets; for (var i = 0; i < sources.length; i++) { @@ -52404,43 +53194,58 @@ var ts; } } return type; - case 2: - return mapper.func(type); + } + case 2: { + var sources = mapper.sources; + var targets = mapper.targets; + for (var i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets[i](); + } + } + return type; + } case 3: + return mapper.func(type); case 4: + case 5: var t1 = getMappedType(type, mapper.mapper1); - return t1 !== type && mapper.kind === 3 ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); + return t1 !== type && mapper.kind === 4 ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); } } function makeUnaryTypeMapper(source, target) { - return { kind: 0, source: source, target: target }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 0, source: source, target: target }); } function makeArrayTypeMapper(sources, targets) { - return { kind: 1, sources: sources, targets: targets }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 1, sources: sources, targets: targets }); + } + function makeFunctionTypeMapper(func, debugInfo) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 3, func: func, debugInfo: ts.Debug.isDebugging ? debugInfo : undefined }); } - function makeFunctionTypeMapper(func) { - return { kind: 2, func: func }; + function makeDeferredTypeMapper(sources, targets) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 2, sources: sources, targets: targets }); } function makeCompositeTypeMapper(kind, mapper1, mapper2) { - return { kind: kind, mapper1: mapper1, mapper2: mapper2 }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: kind, mapper1: mapper1, mapper2: mapper2 }); } function createTypeEraser(sources) { return createTypeMapper(sources, undefined); } function createBackreferenceMapper(context, index) { - return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; }); + var forwardInferences = context.inferences.slice(index); + return createTypeMapper(ts.map(forwardInferences, function (i) { return i.typeParameter; }), ts.map(forwardInferences, function () { return unknownType; })); } function combineTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(3, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(4, mapper1, mapper2) : mapper2; } function mergeTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(4, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(5, mapper1, mapper2) : mapper2; } function prependTypeMapping(source, target, mapper) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4, makeUnaryTypeMapper(source, target), mapper); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5, makeUnaryTypeMapper(source, target), mapper); } function appendTypeMapping(mapper, source, target) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4, mapper, makeUnaryTypeMapper(source, target)); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5, mapper, makeUnaryTypeMapper(source, target)); } function getRestrictiveTypeParameter(tp) { return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), @@ -52664,6 +53469,7 @@ var ts; result.mapper = mapper; result.aliasSymbol = aliasSymbol || type.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + result.objectFlags |= result.aliasTypeArguments ? getPropagatingFlagsOfTypes(result.aliasTypeArguments) : 0; return result; } function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { @@ -53251,7 +54057,7 @@ var ts; }); } function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068) + if (target.flags & (131068 | 131072)) return false; if (isTupleLikeType(source)) { return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); @@ -53316,7 +54122,7 @@ var ts; }); } function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068) + if (target.flags & (131068 | 131072)) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); } @@ -53382,7 +54188,7 @@ var ts; var sourceSig = checkMode & 3 ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = checkMode & 3 ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && - (getFalsyFlags(sourceType) & 98304) === (getFalsyFlags(targetType) & 98304); + (getTypeFacts(sourceType) & 50331648) === (getTypeFacts(targetType) & 50331648); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8) | (strictVariance ? 2 : 1), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3) && !strictVariance && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); @@ -53486,6 +54292,20 @@ var ts; return !!(ts.getObjectFlags(type) & 16 && (type.members && isEmptyResolvedType(type) || type.symbol && type.symbol.flags & 2048 && getMembersOfSymbol(type.symbol).size === 0)); } + function isUnknownLikeUnionType(type) { + if (strictNullChecks && type.flags & 1048576) { + if (!(type.objectFlags & 33554432)) { + var types = type.types; + type.objectFlags |= 33554432 | (types.length >= 3 && types[0].flags & 32768 && + types[1].flags & 65536 && ts.some(types, isEmptyAnonymousObjectType) ? 67108864 : 0); + } + return !!(type.objectFlags & 67108864); + } + return false; + } + function containsUndefinedType(type) { + return !!((type.flags & 1048576 ? type.types[0] : type).flags & 32768); + } function isStringIndexSignatureOnlyType(type) { return type.flags & 524288 && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & 3145728 && ts.every(type.types, isStringIndexSignatureOnlyType) || @@ -53563,13 +54383,15 @@ var ts; return true; if (s & 65536 && (!strictNullChecks && !(t & 3145728) || t & 65536)) return true; - if (s & 524288 && t & 67108864) + if (s & 524288 && t & 67108864 && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(ts.getObjectFlags(source) & 8192))) return true; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1) return true; if (s & (8 | 256) && !(s & 1024) && (t & 32 || relation === assignableRelation && t & 256 && t & 1024)) return true; + if (isUnknownLikeUnionType(target)) + return true; } return false; } @@ -53611,16 +54433,27 @@ var ts; function getNormalizedType(type, writing) { while (true) { var t = isFreshLiteralType(type) ? type.regularType : - ts.getObjectFlags(type) & 4 && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 3145728 ? getReducedType(type) : + ts.getObjectFlags(type) & 4 ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : + type.flags & 3145728 ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 ? writing ? type.baseType : type.substitute : type.flags & 25165824 ? getSimplifiedType(type, writing) : type; - t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) - break; + return t; type = t; } + } + function getNormalizedUnionOrIntersectionType(type, writing) { + var reduced = getReducedType(type); + if (reduced !== type) { + return reduced; + } + if (type.flags & 2097152) { + var normalizedTypes = ts.sameMap(type.types, function (t) { return getNormalizedType(t, writing); }); + if (normalizedTypes !== type.types) { + return getIntersectionType(normalizedTypes); + } + } return type; } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { @@ -53827,7 +54660,7 @@ var ts; ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable"); generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); } - if (target.flags & 262144 && target !== markerSuperType && target !== markerSubType) { + if (target.flags & 262144 && target !== markerSuperTypeForCheck && target !== markerSubTypeForCheck) { var constraint = getBaseConstraintOfType(target); var needsOriginalSource = void 0; if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) { @@ -53995,6 +54828,7 @@ var ts; return 0; } function reportErrorResults(originalSource, originalTarget, source, target, headMessage) { + var _a, _b; var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; @@ -54033,6 +54867,14 @@ var ts; return; } reportRelationError(headMessage, source, target); + if (source.flags & 262144 && ((_b = (_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) === null || _b === void 0 ? void 0 : _b[0]) && !getConstraintOfType(source)) { + var syntheticParam = cloneTypeParameter(source); + syntheticParam.constraint = instantiateType(target, makeUnaryTypeMapper(source, syntheticParam)); + if (hasNonCircularBaseConstraint(syntheticParam)) { + var targetConstraintString = typeToString(target, source.symbol.declarations[0]); + associateRelatedInfo(ts.createDiagnosticForNode(source.symbol.declarations[0], ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint, targetConstraintString)); + } + } } function traceUnionsOrIntersectionsTooLarge(source, target) { if (!ts.tracing) { @@ -54084,7 +54926,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 ? reducedTarget.types : [reducedTarget]; } - var _loop_19 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -54137,7 +54979,7 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_6 = _loop_19(prop); + var state_6 = _loop_20(prop); if (typeof state_6 === "object") return state_6.value; } @@ -54156,7 +54998,7 @@ var ts; return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068) && !(target.flags & 131068)); } if (target.flags & 2097152) { - return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2); + return typeRelatedToEachType(source, target, reportErrors, 2); } if (relation === comparableRelation && target.flags & 131068) { var constraints = ts.sameMap(source.types, getBaseConstraintOrType); @@ -54325,10 +55167,10 @@ var ts; if (outofbandVarianceMarkerHandler) { var saved = entry & 24; if (saved & 8) { - instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers)); + instantiateType(source, reportUnmeasurableMapper); } if (saved & 16) { - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } } return entry & 1 ? -1 : 0; @@ -54420,13 +55262,26 @@ var ts; return result; } 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 && everyType(constraint, function (c) { return c !== source; })) { + result = isRelatedTo(constraint, target, 1, false, undefined, intersectionState); + } + } + if (result) { + resetErrorInfo(saveErrorInfo); + } + 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; - var saveErrorInfo = captureErrorCalculationState(); var sourceFlags = source.flags; var targetFlags = target.flags; if (relation === identityRelation) { @@ -54471,15 +55326,6 @@ var ts; if (result = unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState)) { return result; } - if (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; })) { - if (result = isRelatedTo(constraint, target, 1, false, undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - } if (!(sourceFlags & 465829888 || sourceFlags & 524288 && targetFlags & 1048576 || sourceFlags & 2097152 && targetFlags & (524288 | 1048576 | 465829888))) { @@ -54511,6 +55357,18 @@ var ts; } } } + if (relation === comparableRelation && sourceFlags & 262144) { + var constraint = getConstraintOfTypeParameter(source); + if (constraint && hasNonCircularBaseConstraint(source)) { + while (constraint && constraint.flags & 262144) { + if (result = isRelatedTo(constraint, target, 1, false)) { + return result; + } + constraint = getConstraintOfTypeParameter(constraint); + } + } + return 0; + } } else if (targetFlags & 4194304) { var targetType_1 = target.type; @@ -54556,7 +55414,6 @@ var ts; result &= isRelatedTo(source.indexType, target.indexType, 3, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } if (reportErrors) { @@ -54632,7 +55489,6 @@ var ts; } else if (targetFlags & 16777216) { if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3; } var c = target; @@ -54642,7 +55498,6 @@ var ts; if (result = skipTrue ? -1 : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2, false)) { result &= skipFalse ? -1 : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2, false); if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -54653,34 +55508,32 @@ var ts; if (relation === comparableRelation) { return templateLiteralTypesDefinitelyUnrelated(source, target) ? 0 : -1; } - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1; } } + else if (target.flags & 268435456) { + if (!(source.flags & 268435456)) { + if (isMemberOfStringMapping(source, target)) { + return -1; + } + } + } if (sourceFlags & 8650752) { if (!(sourceFlags & 8388608 && targetFlags & 8388608)) { - var constraint = getConstraintOfType(source); - if (!constraint || (sourceFlags & 262144 && constraint.flags & 1)) { - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864), 3)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - else if (result = isRelatedTo(constraint, target, 1, false, undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + var constraint = getConstraintOfType(source) || unknownType; + if (result = isRelatedTo(constraint, target, 1, false, undefined, intersectionState)) { return result; } - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1, reportErrors && !(targetFlags & sourceFlags & 262144), undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1, reportErrors && constraint !== unknownType && !(targetFlags & sourceFlags & 262144), undefined, intersectionState)) { return result; } if (isMappedTypeGenericIndexedAccess(source)) { var indexConstraint = getConstraintOfType(source.indexType); if (indexConstraint) { if (result = isRelatedTo(getIndexedAccessType(source.objectType, indexConstraint), target, 1, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -54689,7 +55542,6 @@ var ts; } else if (sourceFlags & 4194304) { if (result = isRelatedTo(keyofConstraintType, target, 1, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -54697,29 +55549,28 @@ var ts; if (!(targetFlags & 134217728)) { var constraint = getBaseConstraintOfType(source); if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } } else if (sourceFlags & 268435456) { - if (targetFlags & 268435456 && source.symbol === target.symbol) { + if (targetFlags & 268435456) { + if (source.symbol !== target.symbol) { + return 0; + } if (result = isRelatedTo(source.type, target.type, 3, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } else { var constraint = getBaseConstraintOfType(source); if (constraint && (result = isRelatedTo(constraint, target, 1, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } } else if (sourceFlags & 16777216) { if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3; } if (targetFlags & 16777216) { @@ -54738,7 +55589,6 @@ var ts; result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -54747,7 +55597,6 @@ var ts; var distributiveConstraint = hasNonCircularBaseConstraint(source) ? getConstraintOfDistributiveConditionalType(source) : undefined; if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, 1, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -54755,7 +55604,6 @@ var ts; var defaultConstraint = getDefaultConstraintOfConditionalType(source); if (defaultConstraint) { if (result = isRelatedTo(defaultConstraint, target, 1, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -54767,7 +55615,6 @@ var ts; if (isGenericMappedType(target)) { if (isGenericMappedType(source)) { if (result = mappedTypeRelatedTo(source, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -54861,25 +55708,13 @@ var ts; } } } - function reportUnmeasurableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(false); - } - return p; - } - function reportUnreliableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(true); - } - return p; - } function mappedTypeRelatedTo(source, target, reportErrors) { var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); - var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); + var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMapper : reportUnreliableMapper); if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { @@ -54915,11 +55750,11 @@ var ts; } var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_20 = 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_21 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -54932,7 +55767,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_8 = _loop_21(i); + var state_8 = _loop_22(i); switch (state_8) { case "continue-outer": continue outer; } @@ -54946,7 +55781,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_7 = _loop_20(combination); + var state_7 = _loop_21(combination); if (typeof state_7 === "object") return state_7.value; } @@ -55352,7 +56187,7 @@ var ts; return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); }; } function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, makeFunctionTypeMapper(reportUnreliableMarkers)); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, reportUnreliableMapper); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -55499,7 +56334,7 @@ var ts; return typeCouldHaveTopLevelSingletonTypes(constraint); } } - return isUnitType(type) || !!(type.flags & 134217728); + return isUnitType(type) || !!(type.flags & 134217728) || !!(type.flags & 268435456); } function getExactOptionalUnassignableProperties(source, target) { if (isTupleType(source) && isTupleType(target)) @@ -55590,7 +56425,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_22 = function (tp) { + var _loop_23 = function (tp) { var modifiers = getVarianceModifiers(tp); var variance = modifiers & 65536 ? modifiers & 32768 ? 0 : 1 : @@ -55619,12 +56454,12 @@ var ts; } variances.push(variance); }; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - _loop_22(tp); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var tp = typeParameters_2[_i]; + _loop_23(tp); } links.variances = variances; - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); } return links.variances; } @@ -55900,32 +56735,28 @@ var ts; var commonBaseType; for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { var t = types_13[_i]; - var baseType = getBaseTypeOfLiteralType(t); - if (!commonBaseType) { - commonBaseType = baseType; - } - if (baseType === t || baseType !== commonBaseType) { - return false; + if (!(t.flags & 131072)) { + var baseType = getBaseTypeOfLiteralType(t); + commonBaseType !== null && commonBaseType !== void 0 ? commonBaseType : (commonBaseType = baseType); + if (baseType === t || baseType !== commonBaseType) { + return false; + } } } return true; } - function getSupertypeOrUnion(types) { - if (types.length === 1) { - return types[0]; - } - return literalTypesWithSameBaseType(types) ? - getUnionType(types) : - ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + function getCombinedTypeFlags(types) { + return ts.reduceLeft(types, function (flags, t) { return flags | (t.flags & 1048576 ? getCombinedTypeFlags(t.types) : t.flags); }, 0); } function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); + if (types.length === 1) { + return types[0]; } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304); }); - return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304) : - getUnionType(types, 2); + var primaryTypes = strictNullChecks ? ts.sameMap(types, function (t) { return filterType(t, function (u) { return !(u.flags & 98304); }); }) : types; + var superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? + getUnionType(primaryTypes) : + ts.reduceLeft(primaryTypes, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & 98304); } function getCommonSubtype(types) { return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); @@ -56024,9 +56855,14 @@ var ts; type.flags & 256 ? numberType : type.flags & 2048 ? bigintType : type.flags & 512 ? booleanType : - type.flags & 1048576 ? mapType(type, getBaseTypeOfLiteralType) : + type.flags & 1048576 ? getBaseTypeOfLiteralTypeUnion(type) : type; } + function getBaseTypeOfLiteralTypeUnion(type) { + var _a; + var key = "B".concat(getTypeId(type)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); + } function getWidenedLiteralType(type) { return type.flags & 1024 && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : type.flags & 128 && isFreshLiteralType(type) ? stringType : @@ -56103,26 +56939,8 @@ var ts; var value = _a.value; return value.base10Value === "0"; } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - result |= getFalsyFlags(t); - } - return result; - } - function getFalsyFlags(type) { - return type.flags & 1048576 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 128 ? type.value === "" ? 128 : 0 : - type.flags & 256 ? type.value === 0 ? 256 : 0 : - type.flags & 2048 ? isZeroBigInt(type) ? 2048 : 0 : - type.flags & 512 ? (type === falseType || type === regularFalseType) ? 512 : 0 : - type.flags & 117724; - } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 117632 ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 117632); }) : - type; + return filterType(type, function (t) { return !!(getTypeFacts(t) & 4194304); }); } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); @@ -56152,16 +56970,15 @@ var ts; return type.flags & 32768 ? type : getUnionType([type, isProperty ? missingType : undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { - var reducedType = getTypeWithFacts(type, 2097152); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288, undefined) || unknownSymbol; } return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? - getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : - reducedType; + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : + getIntersectionType([type, emptyObjectType]); } function getNonNullableType(type) { - return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + return strictNullChecks ? getAdjustedTypeWithFacts(type, 2097152) : type; } function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; @@ -56191,12 +57008,13 @@ var ts; && ((target.flags & (8 | 4 | 16)) !== 0); } function isObjectTypeWithInferableIndex(type) { + var objectFlags = ts.getObjectFlags(type); return type.flags & 2097152 ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 | 2048 | 384 | 512)) !== 0 && !(type.symbol.flags & 32) - && !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 && isObjectTypeWithInferableIndex(type.source)); + && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & 4194304) || !!(objectFlags & 1024 && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8); @@ -56505,25 +57323,27 @@ var ts; signature: signature, flags: flags, compareTypes: compareTypes, - mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, true); }), - nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, false); }), + mapper: reportUnmeasurableMapper, + nonFixingMapper: reportUnmeasurableMapper, }; + context.mapper = makeFixingMapperForContext(context); + context.nonFixingMapper = makeNonFixingMapperForContext(context); return context; } - function mapToInferredType(context, t, fix) { - var inferences = context.inferences; - for (var i = 0; i < inferences.length; i++) { - var inference = inferences[i]; - if (t === inference.typeParameter) { - if (fix && !inference.isFixed) { - inferFromIntraExpressionSites(context); - clearCachedInferences(inferences); - inference.isFixed = true; - } - return getInferredType(context, i); + function makeFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (inference, i) { return function () { + if (!inference.isFixed) { + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; } - } - return t; + return getInferredType(context, i); + }; })); + } + function makeNonFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (_, i) { return function () { + return getInferredType(context, i); + }; })); } function clearCachedInferences(inferences) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { @@ -56755,17 +57575,50 @@ var ts; return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen); } - function isValidBigIntString(s) { + function isValidNumberString(s, roundTripOnly) { + if (s === "") + return false; + var n = +s; + return isFinite(n) && (!roundTripOnly || "" + n === s); + } + function parseBigIntLiteralType(text) { + var negative = text.startsWith("-"); + var base10Value = ts.parsePseudoBigInt("".concat(negative ? text.slice(1) : text, "n")); + return getBigIntLiteralType({ negative: negative, base10Value: base10Value }); + } + function isValidBigIntString(s, roundTripOnly) { + if (s === "") + return false; var scanner = ts.createScanner(99, false); var success = true; scanner.setOnError(function () { return success = false; }); scanner.setText(s + "n"); var result = scanner.scan(); - if (result === 40) { + var negative = result === 40; + if (negative) { result = scanner.scan(); } var flags = scanner.getTokenFlags(); - return success && result === 9 && scanner.getTextPos() === (s.length + 1) && !(flags & 512); + return success && result === 9 && scanner.getTextPos() === (s.length + 1) && !(flags & 512) + && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); + } + function isMemberOfStringMapping(source, target) { + if (target.flags & (4 | 3)) { + return true; + } + if (target.flags & 134217728) { + return isTypeAssignableTo(source, target); + } + if (target.flags & 268435456) { + var mappingStack = []; + while (target.flags & 268435456) { + mappingStack.unshift(target.symbol); + target = target.type; + } + var mappedSource = ts.reduceLeft(mappingStack, function (memo, value) { return getStringMappingType(value, memo); }, source); + return mappedSource === source && isMemberOfStringMapping(source, target); + } + return false; } function isValidTypeForTemplateLiteralPlaceholder(source, target) { if (source === target || target.flags & (1 | 4)) { @@ -56773,9 +57626,10 @@ var ts; } if (source.flags & 128) { var value = source.value; - return !!(target.flags & 8 && value !== "" && isFinite(+value) || - target.flags & 64 && value !== "" && isValidBigIntString(value) || - target.flags & (512 | 98304) && value === target.intrinsicName); + return !!(target.flags & 8 && isValidNumberString(value, false) || + target.flags & 64 && isValidBigIntString(value, false) || + target.flags & (512 | 98304) && value === target.intrinsicName || + target.flags & 268435456 && isMemberOfStringMapping(getStringLiteralType(value), target)); } if (source.flags & 134217728) { var texts = source.texts; @@ -56876,8 +57730,10 @@ var ts; propagationType = savePropagationType; return; } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + if (source.aliasSymbol && source.aliasSymbol === target.aliasSymbol) { + if (source.aliasTypeArguments) { + inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + } return; } if (source === target && source.flags & 3145728) { @@ -56914,7 +57770,7 @@ var ts; target = getActualTypeVariable(target); } if (target.flags & 8650752) { - if (source === nonInferrableAnyType || source === silentNeverType || (priority & 128 && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -56969,15 +57825,11 @@ var ts; inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target)); } else if (source.flags & 4194304 && target.flags & 4194304) { - contravariant = !contravariant; - inferFromTypes(source.type, target.type); - contravariant = !contravariant; + inferFromContravariantTypes(source.type, target.type); } else if ((isLiteralType(source) || source.flags & 4) && target.flags & 4194304) { var empty = createEmptyObjectTypeFromStringLiteral(source); - contravariant = !contravariant; - inferWithPriority(empty, target.type, 256); - contravariant = !contravariant; + inferFromContravariantTypesWithPriority(empty, target.type, 256); } else if (source.flags & 8388608 && target.flags & 8388608) { inferFromTypes(source.objectType, target.objectType); @@ -56990,10 +57842,7 @@ var ts; } else if (source.flags & 33554432) { inferFromTypes(source.baseType, target); - var oldPriority = priority; - priority |= 4; - inferFromTypes(source.substitute, target); - priority = oldPriority; + inferWithPriority(source.substitute, target, 4); } else if (target.flags & 16777216) { invokeOnce(source, target, inferToConditionalType); @@ -57032,6 +57881,18 @@ var ts; inferFromTypes(source, target); priority = savePriority; } + function inferFromContravariantTypesWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromContravariantTypes(source, target); + priority = savePriority; + } + function inferToMultipleTypesWithPriority(source, targets, targetFlags, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferToMultipleTypes(source, targets, targetFlags); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -57094,10 +57955,13 @@ var ts; } } function inferFromContravariantTypes(source, target) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + function inferFromContravariantTypesIfStrictFunctionTypes(source, target) { if (strictFunctionTypes || priority & 1024) { - contravariant = !contravariant; - inferFromTypes(source, target); - contravariant = !contravariant; + inferFromContravariantTypes(source, target); } else { inferFromTypes(source, target); @@ -57116,8 +57980,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var type = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -57228,19 +58092,59 @@ var ts; inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else { - var savePriority = priority; - priority |= contravariant ? 64 : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; - inferToMultipleTypes(source, targetTypes, target.flags); - priority = savePriority; + inferToMultipleTypesWithPriority(source, targetTypes, target.flags, contravariant ? 64 : 0); } } function inferToTemplateLiteralType(source, target) { var matches = inferTypesFromTemplateLiteralType(source, target); var types = target.types; if (matches || ts.every(target.texts, function (s) { return s.length === 0; })) { + 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) { + var inferenceContext = getInferenceInfoForType(target_3); + var constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : undefined; + if (constraint && !isTypeAny(constraint)) { + var constraintTypes = constraint.flags & 1048576 ? constraint.types : [constraint]; + var allTypeFlags_1 = ts.reduceLeft(constraintTypes, function (flags, t) { return flags | t.flags; }, 0); + if (!(allTypeFlags_1 & 4)) { + var str_1 = source_1.value; + if (allTypeFlags_1 & 296 && !isValidNumberString(str_1, true)) { + allTypeFlags_1 &= ~296; + } + if (allTypeFlags_1 & 2112 && !isValidBigIntString(str_1, true)) { + allTypeFlags_1 &= ~2112; + } + var matchingType = ts.reduceLeft(constraintTypes, function (left, right) { + return !(right.flags & allTypeFlags_1) ? left : + left.flags & 4 ? left : right.flags & 4 ? source_1 : + left.flags & 134217728 ? left : right.flags & 134217728 && isTypeMatchedByTemplateLiteralType(source_1, right) ? source_1 : + left.flags & 268435456 ? left : right.flags & 268435456 && str_1 === applyStringMapping(right.symbol, str_1) ? source_1 : + left.flags & 128 ? left : right.flags & 128 && right.value === str_1 ? right : + left.flags & 8 ? left : right.flags & 8 ? getNumberLiteralType(+str_1) : + left.flags & 32 ? left : right.flags & 32 ? getNumberLiteralType(+str_1) : + left.flags & 256 ? left : right.flags & 256 && right.value === +str_1 ? right : + left.flags & 64 ? left : right.flags & 64 ? parseBigIntLiteralType(str_1) : + left.flags & 2048 ? left : right.flags & 2048 && ts.pseudoBigIntToString(right.value) === str_1 ? right : + left.flags & 16 ? left : right.flags & 16 ? str_1 === "true" ? trueType : str_1 === "false" ? falseType : booleanType : + left.flags & 512 ? left : right.flags & 512 && right.intrinsicName === str_1 ? right : + left.flags & 32768 ? left : right.flags & 32768 && right.intrinsicName === str_1 ? right : + left.flags & 65536 ? left : right.flags & 65536 && right.intrinsicName === str_1 ? right : + left; + }, neverType); + if (!(matchingType.flags & 131072)) { + inferFromTypes(matchingType, target_3); + return "continue"; + } + } + } + } + inferFromTypes(source_1, target_3); + }; for (var i = 0; i < types.length; i++) { - inferFromTypes(matches ? matches[i] : neverType, types[i]); + _loop_24(i); } } } @@ -57340,19 +58244,16 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 262144); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } - function inferFromSignature(source, target, skipParameters) { - if (!skipParameters) { - var saveBivariant = bivariant; - var kind = target.declaration ? target.declaration.kind : 0; - bivariant = bivariant || kind === 169 || kind === 168 || kind === 171; - applyToParameterTypes(source, target, inferFromContravariantTypes); - bivariant = saveBivariant; - } + function inferFromSignature(source, target) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0; + bivariant = bivariant || kind === 169 || kind === 168 || kind === 171; + applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); + bivariant = saveBivariant; applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { @@ -57570,6 +58471,14 @@ var ts; var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); return key && key + "." + propName; } + break; + case 201: + case 202: + case 256: + case 213: + case 214: + case 169: + return "".concat(getNodeId(node), "#").concat(getTypeId(declaredType)); } return undefined; } @@ -57710,7 +58619,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_23 = function (type) { + var _loop_25 = function (type) { if (type.flags & (524288 | 2097152 | 58982400)) { var discriminant = getTypeOfPropertyOfType(type, name); if (discriminant) { @@ -57734,9 +58643,9 @@ var ts; } } }; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - var state_9 = _loop_23(type); + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var type = types_15[_i]; + var state_9 = _loop_25(type); if (typeof state_9 === "object") return state_9.value; } @@ -57815,33 +58724,36 @@ var ts; return false; } function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 131072) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (assignedType.flags & 512 && isFreshLiteralType(assignedType)) { - reducedType = mapType(reducedType, getFreshTypeOfLiteralType); - } - if (isTypeAssignableTo(assignedType, reducedType)) { - return reducedType; - } + var _a; + if (declaredType === assignedType) { + return declaredType; } - return declaredType; + if (assignedType.flags & 131072) { + return assignedType; + } + var key = "A".concat(getTypeId(declaredType), ",").concat(getTypeId(assignedType)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); + } + function getAssignmentReducedTypeWorker(declaredType, assignedType) { + var filteredType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + var reducedType = assignedType.flags & 512 && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType; + return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType; } function isFunctionObjectType(type) { var resolved = resolveStructuredTypeMembers(type); return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type, ignoreObjects) { - if (ignoreObjects === void 0) { ignoreObjects = false; } + function getTypeFacts(type) { + if (type.flags & (2097152 | 465829888)) { + type = getBaseConstraintOfType(type) || unknownType; + } var flags = type.flags; - if (flags & 4) { + if (flags & (4 | 268435456)) { return strictNullChecks ? 16317953 : 16776705; } - if (flags & 128) { - var isEmpty = type.value === ""; + if (flags & (128 | 134217728)) { + var isEmpty = flags & 128 && type.value === ""; return strictNullChecks ? isEmpty ? 12123649 : 7929345 : isEmpty ? 12582401 : 16776705; @@ -57873,20 +58785,20 @@ var ts; (type === falseType || type === regularFalseType) ? 12580616 : 16774920; } if (flags & 524288) { - if (ignoreObjects) { - return 16768959; - } return ts.getObjectFlags(type) & 16 && isEmptyObjectType(type) ? - strictNullChecks ? 16318463 : 16777215 : + strictNullChecks ? 83427327 : 83886079 : isFunctionObjectType(type) ? strictNullChecks ? 7880640 : 16728000 : strictNullChecks ? 7888800 : 16736160; } - if (flags & (16384 | 32768)) { + if (flags & 16384) { return 9830144; } + if (flags & 32768) { + return 26607360; + } if (flags & 65536) { - return 9363232; + return 42917664; } if (flags & 12288) { return strictNullChecks ? 7925520 : 16772880; @@ -57897,33 +58809,49 @@ var ts; if (flags & 131072) { return 0; } - if (flags & 465829888) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : - strictNullChecks ? 7929345 : 16776705; - } if (flags & 1048576) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0); } if (flags & 2097152) { - ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068)); - return getIntersectionTypeFacts(type, ignoreObjects); + return getIntersectionTypeFacts(type); } - return 16777215; + return 83886079; } - function getIntersectionTypeFacts(type, ignoreObjects) { + function getIntersectionTypeFacts(type) { + var ignoreObjects = maybeTypeOfKind(type, 131068); var oredFacts = 0; - var andedFacts = 16777215; + var andedFacts = 134217727; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - var f = getTypeFacts(t, ignoreObjects); - oredFacts |= f; - andedFacts &= f; + if (!(ignoreObjects && t.flags & 524288)) { + var f = getTypeFacts(t); + oredFacts |= f; + andedFacts &= f; + } } - return oredFacts & 8256 | andedFacts & 16768959; + return oredFacts & 8256 | andedFacts & 134209471; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } + function getAdjustedTypeWithFacts(type, facts) { + var reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 ? unknownUnionType : type, facts)); + if (strictNullChecks) { + switch (facts) { + case 524288: + return mapType(reduced, function (t) { return getTypeFacts(t) & 65536 ? getIntersectionType([t, getTypeFacts(t) & 131072 && !maybeTypeOfKind(reduced, 65536) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t; }); + case 1048576: + return mapType(reduced, function (t) { return getTypeFacts(t) & 131072 ? getIntersectionType([t, getTypeFacts(t) & 65536 && !maybeTypeOfKind(reduced, 32768) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t; }); + case 2097152: + case 4194304: + return mapType(reduced, function (t) { return getTypeFacts(t) & 262144 ? getGlobalNonNullableTypeInstantiation(t) : t; }); + } + } + return reduced; + } + function recombineUnknownType(type) { + return type === unknownUnionType ? unknownType : type; + } function getTypeWithDefault(type, defaultExpression) { return defaultExpression ? getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : @@ -58075,19 +59003,15 @@ var ts; } return links.switchTypes; } - function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) { + function getSwitchClauseTypeOfWitnesses(switchStatement) { + if (ts.some(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 289 && !ts.isStringLiteralLike(clause.expression); })) { + return undefined; + } var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 289) { - if (ts.isStringLiteralLike(clause.expression)) { - witnesses.push(clause.expression.text); - continue; - } - return ts.emptyArray; - } - if (retainDefault) - witnesses.push(undefined); + var text = clause.kind === 289 ? clause.expression.text : undefined; + witnesses.push(text && !ts.contains(witnesses, text) ? text : undefined); } return witnesses; } @@ -58164,8 +59088,8 @@ var ts; var types = origin && origin.flags & 1048576 ? origin.types : type.types; var mappedTypes; var changed = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; var mapped = t.flags & 1048576 ? mapType(t, mapper, noReductions) : mapper(t); changed || (changed = t !== mapped); if (mapped) { @@ -58238,8 +59162,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (!(t.flags & 131072)) { if (!(ts.getObjectFlags(t) & 256)) { return false; @@ -58655,7 +59579,7 @@ var ts; return declaredType; } if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 243 && isMatchingReference(reference, node.parent.parent.expression)) { - return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); } return undefined; } @@ -58864,7 +59788,7 @@ var ts; if (isEvolvingArrayTypeList(types)) { return getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))); } - var result = getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + var result = recombineUnknownType(getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction)); if (result !== declaredType && result.flags & declaredType.flags & 1048576 && ts.arraysEqual(result.types, declaredType.types)) { return declaredType; } @@ -58960,11 +59884,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return type.flags & 2 && assumeTrue ? nonNullUnknownType : - getTypeWithFacts(type, assumeTrue ? 4194304 : 8388608); + return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 : 8388608); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { - type = getTypeWithFacts(type, 2097152); + type = getAdjustedTypeWithFacts(type, 2097152); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -59083,7 +60006,7 @@ var ts; var targetType = ts.hasStaticModifier(ts.Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, true); } function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { var equalsOperator = operator === 34 || operator === 36; @@ -59091,7 +60014,7 @@ var ts; var valueType = getTypeOfExpression(value); var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) || equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 | nullableFlags)); }); - return removeNullable ? getTypeWithFacts(type, 2097152) : type; + return removeNullable ? getAdjustedTypeWithFacts(type, 2097152) : type; } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1) { @@ -59101,9 +60024,6 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (assumeTrue && (type.flags & 2) && (operator === 34 || operator === 35) && (valueType.flags & 65536)) { - return getUnionType([nullType, undefinedType]); - } if ((type.flags & 2) && assumeTrue && (operator === 36 || operator === 37)) { if (valueType.flags & (131068 | 67108864)) { return valueType; @@ -59123,7 +60043,7 @@ var ts; valueType.flags & 65536 ? assumeTrue ? 131072 : 1048576 : assumeTrue ? 65536 : 524288; - return type.flags & 2 && facts & (1048576 | 2097152) ? nonNullUnknownType : getTypeWithFacts(type, facts); + return getAdjustedTypeWithFacts(type, facts); } if (assumeTrue) { var filterFn = operator === 34 ? @@ -59143,21 +60063,13 @@ var ts; var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { - return getTypeWithFacts(type, 2097152); + return getAdjustedTypeWithFacts(type, 2097152); } return type; } - if (type.flags & 1 && literal.text === "function") { - return type; - } - if (assumeTrue && type.flags & 2 && literal.text === "object") { - return type === nonNullUnknownType ? nonPrimitiveType : getUnionType([nonPrimitiveType, nullType]); - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 128 : - typeofNEFacts.get(literal.text) || 32768; - var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text); - return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts); + return assumeTrue ? + narrowTypeByTypeName(type, literal.text) : + getTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768); } function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); @@ -59200,58 +60112,40 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 ? defaultType : getUnionType([caseType, defaultType]); } - function getImpliedTypeFromTypeofGuard(type, text) { - switch (text) { - case "function": - return type.flags & 1 ? type : globalFunctionType; - case "object": - return type.flags & 2 ? getUnionType([nonPrimitiveType, nullType]) : type; - default: - return typeofTypesByName.get(text); - } - } - function narrowUnionMemberByTypeof(candidate) { - return function (type) { - if (isTypeSubtypeOf(type, candidate)) { - return type; - } - if (isTypeSubtypeOf(candidate, type)) { - return candidate; - } - if (type.flags & 465829888) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(candidate, constraint)) { - return getIntersectionType([type, candidate]); - } - } - return type; - }; + function narrowTypeByTypeName(type, typeName) { + switch (typeName) { + case "string": return narrowTypeByTypeFacts(type, stringType, 1); + case "number": return narrowTypeByTypeFacts(type, numberType, 2); + case "bigint": return narrowTypeByTypeFacts(type, bigintType, 4); + case "boolean": return narrowTypeByTypeFacts(type, booleanType, 8); + case "symbol": return narrowTypeByTypeFacts(type, esSymbolType, 16); + case "object": return type.flags & 1 ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32), narrowTypeByTypeFacts(type, nullType, 131072)]); + case "function": return type.flags & 1 ? type : narrowTypeByTypeFacts(type, globalFunctionType, 64); + case "undefined": return narrowTypeByTypeFacts(type, undefinedType, 65536); + } + return narrowTypeByTypeFacts(type, nonPrimitiveType, 128); + } + function narrowTypeByTypeFacts(type, impliedType, facts) { + return mapType(type, function (t) { + return isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? getTypeFacts(t) & facts ? t : neverType : + isTypeSubtypeOf(impliedType, t) ? impliedType : + getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : + neverType; + }); } function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { - var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, true); - if (!switchWitnesses.length) { + var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!witnesses) { return type; } - var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); - var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); - var clauseWitnesses; - var switchFacts; - if (defaultCaseLocation > -1) { - var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); - var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; - var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; - clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); - switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); - } - else { - clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); - switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); - } + var defaultIndex = ts.findIndex(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 290; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultIndex >= clauseStart && defaultIndex < clauseEnd); if (hasDefaultClause) { - return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + var notEqualFacts_1 = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); + return filterType(type, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }); } - var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts); - return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts); + var clauseWitnesses = witnesses.slice(clauseStart, clauseEnd); + return getUnionType(ts.map(clauseWitnesses, function (text) { return text ? narrowTypeByTypeName(type, text) : neverType; })); } function isMatchingConstructorReference(expr) { return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || @@ -59291,7 +60185,7 @@ var ts; var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { - return getTypeWithFacts(type, 2097152); + return getAdjustedTypeWithFacts(type, 2097152); } return type; } @@ -59321,22 +60215,37 @@ var ts; if (!nonConstructorTypeInUnion) return type; } - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, true); + } + function getNarrowedType(type, candidate, assumeTrue, checkDerived) { + var _a; + var key = type.flags & 1048576 ? "N".concat(getTypeId(type), ",").concat(getTypeId(candidate), ",").concat((assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)) : undefined; + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { + function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) { + var isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf; if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - if (type.flags & 1048576) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 131072)) { - return assignableType; - } + if (type.flags & 3) { + return candidate; } - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); + var keyPropertyName = type.flags & 1048576 ? getKeyPropertyName(type) : undefined; + var narrowedType = mapType(candidate, function (c) { + var discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName); + var matching = discriminant && getConstituentTypeForKeyType(type, discriminant); + var directlyRelated = mapType(matching || type, checkDerived ? + function (t) { return isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType; } : + function (t) { return isTypeSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : neverType; }); + return directlyRelated.flags & 131072 ? + mapType(type, function (t) { return maybeTypeOfKind(t, 465829888) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType; }) : + directlyRelated; + }); + return !(narrowedType.flags & 131072) ? narrowedType : + isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -59363,15 +60272,15 @@ var ts; var predicateArgument = getTypePredicateArgument(predicate, callExpression); if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + return getNarrowedType(type, predicate.type, assumeTrue, false); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && !(getTypeFacts(predicate.type) & 65536)) { - type = getTypeWithFacts(type, 2097152); + type = getAdjustedTypeWithFacts(type, 2097152); } var access = getDiscriminantPropertyAccess(predicateArgument, type); if (access) { - return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); + return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, false); }); } } } @@ -59418,7 +60327,7 @@ var ts; } function narrowTypeByOptionality(type, expr, assumePresent) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumePresent ? 2097152 : 262144); + return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 : 262144); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -59493,8 +60402,8 @@ var ts; var annotationIncludesUndefined = strictNullChecks && declaration.kind === 164 && declaration.initializer && - getFalsyFlags(declaredType) & 32768 && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768); + getTypeFacts(declaredType) & 16777216 && + !(getTypeFacts(checkExpression(declaration.initializer)) & 16777216); popTypeResolution(); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288) : declaredType; } @@ -59512,7 +60421,9 @@ var ts; !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { - return !!(type.flags & 465829888 && getBaseConstraintOrType(type).flags & (98304 | 1048576)); + return type.flags & 2097152 ? + ts.some(type.types, isGenericTypeWithUnionConstraint) : + !!(type.flags & 465829888 && getBaseConstraintOrType(type).flags & (98304 | 1048576)); } function isGenericTypeWithoutNullableConstraint(type) { return !!(type.flags & 465829888 && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304)); @@ -59522,14 +60433,14 @@ var ts; !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 64 ? getContextualType(node, 8) - : getContextualType(node)); + : getContextualType(node, undefined)); return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { var substituteConstraints = !(checkMode && checkMode & 2) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); - return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 ? getBaseConstraintOrType(t) : t; }) : type; + return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (n) { @@ -59625,7 +60536,7 @@ var ts; getNodeLinks(container).flags |= 8192; return getTypeOfSymbol(symbol); } - if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + if (shouldMarkIdentifierAliasReferenced(node)) { markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); @@ -59732,12 +60643,29 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 32768) && getFalsyFlags(flowType) & 32768) { + else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function shouldMarkIdentifierAliasReferenced(node) { + var _a; + var parent = node.parent; + if (parent) { + if (ts.isPropertyAccessExpression(parent) && parent.expression === node) { + return false; + } + if (ts.isExportSpecifier(parent) && parent.isTypeOnly) { + return false; + } + var greatGrandparent = (_a = parent.parent) === null || _a === void 0 ? void 0 : _a.parent; + if (greatGrandparent && ts.isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) { + return false; + } + } + return true; + } function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } @@ -59846,7 +60774,7 @@ var ts; } function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) { if (ts.isPropertyDeclaration(container) && ts.hasStaticModifier(container) && - container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.length(container.parent.decorators)) { + container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.hasDecorators(container.parent)) { error(thisExpression, ts.Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); } } @@ -60162,7 +61090,7 @@ var ts; if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { - var contextualType = getApparentTypeOfContextualType(containingLiteral); + var contextualType = getApparentTypeOfContextualType(containingLiteral, undefined); var literal = containingLiteral; var type = contextualType; while (type) { @@ -60174,7 +61102,7 @@ var ts; break; } literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); + type = getApparentTypeOfContextualType(literal, undefined); } return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral)); } @@ -60224,7 +61152,7 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } - function getContextualTypeForVariableLikeDeclaration(declaration) { + function getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -60233,17 +61161,17 @@ var ts; case 164: return getContextuallyTypedParameterType(declaration); case 203: - return getContextualTypeForBindingElement(declaration); + return getContextualTypeForBindingElement(declaration, contextFlags); case 167: if (ts.isStatic(declaration)) { - return getContextualTypeForStaticPropertyDeclaration(declaration); + return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); } } } - function getContextualTypeForBindingElement(declaration) { + function getContextualTypeForBindingElement(declaration, contextFlags) { var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - var parentType = getContextualTypeForVariableLikeDeclaration(parent) || + var parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== 203 && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 64 : 0); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; @@ -60259,8 +61187,8 @@ var ts; return getTypeOfPropertyOfType(parentType, text); } } - function getContextualTypeForStaticPropertyDeclaration(declaration) { - var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent); + function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) { + var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags); if (!parentType) return undefined; return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName); @@ -60268,29 +61196,32 @@ var ts; function getContextualTypeForInitializerExpression(node, contextFlags) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var result = getContextualTypeForVariableLikeDeclaration(declaration); + var result = getContextualTypeForVariableLikeDeclaration(declaration, contextFlags); if (result) { return result; } - if (!(contextFlags & 8) && ts.isBindingPattern(declaration.name)) { + if (!(contextFlags & 8) && ts.isBindingPattern(declaration.name) && declaration.name.elements.length > 0) { return getTypeFromBindingPattern(declaration.name, true, false); } } return undefined; } - function getContextualTypeForReturnExpression(node) { + function getContextualTypeForReturnExpression(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { var functionFlags = ts.getFunctionFlags(func); if (functionFlags & 1) { - var use = functionFlags & 2 ? 2 : 1; - var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, undefined); - if (!iterationTypes) { + var isAsyncGenerator_1 = (functionFlags & 2) !== 0; + if (contextualReturnType.flags & 1048576) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1, type, isAsyncGenerator_1); }); + } + var iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1, contextualReturnType, (functionFlags & 2) !== 0); + if (!iterationReturnType) { return undefined; } - contextualReturnType = iterationTypes.returnType; + contextualReturnType = iterationReturnType; } if (functionFlags & 2) { var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeNoAlias); @@ -60309,15 +61240,19 @@ var ts; } return undefined; } - function getContextualTypeForYieldOperand(node) { + function getContextualTypeForYieldOperand(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { + var isAsyncGenerator_2 = (functionFlags & 2) !== 0; + if (!node.asteriskToken && contextualReturnType.flags & 1048576) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1, type, isAsyncGenerator_2); }); + } return node.asteriskToken ? contextualReturnType - : getIterationTypeOfGeneratorFunctionReturnType(0, contextualReturnType, (functionFlags & 2) !== 0); + : getIterationTypeOfGeneratorFunctionReturnType(0, contextualReturnType, isAsyncGenerator_2); } } return undefined; @@ -60337,14 +61272,14 @@ var ts; } function getContextualIterationType(kind, functionDecl) { var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2); - var contextualReturnType = getContextualReturnType(functionDecl); + var contextualReturnType = getContextualReturnType(functionDecl, undefined); if (contextualReturnType) { return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || undefined; } return undefined; } - function getContextualReturnType(functionDecl) { + function getContextualReturnType(functionDecl, contextFlags) { var returnType = getReturnTypeFromAnnotation(functionDecl); if (returnType) { return returnType; @@ -60355,7 +61290,7 @@ var ts; } var iife = ts.getImmediatelyInvokedFunctionExpression(functionDecl); if (iife) { - return getContextualType(iife); + return getContextualType(iife, contextFlags); } return undefined; } @@ -60417,6 +61352,14 @@ var ts; var lhsType = getTypeOfExpression(e.expression); return ts.isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText); } + if (ts.isElementAccessExpression(e)) { + var propType = checkExpressionCached(e.argumentExpression); + if (!isTypeUsableAsPropertyName(propType)) { + return undefined; + } + var lhsType = getTypeOfExpression(e.expression); + return getPropertyOfType(lhsType, getPropertyNameFromType(propType)); + } return undefined; function tryGetPrivateIdentifierPropertyOfType(type, id) { var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id); @@ -60434,7 +61377,7 @@ var ts; if (decl && (ts.isPropertyDeclaration(decl) || ts.isPropertySignature(decl))) { var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); return (overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper)) || - (decl.initializer && getTypeOfExpression(binaryExpression.left)); + (ts.isPropertyDeclaration(decl) ? decl.initializer && getTypeOfExpression(binaryExpression.left) : undefined); } if (kind === 0) { return getTypeOfExpression(binaryExpression.left); @@ -60560,7 +61503,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; - var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element, contextFlags); if (propertyAssignmentType) { return propertyAssignmentType; } @@ -60585,8 +61528,8 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined; } - function getContextualTypeForChildJsxExpression(node, child) { - var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + function getContextualTypeForChildJsxExpression(node, child, contextFlags) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { return undefined; @@ -60603,24 +61546,24 @@ var ts; } }, true)); } - function getContextualTypeForJsxExpression(node) { + function getContextualTypeForJsxExpression(node, contextFlags) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) - ? getContextualType(node) + ? getContextualType(node, contextFlags) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent, node) + ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) : undefined; } - function getContextualTypeForJsxAttribute(attribute) { + function getContextualTypeForJsxAttribute(attribute, contextFlags) { if (ts.isJsxAttribute(attribute)) { - var attributesType = getApparentTypeOfContextualType(attribute.parent); + var attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return getContextualType(attribute.parent); + return getContextualType(attribute.parent, contextFlags); } } function isPossiblyDiscriminantValue(node) { @@ -60664,16 +61607,14 @@ var ts; function instantiateContextualType(contextualType, node, contextFlags) { if (contextualType && maybeTypeOfKind(contextualType, 465829888)) { var inferenceContext = getInferenceContext(node); - if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { - if (contextFlags && contextFlags & 1) { - return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); - } - if (inferenceContext.returnMapper) { - var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); - return type.flags & 1048576 && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? - filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : - type; - } + if (inferenceContext && contextFlags & 1 && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); + } + if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.returnMapper) { + var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); + return type.flags & 1048576 && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? + filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : + type; } } return contextualType; @@ -60707,9 +61648,9 @@ var ts; return getContextualTypeForInitializerExpression(node, contextFlags); case 214: case 247: - return getContextualTypeForReturnExpression(node); + return getContextualTypeForReturnExpression(node, contextFlags); case 224: - return getContextualTypeForYieldOperand(parent); + return getContextualTypeForYieldOperand(parent, contextFlags); case 218: return getContextualTypeForAwaitOperand(parent, contextFlags); case 208: @@ -60746,17 +61687,17 @@ var ts; case 271: return tryGetTypeFromEffectiveTypeNode(parent); case 288: - return getContextualTypeForJsxExpression(parent); + return getContextualTypeForJsxExpression(parent, contextFlags); case 285: case 287: - return getContextualTypeForJsxAttribute(parent); + return getContextualTypeForJsxAttribute(parent, contextFlags); case 280: case 279: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; function tryFindWhenConstTypeReference(node) { - return getContextualType(node); + return getContextualType(node, contextFlags); } } function getInferenceContext(node) { @@ -60987,8 +61928,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var current = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var current = types_18[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -61025,7 +61966,7 @@ var ts; var elementCount = elements.length; var elementTypes = []; var elementFlags = []; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, undefined); var inDestructuringPattern = ts.isAssignmentTarget(node); var inConstContext = isConstContext(node); var hasOmittedExpression = false; @@ -61174,7 +62115,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, undefined); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 201 || contextualType.pattern.kind === 205); var inConstContext = isConstContext(node); @@ -61472,7 +62413,7 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes, undefined); var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); var childrenPropSymbol = createSymbol(4, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : @@ -61951,19 +62892,19 @@ var ts; return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { - return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304); + return !!(getTypeFacts(type) & 50331648); } function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function reportObjectPossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 ? flags & 65536 ? + function reportObjectPossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 ? facts & 33554432 ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); } - function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 ? flags & 65536 ? + function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 ? facts & 33554432 ? ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); @@ -61973,9 +62914,9 @@ var ts; error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304; - if (kind) { - reportError(node, kind); + var facts = getTypeFacts(type); + if (facts & 50331648) { + reportError(node, facts); var t = getNonNullableType(type); return t.flags & (98304 | 131072) ? errorType : t; } @@ -62136,9 +63077,8 @@ var ts; markAliasReferenced(parentSymbol, node); } return isErrorType(apparentType) ? errorType : apparentType; - ; } - prop = getPropertyOfType(apparentType, right.escapedText); + prop = getPropertyOfType(apparentType, right.escapedText, false, node.kind === 161); } if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 && node.parent.kind === 299)) || @@ -62242,7 +63182,7 @@ var ts; assumeUninitialized = true; } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 32768) && getFalsyFlags(flowType) & 32768) { + if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) { error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); return propType; } @@ -62420,9 +63360,9 @@ var ts; function getSuggestedSymbolForNonexistentProperty(name, containingType) { var props = getPropertiesOfType(containingType); if (typeof name !== "string") { - var parent_2 = name.parent; - if (ts.isPropertyAccessExpression(parent_2)) { - props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + var parent_3 = name.parent; + if (ts.isPropertyAccessExpression(parent_3)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_3, containingType, prop); }); } name = ts.idText(name); } @@ -62828,18 +63768,22 @@ var ts; return inferJsxTypeArguments(node, signature, checkMode, context); } if (node.kind !== 165) { - var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 : 0); + var skipBindingPatterns = ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }); + var contextualType = getContextualType(node, skipBindingPatterns ? 8 : 0); if (contextualType) { var inferenceTargetType = getReturnTypeOfSignature(signature); if (couldContainTypeVariables(inferenceTargetType)) { var outerContext = getInferenceContext(node); - var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1)); - var instantiatedType = instantiateType(contextualType, outerMapper); - var contextualSignature = getSingleCallSignature(instantiatedType); - var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : - instantiatedType; - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128); + var isFromBindingPattern = !skipBindingPatterns && getContextualType(node, 8) !== contextualType; + if (!isFromBindingPattern) { + var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1)); + var instantiatedType = instantiateType(contextualType, outerMapper); + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128); + } var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags); var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper); inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType); @@ -63133,7 +64077,7 @@ var ts; var spreadIndex = getSpreadArgumentIndex(args); if (spreadIndex >= 0) { var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_24 = function (i) { + var _loop_26 = function (i) { var arg = args[i]; var spreadType = arg.kind === 225 && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { @@ -63149,7 +64093,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_24(i); + _loop_26(i); } return effectiveArgs_1; } @@ -63335,7 +64279,7 @@ var ts; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray; var typeArguments; - if (!isDecorator) { + if (!isDecorator && !ts.isSuperCall(node)) { typeArguments = node.typeArguments; if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 106) { ts.forEach(typeArguments, checkSourceElement); @@ -63367,6 +64311,8 @@ var ts; if (result) { return result; } + result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + getNodeLinks(node).resolvedSignature = result; if (reportErrors) { if (candidatesForArgumentError) { if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) { @@ -63397,7 +64343,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_25 = 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) { @@ -63415,7 +64361,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_25(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"); @@ -63452,7 +64398,7 @@ var ts; } } } - return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + return result; function addImplementationSuccessElaboration(failed, diagnostic) { var _a, _b; var oldCandidatesForArgumentError = candidatesForArgumentError; @@ -63526,7 +64472,7 @@ var ts; argCheckMode = checkMode & 32; if (inferenceContext) { var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters); if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { candidateForArgumentArityError = checkCandidate; continue; @@ -63558,7 +64504,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_26 = 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; }); @@ -63566,7 +64512,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_26(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0; @@ -63842,8 +64788,8 @@ var ts; if (apparentType.flags & 1048576) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var constituent = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var constituent = types_19[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -63993,7 +64939,7 @@ var ts; var exports = namespace && getExportsOfSymbol(namespace); var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968); var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968, node); - var declaration = ts.factory.createFunctionTypeNode(undefined, [ts.factory.createParameterDeclaration(undefined, undefined, undefined, "props", undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, undefined) : ts.factory.createKeywordTypeNode(130)); + var declaration = ts.factory.createFunctionTypeNode(undefined, [ts.factory.createParameterDeclaration(undefined, undefined, "props", undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, undefined) : ts.factory.createKeywordTypeNode(130)); var parameterSymbol = createSymbol(1, "props"); parameterSymbol.type = result; return createSignature(declaration, undefined, undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, undefined, 1, 0); @@ -64165,7 +65111,7 @@ var ts; checkGrammarTypeArguments(node, node.typeArguments); var signature = getResolvedSignature(node, undefined, checkMode); if (signature === resolvingSignature) { - return nonInferrableType; + return silentNeverType; } checkDeprecatedSignature(signature, node); if (node.expression.kind === 106) { @@ -64755,13 +65701,6 @@ var ts; } } } - var restType = getEffectiveRestType(context); - if (restType && restType.flags & 262144) { - var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper); - assignContextualParameterTypes(signature, instantiatedContext); - var restPos = getParameterCount(context) - 1; - inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType); - } } function assignContextualParameterTypes(signature, context) { if (context.typeParameters) { @@ -64934,7 +65873,7 @@ var ts; var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : - instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); + instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func, undefined); if (isGenerator) { yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0, isAsync); returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1, isAsync); @@ -64997,7 +65936,7 @@ var ts; nextType = iterationTypes && iterationTypes.nextType; } else { - nextType = getContextualType(yieldExpression); + nextType = getContextualType(yieldExpression, undefined); } if (nextType) ts.pushIfUnique(nextTypes, nextType); @@ -65011,26 +65950,11 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) { var facts = 0; - if (hasDefault) { - for (var i = end; i < witnesses.length; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768; - } - for (var i = start; i < end; i++) { - facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); - } - for (var i = 0; i < start; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768; - } - } - else { - for (var i = start; i < end; i++) { - facts |= typeofEQFacts.get(witnesses[i]) || 128; - } - for (var i = 0; i < start; i++) { - facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); - } + for (var i = 0; i < witnesses.length; i++) { + var witness = i < start || i >= end ? witnesses[i] : undefined; + facts |= witness !== undefined ? typeofNEFacts.get(witness) || 32768 : 0; } return facts; } @@ -65040,14 +65964,16 @@ var ts; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 216) { - var operandType = getTypeOfExpression(node.expression.expression); - var witnesses = getSwitchClauseTypeOfWitnesses(node, false); - var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, true); - var type_6 = getBaseConstraintOfType(operandType) || operandType; - if (type_6.flags & 3) { - return (556800 & notEqualFacts_1) === 556800; + var witnesses = getSwitchClauseTypeOfWitnesses(node); + if (!witnesses) { + return false; + } + var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(node.expression.expression)); + var notEqualFacts_2 = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); + if (operandConstraint.flags & 3) { + return (556800 & notEqualFacts_2) === 556800; } - return !!(filterType(type_6, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072); + return !someType(operandConstraint, function (t) { return (getTypeFacts(t) & notEqualFacts_2) === notEqualFacts_2; }); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -65183,11 +66109,16 @@ var ts; if (isContextSensitive(node)) { if (contextualSignature) { var inferenceContext = getInferenceContext(node); + var instantiatedContextualSignature = void 0; if (checkMode && checkMode & 2) { inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); + var restType = getEffectiveRestType(contextualSignature); + if (restType && restType.flags & 262144) { + instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper); + } } - var instantiatedContextualSignature = inferenceContext ? - instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature; + instantiatedContextualSignature || (instantiatedContextualSignature = inferenceContext ? + instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature); assignContextualParameterTypes(signature, instantiatedContextualSignature); } else { @@ -65351,7 +66282,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks && !(type.flags & (3 | 131072)) && - !(exactOptionalPropertyTypes ? symbol.flags & 16777216 : getFalsyFlags(type) & 32768)) { + !(exactOptionalPropertyTypes ? symbol.flags & 16777216 : getTypeFacts(type) & 16777216)) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); } } @@ -65456,7 +66387,7 @@ var ts; error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } if (node.operator === 39) { - if (maybeTypeOfKind(operandType, 2112)) { + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112)) { error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType))); } return numberType; @@ -65510,8 +66441,8 @@ var ts; } if (type.flags & 3145728) { var types = type.types; - for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { - var t = types_21[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var t = types_20[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -65701,7 +66632,7 @@ var ts; var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768)) { + !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & 16777216)) { sourceType = getTypeWithFacts(sourceType, 524288); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -65714,6 +66645,9 @@ var ts; if (target.kind === 221 && target.operatorToken.kind === 63) { checkBinaryExpression(target, checkMode); target = target.left; + if (strictNullChecks) { + sourceType = getTypeWithFacts(sourceType, 524288); + } } if (target.kind === 205) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); @@ -65843,7 +66777,11 @@ var ts; var operator = operatorToken.kind; if (operator === 55 || operator === 56 || operator === 60) { if (operator === 55) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); + var parent = node.parent; + while (parent.kind === 212 + || ts.isBinaryExpression(parent) && (parent.operatorToken.kind === 55 || parent.operatorToken.kind === 56)) { + parent = parent.parent; + } checkTestingKnownTruthyCallableOrAwaitableType(node.left, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } checkTruthinessOfType(leftType, node.left); @@ -66043,6 +66981,10 @@ var ts; case 35: case 36: case 37: + if (ts.isLiteralExpressionOfObject(left) || ts.isLiteralExpressionOfObject(right)) { + var eqType = operator === 34 || operator === 36; + error(errorNode, ts.Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); + } reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); }); return booleanType; case 102: @@ -66062,7 +67004,7 @@ var ts; case 56: case 75: { var resultType_3 = getTypeFacts(leftType) & 8388608 ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2) : + getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2) : leftType; if (operator === 75) { checkAssignmentOperator(rightType); @@ -66295,7 +67237,7 @@ var ts; type = anyType; addLazyDiagnostic(function () { if (noImplicitAny && !ts.expressionResultIsUnused(node)) { - var contextualType = getContextualType(node); + var contextualType = getContextualType(node, undefined); if (!contextualType || isTypeAny(contextualType)) { error(node, ts.Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); } @@ -66336,7 +67278,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node, undefined) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; } function isTemplateLiteralContextualType(type) { return !!(type.flags & (128 | 134217728) || @@ -66359,7 +67301,7 @@ var ts; if (inferenceContext && inferenceContext.intraExpressionInferenceSites) { inferenceContext.intraExpressionInferenceSites = undefined; } - var result = maybeTypeOfKind(type, 2944) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node, undefined)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -66463,7 +67405,7 @@ var ts; var type = checkExpression(node, checkMode, forceTuple); return isConstContext(node) || ts.isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : - getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node)); + getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node, undefined) : contextualType, node, undefined)); } function checkPropertyAssignment(node, checkMode) { if (node.name.kind === 162) { @@ -66549,8 +67491,8 @@ var ts; var result = []; var oldTypeParameters; var newTypeParameters; - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var tp = typeParameters_2[_i]; + for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { + var tp = typeParameters_3[_i]; var name = tp.symbol.escapedName; if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) { var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name); @@ -66843,12 +67785,14 @@ var ts; error(node, ts.Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); } else if (modifiers === 32768 || modifiers === 65536) { - var source = createMarkerType(symbol, typeParameter, modifiers === 65536 ? markerSubType : markerSuperType); - var target = createMarkerType(symbol, typeParameter, modifiers === 65536 ? markerSuperType : markerSubType); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes", "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); + var source = createMarkerType(symbol, typeParameter, modifiers === 65536 ? markerSubTypeForCheck : markerSuperTypeForCheck); + var target = createMarkerType(symbol, typeParameter, modifiers === 65536 ? markerSuperTypeForCheck : markerSubTypeForCheck); var saveVarianceTypeParameter = typeParameter; varianceTypeParameter = typeParameter; checkTypeAssignableTo(source, target, node, ts.Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation); varianceTypeParameter = saveVarianceTypeParameter; + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } } @@ -66865,7 +67809,7 @@ var ts; error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + if ((node.questionToken || isJSDocOptionalParameter(node)) && ts.isBindingPattern(node.name) && func.body) { error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { @@ -67158,7 +68102,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_27 = 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)); @@ -67173,7 +68117,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_27(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -67203,6 +68147,9 @@ var ts; function checkMethodDeclaration(node) { if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); + if (ts.isMethodDeclaration(node) && node.asteriskToken && ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_a_generator); + } checkFunctionOrMethodDeclaration(node); if (ts.hasSyntacticModifier(node, 128) && node.kind === 169 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); @@ -67308,6 +68255,9 @@ var ts; return !!ts.forEachChild(node, nodeImmediatelyReferencesSuperOrThis); } function checkAccessorDeclaration(node) { + if (ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_an_accessor); + } addLazyDiagnostic(checkAccessorDeclarationDiagnostics); checkSourceElement(node.body); setNodeLinksForPrivateIdentifierScope(node); @@ -67359,6 +68309,12 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) { + if (index < typeParameters.length) { + return getTypeFromTypeNode(node.typeArguments[index]); + } + return getEffectiveTypeArguments(node, typeParameters)[index]; + } function getEffectiveTypeArguments(node, typeParameters) { return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } @@ -67596,8 +68552,11 @@ var ts; if (node.assertions) { var override = ts.getResolutionModeOverrideForClause(node.assertions.assertClause, grammarErrorOnNode); if (override) { + if (!ts.isNightly()) { + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } } } @@ -67927,7 +68886,7 @@ var ts; var promisedType = getPromisedTypeOfPromise(type, errorNode); return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0); } - function getPromisedTypeOfPromise(type, errorNode) { + function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) { if (isTypeAny(type)) { return undefined; } @@ -67952,7 +68911,29 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152); + var thisTypeForError; + var candidates; + for (var _i = 0, thenSignatures_1 = thenSignatures; _i < thenSignatures_1.length; _i++) { + var thenSignature = thenSignatures_1[_i]; + var thisType = getThisTypeOfSignature(thenSignature); + if (thisType && thisType !== voidType && !isTypeRelatedTo(type, thisType, subtypeRelation)) { + thisTypeForError = thisType; + } + else { + candidates = ts.append(candidates, thenSignature); + } + } + if (!candidates) { + ts.Debug.assertIsDefined(thisTypeForError); + if (thisTypeForErrorOut) { + thisTypeForErrorOut.value = thisTypeForError; + } + if (errorNode) { + error(errorNode, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError)); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(candidates, getTypeOfFirstParameterOfSignature)), 2097152); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -67991,20 +68972,32 @@ var ts; isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : type; } - function createAwaitedTypeIfNeeded(type) { - if (isTypeAny(type)) { - return type; - } - if (isAwaitedTypeInstantiation(type)) { - return type; + function isAwaitedTypeNeeded(type) { + if (isTypeAny(type) || isAwaitedTypeInstantiation(type)) { + return false; } if (isGenericObjectType(type)) { var baseConstraint = getBaseConstraintOfType(type); - if (!baseConstraint || (baseConstraint.flags & 3) || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint)) { - var awaitedSymbol = getGlobalAwaitedSymbol(true); - if (awaitedSymbol) { - return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); - } + if (baseConstraint ? + baseConstraint.flags & 3 || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint) : + maybeTypeOfKind(type, 8650752)) { + return true; + } + } + return false; + } + function tryCreateAwaitedType(type) { + var awaitedSymbol = getGlobalAwaitedSymbol(true); + if (awaitedSymbol) { + return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); + } + return undefined; + } + function createAwaitedTypeIfNeeded(type) { + if (isAwaitedTypeNeeded(type)) { + var awaitedType = tryCreateAwaitedType(type); + if (awaitedType) { + return awaitedType; } } ts.Debug.assert(getPromisedTypeOfPromise(type) === undefined, "type provided should not be a non-generic 'promise'-like."); @@ -68026,10 +69019,23 @@ var ts; return typeAsAwaitable.awaitedTypeOfType; } if (type.flags & 1048576) { + if (awaitedTypeStack.lastIndexOf(type.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } var mapper = errorNode ? function (constituentType) { return getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeNoAlias; - return typeAsAwaitable.awaitedTypeOfType = mapType(type, mapper); + awaitedTypeStack.push(type.id); + var mapped = mapType(type, mapper); + awaitedTypeStack.pop(); + return typeAsAwaitable.awaitedTypeOfType = mapped; + } + if (isAwaitedTypeNeeded(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; } - var promisedType = getPromisedTypeOfPromise(type); + var thisTypeForErrorOut = { value: undefined }; + var promisedType = getPromisedTypeOfPromise(type, undefined, thisTypeForErrorOut); if (promisedType) { if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { if (errorNode) { @@ -68048,7 +69054,12 @@ var ts; if (isThenableType(type)) { if (errorNode) { ts.Debug.assertIsDefined(diagnosticMessage); - error(errorNode, diagnosticMessage, arg0); + var chain = void 0; + if (thisTypeForErrorOut.value) { + chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value)); + } + chain = ts.chainDiagnosticMessages(chain, diagnosticMessage, arg0); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, chain)); } return undefined; } @@ -68190,8 +69201,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { - var typeNode = types_22[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 191 || typeNode.kind === 197) { typeNode = typeNode.type; } @@ -68223,16 +69234,16 @@ var ts; return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; } function checkDecorators(node) { - if (!node.decorators) { - return; - } - if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node) || !node.modifiers || !ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning); } - var firstDecorator = node.decorators[0]; + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (!firstDecorator) { + return; + } checkExternalEmitHelpers(firstDecorator, 8); if (node.kind === 164) { checkExternalEmitHelpers(firstDecorator, 32); @@ -68275,7 +69286,12 @@ var ts; break; } } - ts.forEach(node.decorators, checkDecorator); + for (var _f = 0, _g = node.modifiers; _f < _g.length; _f++) { + var modifier = _g[_f]; + if (ts.isDecorator(modifier)) { + checkDecorator(modifier); + } + } } function checkFunctionDeclaration(node) { addLazyDiagnostic(checkFunctionDeclarationDiagnostics); @@ -68305,6 +69321,11 @@ var ts; function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } + function checkJSDocLinkLikeTag(node) { + if (node.name) { + resolveJSDocMemberName(node.name, true); + } + } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); } @@ -68516,8 +69537,8 @@ var ts; return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); - for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { - var typeParameter = typeParameters_3[_i]; + for (var _i = 0, typeParameters_4 = typeParameters; _i < typeParameters_4.length; _i++) { + var typeParameter = typeParameters_4[_i]; if (!isTypeParameterUnused(typeParameter)) continue; var name = ts.idText(typeParameter.name); @@ -68665,6 +69686,21 @@ var ts; } }); } + function checkPotentialUncheckedRenamedBindingElementsInTypes() { + var _a; + for (var _i = 0, potentialUnusedRenamedBindingElementsInTypes_1 = potentialUnusedRenamedBindingElementsInTypes; _i < potentialUnusedRenamedBindingElementsInTypes_1.length; _i++) { + var node = potentialUnusedRenamedBindingElementsInTypes_1[_i]; + if (!((_a = getSymbolOfNode(node)) === null || _a === void 0 ? void 0 : _a.isReferenced)) { + var wrappingDeclaration = ts.walkUpBindingElementsAndPatterns(node); + ts.Debug.assert(ts.isParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here"); + var diagnostic = ts.createDiagnosticForNode(node.name, ts.Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, ts.declarationNameToString(node.name), ts.declarationNameToString(node.propertyName)); + if (!wrappingDeclaration.type) { + ts.addRelatedInfo(diagnostic, ts.createFileDiagnostic(ts.getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, ts.Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, ts.declarationNameToString(node.propertyName))); + } + diagnostics.add(diagnostic); + } + } + } function bindingNameText(name) { switch (name.kind) { case 79: @@ -68902,11 +69938,18 @@ var ts; } if (node.name.kind === 162) { checkComputedPropertyName(node.name); - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkExpressionCached(node.initializer); } } if (ts.isBindingElement(node)) { + if (node.propertyName && + ts.isIdentifier(node.name) && + ts.isParameterDeclaration(node) && + ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + potentialUnusedRenamedBindingElementsInTypes.push(node); + return; + } if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5) { checkExternalEmitHelpers(node, 4); } @@ -68935,13 +69978,13 @@ var ts; } ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (ts.isParameter(node) && node.initializer && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 243; - var needCheckWidenedType = node.name.elements.length === 0; + var needCheckInitializer = ts.hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 243; + var needCheckWidenedType = !ts.some(node.name.elements, ts.not(ts.isOmittedExpression)); if (needCheckInitializer || needCheckWidenedType) { var widenedType = getWidenedTypeForVariableLikeDeclaration(node); if (needCheckInitializer) { @@ -68965,13 +70008,13 @@ var ts; return; } var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node)) { + if (symbol.flags & 2097152 && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.kind === 203 ? node.parent.parent : node)) { checkAliasSymbol(node); return; } var type = convertAutoToAny(getTypeOfSymbol(symbol)); if (node === symbol.valueDeclaration) { - var initializer = ts.getEffectiveInitializer(node); + var initializer = ts.hasOnlyExpressionInitializer(node) && ts.getEffectiveInitializer(node); if (initializer) { var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && @@ -68994,7 +70037,7 @@ var ts; !(symbol.flags & 67108864)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); } - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, undefined); } if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { @@ -69082,7 +70125,7 @@ var ts; return; var type = checkTruthinessExpression(location); var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) && isTypeAssertion(location.expression); - if (getFalsyFlags(type) || isPropertyExpressionCast) + if (!(getTypeFacts(type) & 4194304) || isPropertyExpressionCast) return; var callSignatures = getSignaturesOfType(type, 0); var isPromise = !!getAwaitedTypeOfPromise(type); @@ -69448,17 +70491,28 @@ var ts; return type[cacheKey] = cachedTypes; } function getIterationTypesOfIterable(type, use, errorNode) { + var _a, _b; if (isTypeAny(type)) { return anyIterationTypes; } if (!(type.flags & 1048576)) { - var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode); + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); if (iterationTypes_1 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } return undefined; } + else if ((_a = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _a === void 0 ? void 0 : _a.length) { + for (var _i = 0, _c = errorOutputContainer.errors; _i < _c.length; _i++) { + var diag = _c[_i]; + diagnostics.add(diag); + } + } return iterationTypes_1; } var cacheKey = use & 2 ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; @@ -69466,19 +70520,27 @@ var ts; if (cachedTypes) return cachedTypes === noIterationTypes ? undefined : cachedTypes; var allIterationTypes; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituent = _a[_i]; - var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode); + for (var _d = 0, _e = type.types; _d < _e.length; _d++) { + var constituent = _e[_d]; + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer); if (iterationTypes_2 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } setCachedIterationTypes(type, cacheKey, noIterationTypes); return undefined; } - else { - allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); + else if ((_b = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _b === void 0 ? void 0 : _b.length) { + for (var _f = 0, _g = errorOutputContainer.errors; _f < _g.length; _f++) { + var diag = _g[_f]; + diagnostics.add(diag); + } } + allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); } var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes; setCachedIterationTypes(type, cacheKey, iterationTypes); @@ -69495,46 +70557,57 @@ var ts; } return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType); } - function getIterationTypesOfIterableWorker(type, use, errorNode) { + function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) { if (isTypeAny(type)) { return anyIterationTypes; } + var noCache = false; if (use & 2) { var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver); if (iterationTypes) { - return use & 8 ? - getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : - iterationTypes; + if (iterationTypes === noIterationTypes && errorNode) { + noCache = true; + } + else { + return use & 8 ? + getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : + iterationTypes; + } } } if (use & 1) { var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver); if (iterationTypes) { - if (use & 2) { - if (iterationTypes !== noIterationTypes) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode)); - } + if (iterationTypes === noIterationTypes && errorNode) { + noCache = true; } else { - return iterationTypes; + if (use & 2) { + if (iterationTypes !== noIterationTypes) { + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); + } + } + else { + return iterationTypes; + } } } } if (use & 2) { - var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { return iterationTypes; } } if (use & 1) { - var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { if (use & 2) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes - ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) - : noIterationTypes); + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); } else { return iterationTypes; @@ -69548,7 +70621,7 @@ var ts; } function getIterationTypesOfGlobalIterableType(globalType, resolver) { var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || - getIterationTypesOfIterableSlow(globalType, resolver, undefined); + getIterationTypesOfIterableSlow(globalType, resolver, undefined, undefined, false); return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; } function getIterationTypesOfIterableFast(type, resolver) { @@ -69569,34 +70642,41 @@ var ts; var uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), ts.escapeLeadingUnderscores(symbolName)); return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : "__@".concat(symbolName); } - function getIterationTypesOfIterableSlow(type, resolver, errorNode) { + function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var _a; var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); + return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); } var signatures = methodType ? getSignaturesOfType(methodType, 0) : undefined; if (!ts.some(signatures)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); + return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); } var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature)); - var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes; - return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); + var iterationTypes = (_a = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache)) !== null && _a !== void 0 ? _a : noIterationTypes; + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { 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; - errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); } - function getIterationTypesOfIterator(type, resolver, errorNode) { + function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { + return getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, false); + } + function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) { if (isTypeAny(type)) { return anyIterationTypes; } var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || - getIterationTypesOfIteratorFast(type, resolver) || - getIterationTypesOfIteratorSlow(type, resolver, errorNode); + getIterationTypesOfIteratorFast(type, resolver); + if (iterationTypes === noIterationTypes && errorNode) { + iterationTypes = undefined; + noCache = true; + } + iterationTypes !== null && iterationTypes !== void 0 ? iterationTypes : (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache)); return iterationTypes === noIterationTypes ? undefined : iterationTypes; } function getIterationTypesOfIteratorCached(type, resolver) { @@ -69607,7 +70687,7 @@ var ts; if (isReferenceToType(type, globalType)) { var yieldType = getTypeArguments(type)[0]; var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || - getIterationTypesOfIteratorSlow(globalType, resolver, undefined); + getIterationTypesOfIteratorSlow(globalType, resolver, undefined, undefined, false); var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType; return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } @@ -69652,8 +70732,8 @@ var ts; } return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, undefined)); } - function getIterationTypesOfMethod(type, resolver, methodName, errorNode) { - var _a, _b, _c, _d; + function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) { + var _a, _b, _c, _d, _e, _f; var method = getPropertyOfType(type, methodName); if (!method && methodName !== "next") { return undefined; @@ -69670,15 +70750,21 @@ var ts; var diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic; - error(errorNode, diagnostic, methodName); + if (errorOutputContainer) { + (_a = errorOutputContainer.errors) !== null && _a !== void 0 ? _a : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, diagnostic, methodName)); + } + else { + error(errorNode, diagnostic, methodName); + } } - return methodName === "next" ? anyIterationTypes : undefined; + return methodName === "next" ? noIterationTypes : undefined; } if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) { var globalGeneratorType = resolver.getGlobalGeneratorType(false); var globalIteratorType = resolver.getGlobalIteratorType(false); - var isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) === null || _a === void 0 ? void 0 : _a.members) === null || _b === void 0 ? void 0 : _b.get(methodName)) === methodType.symbol; - var isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) === null || _c === void 0 ? void 0 : _c.members) === null || _d === void 0 ? void 0 : _d.get(methodName)) === methodType.symbol; + var isGeneratorMethod = ((_c = (_b = globalGeneratorType.symbol) === null || _b === void 0 ? void 0 : _b.members) === null || _c === void 0 ? void 0 : _c.get(methodName)) === methodType.symbol; + var isIteratorMethod = !isGeneratorMethod && ((_e = (_d = globalIteratorType.symbol) === null || _d === void 0 ? void 0 : _d.members) === null || _e === void 0 ? void 0 : _e.get(methodName)) === methodType.symbol; if (isGeneratorMethod || isIteratorMethod) { var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType; var mapper = methodType.mapper; @@ -69712,7 +70798,13 @@ var ts; var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType); if (iterationTypes === noIterationTypes) { if (errorNode) { - error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + if (errorOutputContainer) { + (_f = errorOutputContainer.errors) !== null && _f !== void 0 ? _f : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName)); + } + else { + error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + } } yieldType = anyType; returnTypes = ts.append(returnTypes, anyType); @@ -69723,13 +70815,13 @@ var ts; } return createIterationTypes(yieldType, getUnionType(returnTypes), nextType); } - function getIterationTypesOfIteratorSlow(type, resolver, errorNode) { + function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var iterationTypes = combineIterationTypes([ - getIterationTypesOfMethod(type, resolver, "next", errorNode), - getIterationTypesOfMethod(type, resolver, "return", errorNode), - getIterationTypesOfMethod(type, resolver, "throw", errorNode), + getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer), ]); - return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); } function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) { if (isTypeAny(returnType)) { @@ -69745,7 +70837,7 @@ var ts; var use = isAsyncGenerator ? 2 : 1; var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; return getIterationTypesOfIterable(type, use, undefined) || - getIterationTypesOfIterator(type, resolver, undefined); + getIterationTypesOfIterator(type, resolver, undefined, undefined); } function checkBreakOrContinueStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) @@ -69754,9 +70846,14 @@ var ts; function unwrapReturnType(returnType, functionFlags) { var isGenerator = !!(functionFlags & 1); var isAsync = !!(functionFlags & 2); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1, returnType, isAsync) || errorType : - isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : - returnType; + if (isGenerator) { + var returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1, returnType, isAsync); + if (!returnIterationType) { + return errorType; + } + return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType; + } + return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func)); @@ -69957,19 +71054,24 @@ var ts; } var indexInfos = getApplicableIndexInfos(type, propNameType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 ? ts.getDeclarationOfKind(type.symbol, 258) : undefined; - var localPropDeclaration = declaration && declaration.kind === 221 || - name && name.kind === 162 || getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_28 = function (info) { + var propDeclaration = declaration && declaration.kind === 221 || + name && name.kind === 162 ? declaration : undefined; + var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; + 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); if (errorNode && !isTypeAssignableTo(propType, info.type)) { - error(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + var diagnostic = createError(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + if (propDeclaration && errorNode !== propDeclaration) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(propDeclaration, ts.Diagnostics._0_is_declared_here, symbolToString(prop))); + } + diagnostics.add(diagnostic); } }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_28(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -69977,7 +71079,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 ? ts.getDeclarationOfKind(type.symbol, 258) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_29 = 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; @@ -69989,7 +71091,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_29(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -70158,8 +71260,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { - grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (firstDecorator && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(firstDecorator, ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); } if (!node.name && !ts.hasSyntacticModifier(node, 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -70283,7 +71386,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_30 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -70298,7 +71401,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_30(member); + _loop_32(member); } } function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors) { @@ -70373,7 +71476,7 @@ var ts; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_31 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -70391,7 +71494,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_31(member); + _loop_33(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -70436,17 +71539,16 @@ var ts; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { - var _a, _b; + var _a, _b, _c, _d; var baseProperties = getPropertiesOfType(baseType); - basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304) { - continue; + return "continue"; } var baseSymbol = getPropertyOfObjectType(type, base.escapedName); if (!baseSymbol) { - continue; + return "continue"; } var derived = getTargetSymbol(baseSymbol); var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); @@ -70454,14 +71556,14 @@ var ts; if (derived === base) { var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !ts.hasSyntacticModifier(derivedClassDecl, 128))) { - for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { - var otherBaseType = _d[_c]; + for (var _e = 0, _f = getBaseTypes(type); _e < _f.length; _e++) { + var otherBaseType = _f[_e]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1); if (derivedElsewhere && derivedElsewhere !== base) { - continue basePropertyCheck; + return "continue-basePropertyCheck"; } } if (derivedClassDecl.kind === 226) { @@ -70475,16 +71577,18 @@ var ts; else { var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { - continue; + return "continue"; } var errorMessage = void 0; var basePropertyFlags = base.flags & 98308; var derivedPropertyFlags = derived.flags & 98308; if (basePropertyFlags && derivedPropertyFlags) { - if (baseDeclarationFlags & 128 && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 258 + if ((ts.getCheckFlags(base) & 6 + ? (_a = base.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); }) + : (_b = base.declarations) === null || _b === void 0 ? void 0 : _b.every(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); })) + || ts.getCheckFlags(base) & 262144 || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { - continue; + return "continue"; } var overriddenInstanceProperty = basePropertyFlags !== 4 && derivedPropertyFlags === 4; var overriddenInstanceAccessor = basePropertyFlags === 4 && derivedPropertyFlags !== 4; @@ -70495,12 +71599,12 @@ var ts; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { - var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 167 && !d.initializer; }); + var uninitialized = (_c = derived.declarations) === null || _c === void 0 ? void 0 : _c.find(function (d) { return d.kind === 167 && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432) && !(baseDeclarationFlags & 128) && !(derivedDeclarationFlags & 128) - && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 16777216); }))) { + && !((_d = derived.declarations) === null || _d === void 0 ? void 0 : _d.some(function (d) { return !!(d.flags & 16777216); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -70513,11 +71617,11 @@ var ts; } } } - continue; + return "continue"; } else if (isPrototypeProperty(base)) { if (isPrototypeProperty(derived) || derived.flags & 4) { - continue; + return "continue"; } else { ts.Debug.assert(!!(derived.flags & 98304)); @@ -70532,9 +71636,20 @@ var ts; } error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } + }; + basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var state_10 = _loop_34(baseProperty); + switch (state_10) { + case "continue-basePropertyCheck": continue basePropertyCheck; + } } } - function getNonInterhitedProperties(type, baseTypes, properties) { + function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { + return baseDeclarationFlags & 128 && (!ts.isPropertyDeclaration(declaration) || !declaration.initializer) + || ts.isInterfaceDeclaration(declaration.parent); + } + function getNonInheritedProperties(type, baseTypes, properties) { if (!ts.length(baseTypes)) { return properties; } @@ -70603,7 +71718,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName) || ts.isComputedPropertyName(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 || getFalsyFlags(type) & 32768)) { + if (!(type.flags & 3 || containsUndefinedType(type))) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -70627,7 +71742,7 @@ var ts; ts.setParent(reference, staticBlock); reference.flowNode = staticBlock.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - if (!(getFalsyFlags(flowType) & 32768)) { + if (!containsUndefinedType(flowType)) { return true; } } @@ -70642,7 +71757,7 @@ var ts; ts.setParent(reference, constructor); reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 32768); + return !containsUndefinedType(flowType); } function checkInterfaceDeclaration(node) { if (!checkGrammarDecoratorsAndModifiers(node)) @@ -71111,10 +72226,35 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a, _b, _c, _d, _e; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { symbol = getMergedSymbol(symbol.exportSymbol || symbol); + if (ts.isInJSFile(node) && !(target.flags & 111551) && !ts.isTypeOnlyImportOrExportDeclaration(node)) { + var errorNode = ts.isImportOrExportSpecifier(node) ? node.propertyName || node.name : + ts.isNamedDeclaration(node) ? node.name : + node; + ts.Debug.assert(node.kind !== 274); + if (node.kind === 275) { + var diag = error(errorNode, ts.Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); + var alreadyExportedSymbol = (_b = (_a = ts.getSourceFileOfNode(node).symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.get((node.propertyName || node.name).escapedText); + if (alreadyExportedSymbol === target) { + var exportingDeclaration = (_c = alreadyExportedSymbol.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isJSDocNode); + if (exportingDeclaration) { + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(exportingDeclaration, ts.Diagnostics._0_is_automatically_exported_here, ts.unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName))); + } + } + } + else { + ts.Debug.assert(node.kind !== 254); + var importDeclaration = ts.findAncestor(node, ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration)); + var moduleSpecifier = (_e = (importDeclaration && ((_d = ts.tryGetModuleSpecifierFromDeclaration(importDeclaration)) === null || _d === void 0 ? void 0 : _d.text))) !== null && _e !== void 0 ? _e : "..."; + var importedIdentifier = ts.unescapeLeadingUnderscores(ts.isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); + error(errorNode, ts.Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, "import(\"".concat(moduleSpecifier, "\").").concat(importedIdentifier)); + } + return; + } var excludedMeanings = (symbol.flags & (111551 | 1048576) ? 111551 : 0) | (symbol.flags & 788968 ? 788968 : 0) | (symbol.flags & 1920 ? 1920 : 0); @@ -71217,10 +72357,10 @@ var ts; var override = ts.getResolutionModeOverrideForClause(declaration.assertClause, validForTypeAssertions ? grammarErrorOnNode : undefined); if (validForTypeAssertions && override) { if (!ts.isNightly()) { - grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } return; } @@ -71411,7 +72551,9 @@ var ts; error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { - markExportAsReferenced(node); + if (!node.isTypeOnly && !node.parent.parent.isTypeOnly) { + markExportAsReferenced(node); + } var target = symbol && (symbol.flags & 2097152 ? resolveAlias(symbol) : symbol); if (!target || target === unknownSymbol || target.flags & 111551) { checkExpressionCached(node.propertyName || node.name); @@ -71542,12 +72684,16 @@ var ts; } } function checkSourceElementWorker(node) { - if (ts.isInJSFile(node)) { - ts.forEach(node.jsDoc, function (_a) { - var tags = _a.tags; - return ts.forEach(tags, checkSourceElement); + ts.forEach(node.jsDoc, function (_a) { + var comment = _a.comment, tags = _a.tags; + checkJSDocCommentWorker(comment); + ts.forEach(tags, function (tag) { + checkJSDocCommentWorker(tag.comment); + if (ts.isInJSFile(node)) { + checkSourceElement(tag); + } }); - } + }); var kind = node.kind; if (cancellationToken) { switch (kind) { @@ -71631,6 +72777,10 @@ var ts; return checkJSDocTemplateTag(node); case 343: return checkJSDocTypeTag(node); + case 324: + case 325: + case 326: + return checkJSDocLinkLikeTag(node); case 340: return checkJSDocParameterTag(node); case 347: @@ -71724,6 +72874,15 @@ var ts; return checkMissingDeclaration(node); } } + function checkJSDocCommentWorker(node) { + if (ts.isArray(node)) { + ts.forEach(node, function (tag) { + if (ts.isJSDocLinkLike(tag)) { + checkSourceElement(tag); + } + }); + } + } function checkJSDocTypeIsInJsFile(node) { if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); @@ -71867,6 +73026,7 @@ var ts; ts.clear(potentialNewTargetCollisions); ts.clear(potentialWeakMapSetCollisions); ts.clear(potentialReflectCollisions); + ts.clear(potentialUnusedRenamedBindingElementsInTypes); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -71881,6 +73041,9 @@ var ts; } }); } + if (!node.isDeclarationFile) { + checkPotentialUncheckedRenamedBindingElementsInTypes(); + } }); if (compilerOptions.importsNotUsedAsValues === 2 && !node.isDeclarationFile && @@ -72207,7 +73370,7 @@ var ts; if (!result && isJSDoc_1) { var container = ts.findAncestor(name, ts.or(ts.isClassLike, ts.isInterfaceDeclaration)); if (container) { - return resolveJSDocMemberName(name, getSymbolOfNode(container)); + return resolveJSDocMemberName(name, false, getSymbolOfNode(container)); } } return result; @@ -72245,10 +73408,10 @@ var ts; } return undefined; } - function resolveJSDocMemberName(name, container) { + function resolveJSDocMemberName(name, ignoreErrors, container) { if (ts.isEntityName(name)) { var meaning = 788968 | 1920 | 111551; - var symbol = resolveEntityName(name, meaning, false, true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, ignoreErrors, true, ts.getHostSignatureFromJSDoc(name)); if (!symbol && ts.isIdentifier(name) && container) { symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning)); } @@ -72256,7 +73419,7 @@ var ts; return symbol; } } - var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left); + var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container); var right = ts.isIdentifier(name) ? name.escapedText : name.right.escapedText; if (left) { var proto = left.flags & 111551 && getPropertyOfType(getTypeOfSymbol(left), "prototype"); @@ -73122,10 +74285,16 @@ var ts; if (!fileToDirective) { return undefined; } - var meaning = 788968 | 1920; - if ((node.kind === 79 && isInTypeQuery(node)) || (node.kind === 206 && !isInHeritageClause(node))) { + var meaning; + if (node.parent.kind === 162) { meaning = 111551 | 1048576; } + else { + meaning = 788968 | 1920; + if ((node.kind === 79 && isInTypeQuery(node)) || (node.kind === 206 && !isInHeritageClause(node))) { + meaning = 111551 | 1048576; + } + } var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -73379,7 +74548,10 @@ var ts; return checkGrammarDecorators(node) || checkGrammarModifiers(node); } function checkGrammarDecorators(node) { - if (!node.decorators) { + if (ts.canHaveIllegalDecorators(node) && ts.some(node.illegalDecorators)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node)) { return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { @@ -73392,7 +74564,7 @@ var ts; } else if (node.kind === 172 || node.kind === 173) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + if (ts.hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } } @@ -73407,6 +74579,8 @@ var ts; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; if (modifier.kind !== 145) { if (node.kind === 166 || node.kind === 168) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); @@ -73686,6 +74860,13 @@ var ts; case 164: case 163: return false; + case 170: + case 296: + case 297: + case 264: + case 179: + case 276: + return true; default: if (node.parent.kind === 262 || node.parent.kind === 305) { return false; @@ -73696,20 +74877,26 @@ var ts; case 257: case 180: return nodeHasAnyModifiersExcept(node, 126); + case 226: case 258: case 237: case 259: - case 170: return true; case 260: return nodeHasAnyModifiersExcept(node, 85); default: - ts.Debug.fail(); + ts.Debug.assertNever(node); } } } function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; + return modifier.kind !== allowedModifier; + } + return false; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { @@ -73991,19 +75178,25 @@ var ts; if (name.kind === 80) { grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } - if (prop.modifiers) { + if (ts.canHaveModifiers(prop) && prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 131 || prop.kind !== 169) { + if (ts.isModifier(mod) && (mod.kind !== 131 || prop.kind !== 169)) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } + else if (ts.canHaveIllegalModifiers(prop) && prop.modifiers) { + for (var _d = 0, _e = prop.modifiers; _d < _e.length; _d++) { + var mod = _e[_d]; + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } var currentKind = void 0; switch (prop.kind) { case 297: - checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); case 296: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8) { checkGrammarNumericLiteral(name); @@ -74417,9 +75610,6 @@ var ts; else { return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (!isConstOrReadonly || isInvalidInitializer) { - return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } } } function checkGrammarVariableDeclaration(node) { @@ -74580,7 +75770,7 @@ var ts; } } function checkGrammarConstructorTypeAnnotation(node) { - var type = ts.getEffectiveReturnTypeNode(node); + var type = node.type || ts.getEffectiveReturnTypeNode(node); if (type) { return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } @@ -74604,6 +75794,7 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } @@ -74612,6 +75803,7 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } @@ -74933,7 +76125,6 @@ var ts; if (nodes === undefined || visitor === undefined) { return nodes; } - var updated; var length = nodes.length; if (start === undefined || start < 0) { start = 0; @@ -74945,18 +76136,48 @@ var ts; var pos = -1; var end = -1; if (start > 0 || count < length) { - updated = []; hasTrailingComma = nodes.hasTrailingComma && start + count === length; } + else { + pos = nodes.pos; + end = nodes.end; + hasTrailingComma = nodes.hasTrailingComma; + } + var updated = visitArrayWorker(nodes, visitor, test, start, count); + if (updated !== nodes) { + var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); + ts.setTextRangePosEnd(updatedArray, pos, end); + return updatedArray; + } + return nodes; + } + ts.visitNodes = visitNodes; + function visitArray(nodes, visitor, test, start, count) { + if (nodes === undefined) { + return nodes; + } + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + return visitArrayWorker(nodes, visitor, test, start, count); + } + ts.visitArray = visitArray; + function visitArrayWorker(nodes, visitor, test, start, count) { + var updated; + var length = nodes.length; + if (start > 0 || count < length) { + updated = []; + } for (var i = 0; i < count; i++) { var node = nodes[i + start]; var visited = node !== undefined ? visitor(node) : undefined; if (updated !== undefined || visited === undefined || visited !== node) { if (updated === undefined) { updated = nodes.slice(0, i); - hasTrailingComma = nodes.hasTrailingComma; - pos = nodes.pos; - end = nodes.end; } if (visited) { if (ts.isArray(visited)) { @@ -74973,14 +76194,8 @@ var ts; } } } - if (updated) { - var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); - ts.setTextRangePosEnd(updatedArray, pos, end); - return updatedArray; - } - return nodes; + return updated !== null && updated !== void 0 ? updated : nodes; } - ts.visitNodes = visitNodes; function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict, nodesVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } context.startLexicalEnvironment(); @@ -75036,14 +76251,14 @@ var ts; factory.createConditionalExpression(factory.createStrictEquality(factory.getGeneratedNameForNode(parameter), factory.createVoidZero()), undefined, parameter.initializer, undefined, factory.getGeneratedNameForNode(parameter)) : factory.getGeneratedNameForNode(parameter)), ]))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, undefined); + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, undefined); } function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { var factory = context.factory; context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([ factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(ts.setEmitFlags(factory.cloneNode(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer) | 1536)), parameter), 1536)) ]), parameter), 1 | 32 | 384 | 1536))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, undefined); + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, undefined); } function visitFunctionBody(node, visitor, context, nodeVisitor) { if (nodeVisitor === void 0) { nodeVisitor = visitNode; } @@ -75102,7 +76317,7 @@ var ts; return factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); case 164: ts.Debug.type(node); - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + return factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 165: ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -75111,27 +76326,27 @@ var ts; return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 167: ts.Debug.type(node); - return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + return factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 168: ts.Debug.type(node); return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 169: ts.Debug.type(node); - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 171: ts.Debug.type(node); - return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 172: ts.Debug.type(node); - return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 173: ts.Debug.type(node); - return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 170: ts.Debug.type(node); context.startLexicalEnvironment(); context.suspendLexicalEnvironment(); - return factory.updateClassStaticBlockDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 174: ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -75140,7 +76355,7 @@ var ts; return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 176: ts.Debug.type(node); - return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 177: ts.Debug.type(node); return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, ts.isAssertsKeyword), nodeVisitor(node.parameterName, visitor, ts.isIdentifierOrThisTypeNode), nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -75185,13 +76400,13 @@ var ts; return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); case 200: ts.Debug.type(node); - return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); case 295: ts.Debug.type(node); return factory.updateImportTypeAssertionContainer(node, nodeVisitor(node.assertClause, visitor, ts.isNode), node.multiLine); case 197: ts.Debug.type(node); - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + return factory.updateNamedTupleMember(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 191: ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -75254,7 +76469,7 @@ var ts; return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 210: ts.Debug.type(node); - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); case 211: ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -75302,7 +76517,7 @@ var ts; return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 226: ts.Debug.type(node); - return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 228: ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); @@ -75381,22 +76596,22 @@ var ts; return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 256: ts.Debug.type(node); - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 257: ts.Debug.type(node); - return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 258: ts.Debug.type(node); - return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + return factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 259: ts.Debug.type(node); - return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 260: ts.Debug.type(node); - return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + return factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 261: ts.Debug.type(node); - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + return factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); case 262: ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); @@ -75408,10 +76623,10 @@ var ts; return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); case 265: ts.Debug.type(node); - return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); + return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); case 266: ts.Debug.type(node); - return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 293: ts.Debug.type(node); return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); @@ -75435,10 +76650,10 @@ var ts; return factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); case 271: ts.Debug.type(node); - return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); + return factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); case 272: ts.Debug.type(node); - return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 273: ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); @@ -76418,6 +77633,92 @@ var ts; return !ts.isStatic(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); } ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; + if (decorators || ts.hasDecorators(parameter)) { + if (!decorators) { + decorators = new Array(numParameters); + } + decorators[i] = ts.getDecorators(parameter); + } + } + } + return decorators; + } + function getAllDecoratorsOfClass(node) { + var decorators = ts.getDecorators(node); + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + ts.getAllDecoratorsOfClass = getAllDecoratorsOfClass; + function getAllDecoratorsOfClassElement(member, parent) { + switch (member.kind) { + case 172: + case 173: + return getAllDecoratorsOfAccessors(member, parent); + case 169: + return getAllDecoratorsOfMethod(member); + case 167: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + ts.getAllDecoratorsOfClassElement = getAllDecoratorsOfClassElement; + function getAllDecoratorsOfAccessors(accessor, parent) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(parent.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = ts.hasDecorators(firstAccessor) ? firstAccessor : + secondAccessor && ts.hasDecorators(secondAccessor) ? secondAccessor : + undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = ts.getDecorators(firstAccessorWithDecorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters, + getDecorators: getAccessor && ts.getDecorators(getAccessor), + setDecorators: setAccessor && ts.getDecorators(setAccessor) + }; + } + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = ts.getDecorators(method); + var parameters = getDecoratorsOfParameters(method); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + function getAllDecoratorsOfProperty(property) { + var decorators = ts.getDecorators(property); + if (!ts.some(decorators)) { + return undefined; + } + return { decorators: decorators }; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -76619,8 +77920,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 - && !(element.transformFlags & (16384 | 32768)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 | 32768)) + && !(element.transformFlags & (32768 | 65536)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (32768 | 65536)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -76667,7 +77968,7 @@ var ts; for (var i = 0; i < numElements; i++) { var element = elements[i]; if (flattenContext.level >= 1) { - if (element.transformFlags & 32768 || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 65536 || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(undefined); if (flattenContext.hoistTempVariables) { @@ -76835,9 +78136,9 @@ var ts; var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); - var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var typeSerializer = compilerOptions.emitDecoratorMetadata ? ts.createRuntimeTypeSerializer(context) : undefined; var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; @@ -76848,11 +78149,9 @@ var ts; var currentNamespace; var currentNamespaceContainerName; var currentLexicalScope; - var currentNameScope; var currentScopeFirstDeclarationsOfName; var currentClassHasParameterProperties; var enabledSubstitutions; - var classAliases; var applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { @@ -76881,7 +78180,6 @@ var ts; } function saveStateAndInvoke(node, f) { var savedCurrentScope = currentLexicalScope; - var savedCurrentNameScope = currentNameScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties; onBeforeVisitNode(node); @@ -76890,7 +78188,6 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } currentLexicalScope = savedCurrentScope; - currentNameScope = savedCurrentNameScope; currentClassHasParameterProperties = savedCurrentClassHasParameterProperties; return visited; } @@ -76901,7 +78198,6 @@ var ts; case 262: case 235: currentLexicalScope = node; - currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; case 257: @@ -76915,9 +78211,6 @@ var ts; else { ts.Debug.assert(node.kind === 257 || ts.hasSyntacticModifier(node, 512)); } - if (ts.isClassDeclaration(node)) { - currentNameScope = node; - } break; } } @@ -76981,28 +78274,53 @@ var ts; } return node; } - function classElementVisitor(node) { - return saveStateAndInvoke(node, classElementVisitorWorker); + function getClassElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return classElementVisitorWorker(n, parent); }); }; } - function classElementVisitorWorker(node) { + function classElementVisitorWorker(node, parent) { switch (node.kind) { case 171: return visitConstructor(node); case 167: - return visitPropertyDeclaration(node); - case 176: + return visitPropertyDeclaration(node, parent); case 172: + return visitGetAccessor(node, parent); case 173: + return visitSetAccessor(node, parent); case 169: + return visitMethodDeclaration(node, parent); case 170: - return visitorWorker(node); + return ts.visitEachChild(node, visitor, context); case 234: return node; + case 176: + return; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function getObjectLiteralElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return objectLiteralElementVisitorWorker(n, parent); }); }; + } + function objectLiteralElementVisitorWorker(node, parent) { + switch (node.kind) { + case 296: + case 297: + case 298: + return visitor(node); + case 172: + return visitGetAccessor(node, parent); + case 173: + return visitSetAccessor(node, parent); + case 169: + return visitMethodDeclaration(node, parent); default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { + if (ts.isDecorator(node)) + return undefined; if (ts.modifierToFlag(node.kind) & 116958) { return undefined; } @@ -77058,16 +78376,11 @@ var ts; case 195: case 196: case 176: - case 165: return undefined; case 259: return factory.createNotEmittedStatement(node); - case 167: - return visitPropertyDeclaration(node); case 264: return undefined; - case 171: - return visitConstructor(node); case 258: return factory.createNotEmittedStatement(node); case 257: @@ -77078,12 +78391,15 @@ var ts; return visitHeritageClause(node); case 228: return visitExpressionWithTypeArguments(node); + case 205: + return visitObjectLiteralExpression(node); + case 171: + case 167: case 169: - return visitMethodDeclaration(node); case 172: - return visitGetAccessor(node); case 173: - return visitSetAccessor(node); + case 170: + return ts.Debug.fail("Class and object literal elements must be visited with their respective visitors"); case 256: return visitFunctionDeclaration(node); case 213: @@ -77129,6 +78445,9 @@ var ts; !ts.isJsonSourceFile(node); return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } + function visitObjectLiteralExpression(node) { + return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, getObjectLiteralElementVisitor(node), ts.isObjectLiteralElement)); + } function getClassFacts(node, staticProperties) { var facts = 0; if (ts.some(staticProperties)) @@ -77151,17 +78470,17 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 4096); + return !!(node.transformFlags & 8192); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { - return ts.some(node.decorators) + return ts.hasDecorators(node) || ts.some(node.typeParameters) || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) || ts.some(node.members, hasTypeScriptClassSyntax); } function visitClassDeclaration(node) { if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1))) { - return ts.visitEachChild(node, visitor, context); + return factory.updateClassDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } var staticProperties = ts.getProperties(node, true, true); var facts = getClassFacts(node, staticProperties); @@ -77169,13 +78488,18 @@ var ts; context.startLexicalEnvironment(); } var name = node.name || (facts & 5 ? factory.getGeneratedNameForNode(node) : undefined); - var classStatement = facts & 2 - ? createClassDeclarationHeadWithDecorators(node, name) - : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + var modifiers = !(facts & 128) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : ts.elideNodes(factory, node.modifiers); + var classStatement = factory.updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); + var emitFlags = ts.getEmitFlags(node); + if (facts & 1) { + emitFlags |= 32; + } + ts.setEmitFlags(classStatement, emitFlags); var statements = [classStatement]; - addClassElementDecorationStatements(statements, node, false); - addClassElementDecorationStatements(statements, node, true); - addConstructorDecorationStatement(statements, node); if (facts & 128) { var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19); var localName = factory.getInternalName(node); @@ -77215,47 +78539,12 @@ var ts; } return ts.singleOrMany(statements); } - function createClassDeclarationHeadWithoutDecorators(node, name, facts) { - var modifiers = !(facts & 128) - ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) - : undefined; - var classDeclaration = factory.createClassDeclaration(undefined, modifiers, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - var emitFlags = ts.getEmitFlags(node); - if (facts & 1) { - emitFlags |= 32; - } - ts.setTextRange(classDeclaration, node); - ts.setOriginalNode(classDeclaration, node); - ts.setEmitFlags(classDeclaration, emitFlags); - return classDeclaration; - } - function createClassDeclarationHeadWithDecorators(node, name) { - var location = ts.moveRangePastDecorators(node); - var classAlias = getClassAliasIfNeeded(node); - var declName = languageVersion <= 2 ? - factory.getInternalName(node, false, true) : - factory.getLocalName(node, false, true); - var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node); - var classExpression = factory.createClassExpression(undefined, undefined, name, undefined, heritageClauses, members); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, location); - var statement = factory.createVariableStatement(undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(declName, undefined, undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) - ], 1)); - ts.setOriginalNode(statement, node); - ts.setTextRange(statement, location); - ts.setCommentRange(statement, node); - return statement; - } function visitClassExpression(node) { - if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { - return ts.visitEachChild(node, visitor, context); - } - var classExpression = factory.createClassExpression(undefined, undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, node); - return classExpression; + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + return factory.updateClassExpression(node, decorators, node.name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), isClassLikeDeclarationWithTypeScriptSyntax(node) ? + transformClassMembers(node) : + ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } function transformClassMembers(node) { var members = []; @@ -77266,225 +78555,86 @@ var ts; for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) { var parameter = parametersWithPropertyAssignments_1[_i]; if (ts.isIdentifier(parameter.name)) { - members.push(ts.setOriginalNode(factory.createPropertyDeclaration(undefined, undefined, parameter.name, undefined, undefined, undefined), parameter)); + members.push(ts.setOriginalNode(factory.createPropertyDeclaration(undefined, parameter.name, undefined, undefined, undefined), parameter)); } } } - ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + ts.addRange(members, ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), node.members); } - function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); - } - function isStaticDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, true, parent); - } - function isInstanceDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, false, parent); - } - function isDecoratedClassElement(member, isStaticElement, parent) { - return ts.nodeOrChildIsDecorated(member, parent) - && isStaticElement === ts.isStatic(member); - } - function getDecoratorsOfParameters(node) { - var decorators; - if (node) { - var parameters = node.parameters; - var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); - var firstParameterOffset = firstParameterIsThis ? 1 : 0; - var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i + firstParameterOffset]; - if (decorators || parameter.decorators) { - if (!decorators) { - decorators = new Array(numParameters); - } - decorators[i] = parameter.decorators; - } - } - } - return decorators; - } - function getAllDecoratorsOfConstructor(node) { - var decorators = node.decorators; - var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); - if (!decorators && !parameters) { - return undefined; - } - return { - decorators: decorators, - parameters: parameters - }; - } - function getAllDecoratorsOfClassElement(node, member) { - switch (member.kind) { - case 172: - case 173: - return getAllDecoratorsOfAccessors(node, member); - case 169: - return getAllDecoratorsOfMethod(member); - case 167: - return getAllDecoratorsOfProperty(member); - default: - return undefined; - } - } - function getAllDecoratorsOfAccessors(node, accessor) { - if (!accessor.body) { - return undefined; - } - var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; - if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { - return undefined; - } - var decorators = firstAccessorWithDecorators.decorators; - var parameters = getDecoratorsOfParameters(setAccessor); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - function getAllDecoratorsOfMethod(method) { - if (!method.body) { - return undefined; - } - var decorators = method.decorators; - var parameters = getDecoratorsOfParameters(method); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - function getAllDecoratorsOfProperty(property) { - var decorators = property.decorators; - if (!decorators) { - return undefined; - } - return { decorators: decorators }; - } function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + var _a, _b, _c, _d; if (!allDecorators) { return undefined; } - var decoratorExpressions = []; - ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); - ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, container, decoratorExpressions); - return decoratorExpressions; - } - function addClassElementDecorationStatements(statements, node, isStatic) { - ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); - } - function generateClassElementDecorationExpressions(node, isStatic) { - var members = getDecoratedClassElements(node, isStatic); - var expressions; - for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { - var member = members_8[_i]; - var expression = generateClassElementDecorationExpression(node, member); - if (expression) { - if (!expressions) { - expressions = [expression]; - } - else { - expressions.push(expression); - } - } - } - return expressions; - } - function generateClassElementDecorationExpression(node, member) { - var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - var prefix = getClassMemberPrefix(node, member); - var memberName = getExpressionForPropertyName(member, !ts.hasSyntacticModifier(member, 2)); - var descriptor = languageVersion > 0 - ? member.kind === 167 - ? factory.createVoidZero() - : factory.createNull() - : undefined; - var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); - ts.setTextRange(helper, ts.moveRangePastDecorators(member)); - ts.setEmitFlags(helper, 1536); - return helper; - } - function addConstructorDecorationStatement(statements, node) { - var expression = generateConstructorDecorationExpression(node); - if (expression) { - statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); - } - } - function generateConstructorDecorationExpression(node) { - var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; - var localName = languageVersion <= 2 ? - factory.getInternalName(node, false, true) : - factory.getLocalName(node, false, true); - var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); - var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); - ts.setEmitFlags(expression, 1536); - ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); - return expression; - } - function transformDecorator(decorator) { - return ts.visitNode(decorator.expression, visitor, ts.isExpression); + var decorators = ts.visitArray(allDecorators.decorators, visitor, ts.isDecorator); + var parameterDecorators = ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter); + var metadataDecorators = ts.some(decorators) || ts.some(parameterDecorators) ? getTypeMetadata(node, container) : undefined; + var result = factory.createNodeArray(ts.concatenate(ts.concatenate(decorators, parameterDecorators), metadataDecorators)); + var pos = (_b = (_a = ts.firstOrUndefined(allDecorators.decorators)) === null || _a === void 0 ? void 0 : _a.pos) !== null && _b !== void 0 ? _b : -1; + var end = (_d = (_c = ts.lastOrUndefined(allDecorators.decorators)) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : -1; + ts.setTextRangePosEnd(result, pos, end); + return result; } - function transformDecoratorsOfParameter(decorators, parameterOffset) { - var expressions; - if (decorators) { - expressions = []; - for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { - var decorator = decorators_1[_i]; - var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); - ts.setTextRange(helper, decorator.expression); + function transformDecoratorsOfParameter(parameterDecorators, parameterOffset) { + if (parameterDecorators) { + var decorators = []; + for (var _i = 0, parameterDecorators_1 = parameterDecorators; _i < parameterDecorators_1.length; _i++) { + var parameterDecorator = parameterDecorators_1[_i]; + var expression = ts.visitNode(parameterDecorator.expression, visitor, ts.isExpression); + var helper = emitHelpers().createParamHelper(expression, parameterOffset); + ts.setTextRange(helper, parameterDecorator.expression); ts.setEmitFlags(helper, 1536); - expressions.push(helper); + var decorator = factory.createDecorator(helper); + ts.setSourceMapRange(decorator, parameterDecorator.expression); + ts.setCommentRange(decorator, parameterDecorator.expression); + ts.setEmitFlags(decorator, 1536); + decorators.push(decorator); } + return decorators; } - return expressions; } - function addTypeMetadata(node, container, decoratorExpressions) { - if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, container, decoratorExpressions); - } - else { - addOldTypeMetadata(node, container, decoratorExpressions); - } + function getTypeMetadata(node, container) { + return USE_NEW_TYPE_METADATA_FORMAT ? + getNewTypeMetadata(node, container) : + getOldTypeMetadata(node, container); } - function addOldTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getOldTypeMetadata(node, container) { + if (typeSerializer) { + var decorators = void 0; if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node))); + var typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(typeMetadata)); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container))); + var paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container)); + decorators = ts.append(decorators, factory.createDecorator(paramTypesMetadata)); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node))); + var returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(returnTypeMetadata)); } + return decorators; } } - function addNewTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getNewTypeMetadata(node, container) { + if (typeSerializer) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(undefined, undefined, [], undefined, factory.createToken(38), serializeTypeOfNode(node)))); + var typeProperty = factory.createPropertyAssignment("type", factory.createArrowFunction(undefined, undefined, [], undefined, factory.createToken(38), typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, typeProperty); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(undefined, undefined, [], undefined, factory.createToken(38), serializeParameterTypesOfNode(node, container)))); + var paramTypeProperty = factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(undefined, undefined, [], undefined, factory.createToken(38), typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container))); + properties = ts.append(properties, paramTypeProperty); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(undefined, undefined, [], undefined, factory.createToken(38), serializeReturnTypeOfNode(node)))); + var returnTypeProperty = factory.createPropertyAssignment("returnType", factory.createArrowFunction(undefined, undefined, [], undefined, factory.createToken(38), typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, returnTypeProperty); } if (properties) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, true))); + var typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, true)); + return [factory.createDecorator(typeInfoMetadata)]; } } } @@ -77510,262 +78660,6 @@ var ts; } return false; } - function getAccessorTypeNode(node) { - var accessors = resolver.getAllAccessorDeclarations(node); - return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) - || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); - } - function serializeTypeOfNode(node) { - switch (node.kind) { - case 167: - case 164: - return serializeTypeNode(node.type); - case 173: - case 172: - return serializeTypeNode(getAccessorTypeNode(node)); - case 257: - case 226: - case 169: - return factory.createIdentifier("Function"); - default: - return factory.createVoidZero(); - } - } - function serializeParameterTypesOfNode(node, container) { - var valueDeclaration = ts.isClassLike(node) - ? ts.getFirstConstructorWithBody(node) - : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) - ? node - : undefined; - var expressions = []; - if (valueDeclaration) { - var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); - var numParameters = parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { - continue; - } - if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); - } - else { - expressions.push(serializeTypeOfNode(parameter)); - } - } - } - return factory.createArrayLiteralExpression(expressions); - } - function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 172) { - var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; - if (setAccessor) { - return setAccessor.parameters; - } - } - return node.parameters; - } - function serializeReturnTypeOfNode(node) { - if (ts.isFunctionLike(node) && node.type) { - return serializeTypeNode(node.type); - } - else if (ts.isAsyncFunction(node)) { - return factory.createIdentifier("Promise"); - } - return factory.createVoidZero(); - } - function serializeTypeNode(node) { - if (node === undefined) { - return factory.createIdentifier("Object"); - } - switch (node.kind) { - case 114: - case 153: - case 143: - return factory.createVoidZero(); - case 191: - return serializeTypeNode(node.type); - case 179: - case 180: - return factory.createIdentifier("Function"); - case 183: - case 184: - return factory.createIdentifier("Array"); - case 177: - case 133: - return factory.createIdentifier("Boolean"); - case 198: - case 150: - return factory.createIdentifier("String"); - case 148: - return factory.createIdentifier("Object"); - case 196: - switch (node.literal.kind) { - case 10: - case 14: - return factory.createIdentifier("String"); - case 219: - case 8: - return factory.createIdentifier("Number"); - case 9: - return getGlobalBigIntNameWithFallback(); - case 110: - case 95: - return factory.createIdentifier("Boolean"); - case 104: - return factory.createVoidZero(); - default: - return ts.Debug.failBadSyntaxKind(node.literal); - } - case 147: - return factory.createIdentifier("Number"); - case 158: - return getGlobalBigIntNameWithFallback(); - case 151: - return languageVersion < 2 - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case 178: - return serializeTypeReferenceNode(node); - case 188: - case 187: - return serializeTypeList(node.types); - case 189: - return serializeTypeList([node.trueType, node.falseType]); - case 193: - if (node.operator === 145) { - return serializeTypeNode(node.type); - } - break; - case 181: - case 194: - case 195: - case 182: - case 130: - case 155: - case 192: - case 200: - break; - case 312: - case 313: - case 317: - case 318: - case 319: - break; - case 314: - case 315: - case 316: - return serializeTypeNode(node.type); - default: - return ts.Debug.failBadSyntaxKind(node); - } - return factory.createIdentifier("Object"); - } - function serializeTypeList(types) { - var serializedUnion; - for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { - var typeNode = types_23[_i]; - while (typeNode.kind === 191) { - typeNode = typeNode.type; - } - if (typeNode.kind === 143) { - continue; - } - if (!strictNullChecks && (typeNode.kind === 196 && typeNode.literal.kind === 104 || typeNode.kind === 153)) { - continue; - } - var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { - return serializedIndividual; - } - else if (serializedUnion) { - if (!ts.isIdentifier(serializedUnion) || - !ts.isIdentifier(serializedIndividual) || - serializedUnion.escapedText !== serializedIndividual.escapedText) { - return factory.createIdentifier("Object"); - } - } - else { - serializedUnion = serializedIndividual; - } - } - return serializedUnion || factory.createVoidZero(); - } - function serializeTypeReferenceNode(node) { - var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); - switch (kind) { - case ts.TypeReferenceSerializationKind.Unknown: - if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { - return factory.createIdentifier("Object"); - } - var serialized = serializeEntityNameAsExpressionFallback(node.typeName); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), undefined, temp, undefined, factory.createIdentifier("Object")); - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName); - case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: - return factory.createVoidZero(); - case ts.TypeReferenceSerializationKind.BigIntLikeType: - return getGlobalBigIntNameWithFallback(); - case ts.TypeReferenceSerializationKind.BooleanType: - return factory.createIdentifier("Boolean"); - case ts.TypeReferenceSerializationKind.NumberLikeType: - return factory.createIdentifier("Number"); - case ts.TypeReferenceSerializationKind.StringLikeType: - return factory.createIdentifier("String"); - case ts.TypeReferenceSerializationKind.ArrayLikeType: - return factory.createIdentifier("Array"); - case ts.TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < 2 - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - return factory.createIdentifier("Function"); - case ts.TypeReferenceSerializationKind.Promise: - return factory.createIdentifier("Promise"); - case ts.TypeReferenceSerializationKind.ObjectType: - return factory.createIdentifier("Object"); - default: - return ts.Debug.assertNever(kind); - } - } - function createCheckedValue(left, right) { - return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right); - } - function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 79) { - var copied = serializeEntityNameAsExpression(node); - return createCheckedValue(copied, copied); - } - if (node.left.kind === 79) { - return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); - } - var left = serializeEntityNameAsExpressionFallback(node.left); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right)); - } - function serializeEntityNameAsExpression(node) { - switch (node.kind) { - case 79: - var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); - name.original = undefined; - ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); - return name; - case 161: - return serializeQualifiedNameAsExpression(node); - } - } - function serializeQualifiedNameAsExpression(node) { - return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); - } - function getGlobalSymbolNameWithFallback() { - return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), undefined, factory.createIdentifier("Symbol"), undefined, factory.createIdentifier("Object")); - } - function getGlobalBigIntNameWithFallback() { - return languageVersion < 99 - ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), undefined, factory.createIdentifier("BigInt"), undefined, factory.createIdentifier("Object")) - : factory.createIdentifier("BigInt"); - } function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { var name = member.name; if (ts.isPrivateIdentifier(name)) { @@ -77785,7 +78679,7 @@ var ts; } function visitPropertyNameOfClassElement(member) { var name = member.name; - if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) { + if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.hasDecorators(member))) { var expression = ts.visitNode(name.expression, visitor, ts.isExpression); var innerExpression = ts.skipPartiallyEmittedExpressions(expression); if (!ts.isSimpleInlineableExpression(innerExpression)) { @@ -77808,22 +78702,23 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } - function visitPropertyDeclaration(node) { - if (node.flags & 16777216 || ts.hasSyntacticModifier(node, 128)) { + function visitPropertyDeclaration(node, parent) { + var isAmbient = node.flags & 16777216 || ts.hasSyntacticModifier(node, 128); + if (isAmbient && !ts.hasDecorators(node)) { return undefined; } - var updated = factory.updatePropertyDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), undefined, undefined, ts.visitNode(node.initializer, visitor)); - if (updated !== node) { - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); + var allDecorators = ts.getAllDecoratorsOfClassElement(node, parent); + var decorators = transformAllDecoratorsOfDeclaration(node, parent, allDecorators); + if (isAmbient) { + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, factory.createModifiersFromModifierFlags(2)), ts.visitNode(node.name, visitor, ts.isPropertyName), undefined, undefined, undefined); } - return updated; + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), undefined, undefined, ts.visitNode(node.initializer, visitor)); } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - return factory.updateConstructorDeclaration(node, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node)); + return factory.updateConstructorDeclaration(node, undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node)); } function transformConstructorBody(body, constructor) { var parametersWithPropertyAssignments = constructor && @@ -77845,7 +78740,8 @@ var ts; else { statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, prologueStatementCount), true), parameterPropertyAssignments, true), statements.slice(prologueStatementCount), true); } - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, superStatementIndex + 1 + prologueStatementCount)); + var start = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, start)); statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), true); ts.setTextRange(block, body); @@ -77863,47 +78759,49 @@ var ts; ts.setEmitFlags(localName, 1536); return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(factory.createExpressionStatement(factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1)))); } - function visitMethodDeclaration(node) { + function visitMethodDeclaration(node, parent) { + if (!(node.transformFlags & 1)) { + return node; + } if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var updated = factory.updateMethodDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); - if (updated !== node) { - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; + var allDecorators = ts.isClassLike(parent) ? ts.getAllDecoratorsOfClassElement(node, parent) : undefined; + var decorators = ts.isClassLike(parent) ? transformAllDecoratorsOfDeclaration(node, parent, allDecorators) : undefined; + return factory.updateMethodDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); } function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128)); } - function visitGetAccessor(node) { + function visitGetAccessor(node, parent) { + if (!(node.transformFlags & 1)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateGetAccessorDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateGetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); } - function visitSetAccessor(node) { + function visitSetAccessor(node, parent) { + if (!(node.transformFlags & 1)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateSetAccessorDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateSetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return factory.createNotEmittedStatement(node); } - var updated = factory.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); + var updated = factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); if (isExportOfNamespace(node)) { var statements = [updated]; addExportMemberAssignment(statements, node); @@ -77926,7 +78824,7 @@ var ts; if (ts.parameterIsThisKeyword(node)) { return undefined; } - var updated = factory.updateParameterDeclaration(node, undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); if (updated !== node) { ts.setCommentRange(updated, node); ts.setTextRange(updated, ts.moveRangePastModifiers(node)); @@ -78020,7 +78918,7 @@ var ts; var localName = factory.getLocalName(node, false, true); moduleArg = factory.createAssignment(localName, moduleArg); } - var enumStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(undefined, undefined, undefined, undefined, [factory.createParameterDeclaration(undefined, undefined, undefined, parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [moduleArg])); + var enumStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(undefined, undefined, undefined, undefined, [factory.createParameterDeclaration(undefined, undefined, parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); if (varAdded) { ts.setSyntheticLeadingComments(enumStatement, undefined); @@ -78152,7 +79050,7 @@ var ts; var localName = factory.getLocalName(node, false, true); moduleArg = factory.createAssignment(localName, moduleArg); } - var moduleStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(undefined, undefined, undefined, undefined, [factory.createParameterDeclaration(undefined, undefined, undefined, parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg])); + var moduleStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(undefined, undefined, undefined, undefined, [factory.createParameterDeclaration(undefined, undefined, parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); if (varAdded) { ts.setSyntheticLeadingComments(moduleStatement, undefined); @@ -78223,7 +79121,7 @@ var ts; return importClause || compilerOptions.importsNotUsedAsValues === 1 || compilerOptions.importsNotUsedAsValues === 2 - ? factory.updateImportDeclaration(node, undefined, undefined, importClause, node.moduleSpecifier, node.assertClause) + ? factory.updateImportDeclaration(node, undefined, importClause, node.moduleSpecifier, node.assertClause) : undefined; } function visitImportClause(node) { @@ -78262,7 +79160,7 @@ var ts; compilerOptions.importsNotUsedAsValues === 2); var exportClause = ts.visitNode(node.exportClause, function (bindings) { return visitNamedExportBindings(bindings, allowEmpty); }, ts.isNamedExportBindings); return exportClause - ? factory.updateExportDeclaration(node, undefined, undefined, node.isTypeOnly, exportClause, node.moduleSpecifier, node.assertClause) + ? factory.updateExportDeclaration(node, undefined, node.isTypeOnly, exportClause, node.moduleSpecifier, node.assertClause) : undefined; } function visitNamedExports(node, allowEmpty) { @@ -78290,7 +79188,7 @@ var ts; if (ts.isExternalModuleImportEqualsDeclaration(node)) { var isReferenced = shouldEmitAliasDeclaration(node); if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1) { - return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration(undefined, undefined, undefined, node.moduleReference.expression, undefined), node), node); + return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration(undefined, undefined, node.moduleReference.expression, undefined), node), node); } return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined; } @@ -78322,9 +79220,6 @@ var ts; return isExternalModuleExport(node) && ts.hasSyntacticModifier(node, 512); } - function expressionToStatement(expression) { - return factory.createExpressionStatement(expression); - } function addExportMemberAssignment(statements, node) { var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true), factory.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); @@ -78349,36 +79244,12 @@ var ts; function getNamespaceContainerName(node) { return factory.getGeneratedNameForNode(node); } - function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 16777216) { - enableSubstitutionForClassAliases(); - var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - hoistVariableDeclaration(classAlias); - return classAlias; - } - } - function getClassPrototype(node) { - return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); - } - function getClassMemberPrefix(node, member) { - return ts.isStatic(member) - ? factory.getDeclarationName(node) - : getClassPrototype(node); - } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8) === 0) { enabledSubstitutions |= 8; context.enableSubstitution(79); } } - function enableSubstitutionForClassAliases() { - if ((enabledSubstitutions & 1) === 0) { - enabledSubstitutions |= 1; - context.enableSubstitution(79); - classAliases = []; - } - } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; @@ -78445,27 +79316,9 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - return trySubstituteClassAlias(node) - || trySubstituteNamespaceExportedName(node) + return trySubstituteNamespaceExportedName(node) || node; } - function trySubstituteClassAlias(node) { - if (enabledSubstitutions & 1) { - if (resolver.getNodeCheckFlags(node) & 33554432) { - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = classAliases[declaration.id]; - if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; - } - } - } - } - return undefined; - } function trySubstituteNamespaceExportedName(node) { if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var container = resolver.getReferencedExportContainer(node, false); @@ -78551,7 +79404,7 @@ var ts; return visited; } function visitorWorker(node, valueIsDiscarded) { - if (node.transformFlags & 8388608) { + if (node.transformFlags & 16777216) { switch (node.kind) { case 226: case 257: @@ -78566,8 +79419,8 @@ var ts; return visitClassStaticBlockDeclaration(node); } } - if (node.transformFlags & 8388608 || - node.transformFlags & 33554432 && + if (node.transformFlags & 16777216 || + node.transformFlags & 134217728 && shouldTransformSuperInStaticInitializers && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { @@ -78690,7 +79543,7 @@ var ts; return node; } function visitMethodOrAccessorDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.isPrivateIdentifier(node.name)) { return ts.visitEachChild(node, classElementVisitor, context); } @@ -78701,7 +79554,7 @@ var ts; } var functionName = getHoistedFunctionName(node); if (functionName) { - getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return ts.isModifier(m) && !ts.isStaticModifier(m); }), node.asteriskToken, functionName, undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); } return undefined; } @@ -78722,13 +79575,13 @@ var ts; } } function visitPropertyDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (ts.isPrivateIdentifier(node.name)) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { if (ts.isStatic(node)) { return ts.visitEachChild(node, visitor, context); } - return factory.updatePropertyDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, undefined, undefined, undefined); + return factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, undefined, undefined, undefined); } var info = accessPrivateIdentifier(node.name); ts.Debug.assert(info, "Undeclared private name for property declaration."); @@ -78743,7 +79596,7 @@ var ts; if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); if (initializerStatement) { - var staticBlock = factory.createClassStaticBlockDeclaration(undefined, undefined, factory.createBlock([initializerStatement])); + var staticBlock = factory.createClassStaticBlockDeclaration(factory.createBlock([initializerStatement])); ts.setOriginalNode(staticBlock, node); ts.setCommentRange(staticBlock, node); ts.setCommentRange(initializerStatement, { pos: -1, end: -1 }); @@ -78815,10 +79668,11 @@ var ts; } function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) { if (node.operator === 45 || node.operator === 46) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + var operand = ts.skipParentheses(node.operand); + if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(operand)) { var info = void 0; - if (info = accessPrivateIdentifier(node.operand.name)) { - var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression); + if (info = accessPrivateIdentifier(operand.name)) { + var receiver = ts.visitNode(operand.expression, visitor, ts.isExpression); var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; var expression = createPrivateIdentifierAccess(info, readExpression); var temp = ts.isPrefixUnaryExpression(node) || valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); @@ -78834,36 +79688,36 @@ var ts; } } else if (shouldTransformSuperInStaticInitializers && - ts.isSuperProperty(node.operand) && + ts.isSuperProperty(operand) && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; if (facts & 1) { - var operand = visitInvalidSuperProperty(node.operand); + var expression = visitInvalidSuperProperty(operand); return ts.isPrefixUnaryExpression(node) ? - factory.updatePrefixUnaryExpression(node, operand) : - factory.updatePostfixUnaryExpression(node, operand); + factory.updatePrefixUnaryExpression(node, expression) : + factory.updatePostfixUnaryExpression(node, expression); } if (classConstructor && superClassReference) { var setterName = void 0; var getterName = void 0; - if (ts.isPropertyAccessExpression(node.operand)) { - if (ts.isIdentifier(node.operand.name)) { - getterName = setterName = factory.createStringLiteralFromNode(node.operand.name); + if (ts.isPropertyAccessExpression(operand)) { + if (ts.isIdentifier(operand.name)) { + getterName = setterName = factory.createStringLiteralFromNode(operand.name); } } else { - if (ts.isSimpleInlineableExpression(node.operand.argumentExpression)) { - getterName = setterName = node.operand.argumentExpression; + if (ts.isSimpleInlineableExpression(operand.argumentExpression)) { + getterName = setterName = operand.argumentExpression; } else { getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, ts.visitNode(node.operand.argumentExpression, visitor, ts.isExpression)); + setterName = factory.createAssignment(getterName, ts.visitNode(operand.argumentExpression, visitor, ts.isExpression)); } } if (setterName && getterName) { var expression = factory.createReflectGetCall(superClassReference, getterName, classConstructor); - ts.setTextRange(expression, node.operand); + ts.setTextRange(expression, operand); var temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); expression = ts.expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp); expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor); @@ -79078,13 +79932,13 @@ var ts; facts |= 2; } if (ts.isPropertyDeclaration(member) || ts.isClassStaticBlockDeclaration(member)) { - if (shouldTransformThisInStaticInitializers && member.transformFlags & 8192) { + if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384) { facts |= 8; if (!(facts & 1)) { facts |= 2; } } - if (shouldTransformSuperInStaticInitializers && member.transformFlags & 33554432) { + if (shouldTransformSuperInStaticInitializers && member.transformFlags & 134217728) { if (!(facts & 1)) { facts |= 2 | 4; } @@ -79119,7 +79973,7 @@ var ts; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104); var statements = [ - factory.updateClassDeclaration(node, undefined, node.modifiers, node.name, undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) + factory.updateClassDeclaration(node, node.modifiers, node.name, undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; if (pendingClassReferenceAssignment) { getPendingExpressions().unshift(pendingClassReferenceAssignment); @@ -79157,7 +80011,7 @@ var ts; temp = createClassTempVar(); getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); } - var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); + var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || ts.isPrivateIdentifier(p.name); }); if (hasTransformableStatics || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { @@ -79217,7 +80071,7 @@ var ts; members.push(constructor); } if (!shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(pendingExpressions)) { - members.push(factory.createClassStaticBlockDeclaration(undefined, undefined, factory.createBlock([ + members.push(factory.createClassStaticBlockDeclaration(factory.createBlock([ factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)) ]))); pendingExpressions = undefined; @@ -79250,7 +80104,7 @@ var ts; if (!body) { return undefined; } - return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration(undefined, undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); + return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration(undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { var _a; @@ -79559,10 +80413,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_3 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_3, node); - ts.setCommentRange(clone_3, node); - return clone_3; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -79897,6 +80751,659 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function createRuntimeTypeSerializer(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var currentLexicalScope; + var currentNameScope; + return { + serializeTypeNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeNode, node); }, + serializeTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeOfNode, node); }, + serializeParameterTypesOfNode: function (serializerContext, node, container) { return setSerializerContextAnd(serializerContext, serializeParameterTypesOfNode, node, container); }, + serializeReturnTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeReturnTypeOfNode, node); }, + }; + function setSerializerContextAnd(serializerContext, cb, node, arg) { + var savedCurrentLexicalScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + currentLexicalScope = serializerContext.currentLexicalScope; + currentNameScope = serializerContext.currentNameScope; + var result = arg === undefined ? cb(node) : cb(node, arg); + currentLexicalScope = savedCurrentLexicalScope; + currentNameScope = savedCurrentNameScope; + return result; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + function serializeTypeOfNode(node) { + switch (node.kind) { + case 167: + case 164: + return serializeTypeNode(node.type); + case 173: + case 172: + return serializeTypeNode(getAccessorTypeNode(node)); + case 257: + case 226: + case 169: + return ts.factory.createIdentifier("Function"); + default: + return ts.factory.createVoidZero(); + } + } + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.factory.createArrayLiteralExpression(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 172) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.factory.createIdentifier("Promise"); + } + return ts.factory.createVoidZero(); + } + function serializeTypeNode(node) { + if (node === undefined) { + return ts.factory.createIdentifier("Object"); + } + node = ts.skipTypeParentheses(node); + switch (node.kind) { + case 114: + case 153: + case 143: + return ts.factory.createVoidZero(); + case 179: + case 180: + return ts.factory.createIdentifier("Function"); + case 183: + case 184: + return ts.factory.createIdentifier("Array"); + case 177: + return node.assertsModifier ? + ts.factory.createVoidZero() : + ts.factory.createIdentifier("Boolean"); + case 133: + return ts.factory.createIdentifier("Boolean"); + case 198: + case 150: + return ts.factory.createIdentifier("String"); + case 148: + return ts.factory.createIdentifier("Object"); + case 196: + return serializeLiteralOfLiteralTypeNode(node.literal); + case 147: + return ts.factory.createIdentifier("Number"); + case 158: + return getGlobalConstructor("BigInt", 7); + case 151: + return getGlobalConstructor("Symbol", 2); + case 178: + return serializeTypeReferenceNode(node); + case 188: + return serializeUnionOrIntersectionConstituents(node.types, true); + case 187: + return serializeUnionOrIntersectionConstituents(node.types, false); + case 189: + return serializeUnionOrIntersectionConstituents([node.trueType, node.falseType], false); + case 193: + if (node.operator === 145) { + return serializeTypeNode(node.type); + } + break; + case 181: + case 194: + case 195: + case 182: + case 130: + case 155: + case 192: + case 200: + break; + case 312: + case 313: + case 317: + case 318: + case 319: + break; + case 314: + case 315: + case 316: + return serializeTypeNode(node.type); + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.factory.createIdentifier("Object"); + } + function serializeLiteralOfLiteralTypeNode(node) { + switch (node.kind) { + case 10: + case 14: + return ts.factory.createIdentifier("String"); + case 219: { + var operand = node.operand; + switch (operand.kind) { + case 8: + case 9: + return serializeLiteralOfLiteralTypeNode(operand); + default: + return ts.Debug.failBadSyntaxKind(operand); + } + } + case 8: + return ts.factory.createIdentifier("Number"); + case 9: + return getGlobalConstructor("BigInt", 7); + case 110: + case 95: + return ts.factory.createIdentifier("Boolean"); + case 104: + return ts.factory.createVoidZero(); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function serializeUnionOrIntersectionConstituents(types, isIntersection) { + var serializedType; + for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { + var typeNode = types_22[_i]; + typeNode = ts.skipTypeParentheses(typeNode); + if (typeNode.kind === 143) { + if (isIntersection) + return ts.factory.createVoidZero(); + continue; + } + if (typeNode.kind === 155) { + if (!isIntersection) + return ts.factory.createIdentifier("Object"); + continue; + } + if (typeNode.kind === 130) { + return ts.factory.createIdentifier("Object"); + } + if (!strictNullChecks && ((ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === 104) || typeNode.kind === 153)) { + continue; + } + var serializedConstituent = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") { + return serializedConstituent; + } + if (serializedType) { + if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) { + return ts.factory.createIdentifier("Object"); + } + } + else { + serializedType = serializedConstituent; + } + } + return serializedType !== null && serializedType !== void 0 ? serializedType : (ts.factory.createVoidZero()); + } + function equateSerializedTypeNodes(left, right) { + return (ts.isGeneratedIdentifier(left) ? ts.isGeneratedIdentifier(right) : + ts.isIdentifier(left) ? ts.isIdentifier(right) + && left.escapedText === right.escapedText : + ts.isPropertyAccessExpression(left) ? ts.isPropertyAccessExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) + && equateSerializedTypeNodes(left.name, right.name) : + ts.isVoidExpression(left) ? ts.isVoidExpression(right) + && ts.isNumericLiteral(left.expression) && left.expression.text === "0" + && ts.isNumericLiteral(right.expression) && right.expression.text === "0" : + ts.isStringLiteral(left) ? ts.isStringLiteral(right) + && left.text === right.text : + ts.isTypeOfExpression(left) ? ts.isTypeOfExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + ts.isParenthesizedExpression(left) ? ts.isParenthesizedExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + ts.isConditionalExpression(left) ? ts.isConditionalExpression(right) + && equateSerializedTypeNodes(left.condition, right.condition) + && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) + && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : + ts.isBinaryExpression(left) ? ts.isBinaryExpression(right) + && left.operatorToken.kind === right.operatorToken.kind + && equateSerializedTypeNodes(left.left, right.left) + && equateSerializedTypeNodes(left.right, right.right) : + false); + } + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope !== null && currentNameScope !== void 0 ? currentNameScope : currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.factory.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createAssignment(temp, serialized), "function"), undefined, temp, undefined, ts.factory.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.factory.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalConstructor("BigInt", 7); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.factory.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.factory.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.factory.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.factory.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return getGlobalConstructor("Symbol", 2); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.factory.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.factory.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.factory.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + function createCheckedValue(left, right) { + return ts.factory.createLogicalAnd(ts.factory.createStrictInequality(ts.factory.createTypeOfExpression(left), ts.factory.createStringLiteral("undefined")), right); + } + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 79) { + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 79) { + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createLogicalAnd(ts.factory.createLogicalAnd(left.left, ts.factory.createStrictInequality(ts.factory.createAssignment(temp, left.right), ts.factory.createVoidZero())), ts.factory.createPropertyAccessExpression(temp, node.right)); + } + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 79: + var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); + name.original = undefined; + ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); + return name; + case 161: + return serializeQualifiedNameAsExpression(node); + } + } + function serializeQualifiedNameAsExpression(node) { + return ts.factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); + } + function getGlobalConstructorWithFallback(name) { + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createIdentifier(name), "function"), undefined, ts.factory.createIdentifier(name), undefined, ts.factory.createIdentifier("Object")); + } + function getGlobalConstructor(name, minLanguageVersion) { + return languageVersion < minLanguageVersion ? + getGlobalConstructorWithFallback(name) : + ts.factory.createIdentifier(name); + } + } + ts.createRuntimeTypeSerializer = createRuntimeTypeSerializer; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformLegacyDecorators(context) { + var factory = context.factory, emitHelpers = context.getEmitHelperFactory, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var previousOnSubstituteNode = context.onSubstituteNode; + context.onSubstituteNode = onSubstituteNode; + var classAliases; + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function modifierVisitor(node) { + return ts.isDecorator(node) ? undefined : node; + } + function visitor(node) { + if (!(node.transformFlags & 33554432)) { + return node; + } + switch (node.kind) { + case 165: + return undefined; + case 257: + return visitClassDeclaration(node); + case 226: + return visitClassExpression(node); + case 171: + return visitConstructorDeclaration(node); + case 169: + return visitMethodDeclaration(node); + case 173: + return visitSetAccessorDeclaration(node); + case 172: + return visitGetAccessorDeclaration(node); + case 167: + return visitPropertyDeclaration(node); + case 164: + return visitParameterDeclaration(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitClassDeclaration(node) { + if (!(ts.classOrConstructorParameterIsDecorated(node) || ts.childIsDecorated(node))) + return ts.visitEachChild(node, visitor, context); + var statements = ts.hasDecorators(node) ? + transformClassDeclarationWithClassDecorators(node, node.name) : + transformClassDeclarationWithoutClassDecorators(node, node.name); + if (statements.length > 1) { + statements.push(factory.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statements[0], ts.getEmitFlags(statements[0]) | 4194304); + } + return ts.singleOrMany(statements); + } + function decoratorContainsPrivateIdentifierInExpression(decorator) { + return !!(decorator.transformFlags & 536870912); + } + function parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators) { + return ts.some(parameterDecorators, decoratorContainsPrivateIdentifierInExpression); + } + function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.canHaveDecorators(member)) + continue; + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) + return true; + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) + return true; + } + return false; + } + function transformDecoratorsOfClassElements(node, members) { + var decorationStatements = []; + addClassElementDecorationStatements(decorationStatements, node, false); + addClassElementDecorationStatements(decorationStatements, node, true); + if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { + members = ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], members, true), [ + factory.createClassStaticBlockDeclaration(factory.createBlock(decorationStatements, true)) + ], false)), members); + decorationStatements = undefined; + } + return { decorationStatements: decorationStatements, members: members }; + } + function transformClassDeclarationWithoutClassDecorators(node, name) { + var _a; + var modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var updated = factory.updateClassDeclaration(node, modifiers, name, undefined, heritageClauses, members); + return ts.addRange([updated], decorationStatements); + } + function transformClassDeclarationWithClassDecorators(node, name) { + var _a; + var location = ts.moveRangePastModifiers(node); + var classAlias = getClassAliasIfNeeded(node); + var declName = languageVersion <= 2 ? + factory.getInternalName(node, false, true) : + factory.getLocalName(node, false, true); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var classExpression = factory.createClassExpression(undefined, name, undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + var statement = factory.createVariableStatement(undefined, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(declName, undefined, undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) + ], 1)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + var statements = [statement]; + ts.addRange(statements, decorationStatements); + addConstructorDecorationStatement(statements, node); + return statements; + } + function visitClassExpression(node) { + return factory.updateClassExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)); + } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)); + } + function finishClassElement(updated, original) { + if (updated !== original) { + ts.setCommentRange(updated, original); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(original)); + } + return updated; + } + function visitMethodDeclaration(node) { + return finishClassElement(factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), undefined, undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitGetAccessorDeclaration(node) { + return finishClassElement(factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitSetAccessorDeclaration(node) { + return finishClassElement(factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitPropertyDeclaration(node) { + if (node.flags & 16777216 || ts.hasSyntacticModifier(node, 2)) { + return undefined; + } + return finishClassElement(factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function visitParameterDeclaration(node) { + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32); + } + return updated; + } + function transformAllDecoratorsOfDeclaration(allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + return decoratorExpressions; + } + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), function (expr) { return factory.createExpressionStatement(expr); })); + } + function isDecoratedClassElement(member, isStaticElement, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStaticElement === ts.isStatic(member); + } + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, function (m) { return isDecoratedClassElement(m, isStatic, node); }); + } + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { + var member = members_8[_i]; + expressions = ts.append(expressions, generateClassElementDecorationExpression(node, member)); + } + return expressions; + } + function generateClassElementDecorationExpression(node, member) { + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, !ts.hasSyntacticModifier(member, 2)); + var descriptor = languageVersion > 0 + ? member.kind === 167 + ? factory.createVoidZero() + : factory.createNull() + : undefined; + var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); + ts.setEmitFlags(helper, 1536); + ts.setSourceMapRange(helper, ts.moveRangePastModifiers(member)); + return helper; + } + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); + } + } + function generateConstructorDecorationExpression(node) { + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + var localName = languageVersion <= 2 ? + factory.getInternalName(node, false, true) : + factory.getLocalName(node, false, true); + var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); + var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(node)); + return expression; + } + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); + ts.setTextRange(helper, decorator.expression); + ts.setEmitFlags(helper, 1536); + expressions.push(helper); + } + } + return expressions; + } + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isPrivateIdentifier(name)) { + return factory.createIdentifier(""); + } + else if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression) + ? factory.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return factory.createStringLiteral(ts.idText(name)); + } + else { + return factory.cloneNode(name); + } + } + function enableSubstitutionForClassAliases() { + if (!classAliases) { + context.enableSubstitution(79); + classAliases = []; + } + } + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216) { + enableSubstitutionForClassAliases(); + var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.isStatic(member) + ? factory.getDeclarationName(node) + : getClassPrototype(node); + } + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 79: + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + var _a; + return (_a = trySubstituteClassAlias(node)) !== null && _a !== void 0 ? _a : node; + } + function trySubstituteClassAlias(node) { + if (classAliases) { + if (resolver.getNodeCheckFlags(node) & 33554432) { + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; + if (classAlias) { + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; + } + } + } + } + return undefined; + } + } + ts.transformLegacyDecorators = transformLegacyDecorators; +})(ts || (ts = {})); +var ts; (function (ts) { function transformES2017(context) { var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; @@ -80071,22 +81578,22 @@ var ts; return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } function visitMethodDeclaration(node) { - return factory.updateMethodDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + 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)); } function visitFunctionDeclaration(node) { - return factory.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + 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 ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } function visitFunctionExpression(node) { - return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } function visitArrowFunction(node) { - return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 + return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } @@ -80343,7 +81850,7 @@ var ts; getterAndSetter.push(factory.createPropertyAssignment("get", factory.createArrowFunction(undefined, undefined, [], undefined, undefined, ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4), name), 4)))); if (hasBinding) { getterAndSetter.push(factory.createPropertyAssignment("set", factory.createArrowFunction(undefined, undefined, [ - factory.createParameterDeclaration(undefined, undefined, undefined, "v", undefined, undefined, undefined) + factory.createParameterDeclaration(undefined, undefined, "v", undefined, undefined, undefined) ], undefined, undefined, factory.createAssignment(ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4), name), 4), factory.createIdentifier("v"))))); } accessors.push(factory.createPropertyAssignment(name, factory.createObjectLiteralExpression(getterAndSetter))); @@ -80562,7 +82069,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 32768) { + if (node.transformFlags & 65536) { var objects = chunkObjectLiteralElements(node.properties); if (objects.length && objects[0].kind !== 205) { objects.unshift(factory.createObjectLiteralExpression()); @@ -80603,7 +82110,7 @@ var ts; return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction); } function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 65536) { return ts.flattenDestructuringAssignment(node, visitor, context, 1, !expressionResultIsUnused); } if (node.operatorToken.kind === 27) { @@ -80630,7 +82137,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 32768) { + node.variableDeclaration.name.transformFlags & 65536) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, undefined, undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1); @@ -80665,7 +82172,7 @@ var ts; return visitVariableDeclarationWorker(node, false); } function visitVariableDeclarationWorker(node, exportedVariableStatement) { - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 65536) { return ts.flattenDestructuringBinding(node, visitor, context, 1, undefined, exportedVariableStatement); } return ts.visitEachChild(node, visitor, context); @@ -80678,7 +82185,7 @@ var ts; } function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0, 2); - if (node.initializer.transformFlags & 32768) { + if (node.initializer.transformFlags & 65536) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -80773,10 +82280,10 @@ var ts; } function visitParameter(node) { if (parametersWithPrecedingObjectRestOrSpread === null || parametersWithPrecedingObjectRestOrSpread === void 0 ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { - return factory.updateParameterDeclaration(node, undefined, undefined, node.dotDotDotToken, ts.isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, undefined, undefined, undefined); + return factory.updateParameterDeclaration(node, undefined, node.dotDotDotToken, ts.isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, undefined, undefined, undefined); } - if (node.transformFlags & 32768) { - return factory.updateParameterDeclaration(node, undefined, undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + if (node.transformFlags & 65536) { + return factory.updateParameterDeclaration(node, undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); } @@ -80787,7 +82294,7 @@ var ts; if (parameters) { parameters.add(parameter); } - else if (parameter.transformFlags & 32768) { + else if (parameter.transformFlags & 65536) { parameters = new ts.Set(); } } @@ -80798,7 +82305,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateConstructorDeclaration(node, undefined, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateConstructorDeclaration(node, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -80808,7 +82315,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateGetAccessorDeclaration(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), undefined, transformFunctionBody(node)); + var updated = factory.updateGetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), undefined, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -80818,7 +82325,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateSetAccessorDeclaration(node, undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateSetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -80828,8 +82335,8 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateMethodDeclaration(node, undefined, enclosingFunctionFlags & 1 - ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + var updated = factory.updateMethodDeclaration(node, enclosingFunctionFlags & 1 + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifierLike) : node.modifiers, enclosingFunctionFlags & 2 ? undefined : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(undefined, visitor, ts.isToken), undefined, ts.visitParameterList(node.parameters, parameterVisitor, context), undefined, enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 @@ -80844,7 +82351,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateFunctionDeclaration(node, undefined, enclosingFunctionFlags & 1 + var updated = factory.updateFunctionDeclaration(node, enclosingFunctionFlags & 1 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 ? undefined @@ -80976,7 +82483,7 @@ var ts; statements = ts.append(statements, statement); } } - else if (parameter.transformFlags & 32768) { + else if (parameter.transformFlags & 65536) { containsPrecedingObjectRestOrSpread = true; var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, factory.getGeneratedNameForNode(parameter), false, true); if (ts.some(declarations)) { @@ -81428,7 +82935,7 @@ var ts; for (var _i = 0, _a = ts.arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries()); _i < _a.length; _i++) { var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1]; if (ts.isExternalModule(node)) { - var importStatement = factory.createImportDeclaration(undefined, undefined, factory.createImportClause(false, undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), undefined); + var importStatement = factory.createImportDeclaration(undefined, factory.createImportClause(false, undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), undefined); ts.setParentRecursive(importStatement, false); statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement); } @@ -81639,20 +83146,27 @@ var ts; if (node === undefined) { return factory.createTrue(); } - else if (node.kind === 10) { + if (node.kind === 10) { var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 288) { + if (node.kind === 288) { if (node.expression === undefined) { return factory.createTrue(); } return ts.visitNode(node.expression, visitor, ts.isExpression); } - else { - return ts.Debug.failBadSyntaxKind(node); + if (ts.isJsxElement(node)) { + return visitJsxElement(node, false); + } + if (ts.isJsxSelfClosingElement(node)) { + return visitJsxSelfClosingElement(node, false); + } + if (ts.isJsxFragment(node)) { + return visitJsxFragment(node, false); } + return ts.Debug.failBadSyntaxKind(node); } function visitJsxText(node) { var fixed = fixupWhitespaceAndDecodeEntities(node.text); @@ -82102,7 +83616,7 @@ var ts; && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 2097152 + return node.transformFlags & 4194304 && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -82405,7 +83919,7 @@ var ts; enableSubstitutionsForBlockScopedBindings(); } var extendsClauseElement = ts.getClassExtendsHeritageElement(node); - var classFunction = factory.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [factory.createParameterDeclaration(undefined, undefined, undefined, factory.createUniqueName("_super", 16 | 32))] : [], undefined, transformClassBody(node, extendsClauseElement)); + var classFunction = factory.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [factory.createParameterDeclaration(undefined, undefined, factory.createUniqueName("_super", 16 | 32))] : [], undefined, transformClassBody(node, extendsClauseElement)); ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536) | 524288); var inner = factory.createPartiallyEmittedExpression(classFunction); ts.setTextRangeEnd(inner, node.end); @@ -82451,7 +83965,7 @@ var ts; var ancestorFacts = enterSubtree(32662, 73); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - var constructorFunction = factory.createFunctionDeclaration(undefined, undefined, undefined, name, undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + var constructorFunction = factory.createFunctionDeclaration(undefined, undefined, name, undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); ts.setTextRange(constructorFunction, constructor || node); if (extendsClauseElement) { ts.setEmitFlags(constructorFunction, 8); @@ -82509,7 +84023,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, false); if (isDerivedClass || superCallExpression) { - if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 8192)) { + if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 16384)) { var superCall_1 = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); var returnStatement = factory.createReturnStatement(superCallExpression); ts.setCommentRange(returnStatement, ts.getCommentRange(superCall_1)); @@ -82582,10 +84096,10 @@ var ts; return undefined; } else if (ts.isBindingPattern(node.name)) { - return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(undefined, undefined, undefined, factory.getGeneratedNameForNode(node), undefined, undefined, undefined), node), node); + return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(undefined, undefined, factory.getGeneratedNameForNode(node), undefined, undefined, undefined), node), node); } else if (node.initializer) { - return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(undefined, undefined, undefined, node.name, undefined, undefined, undefined), node), node); + return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(undefined, undefined, node.name, undefined, undefined, undefined), node), node); } else { return node; @@ -82824,7 +84338,7 @@ var ts; return call; } function visitArrowFunction(node) { - if (node.transformFlags & 8192 && !(hierarchyFacts & 16384)) { + if (node.transformFlags & 16384 && !(hierarchyFacts & 16384)) { hierarchyFacts |= 65536; } var savedConvertedLoopState = convertedLoopState; @@ -82864,7 +84378,7 @@ var ts; : node.name; exitSubtree(ancestorFacts, 98304, 0); convertedLoopState = savedConvertedLoopState; - return factory.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, undefined, parameters, undefined, body); + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, undefined, parameters, undefined, body); } function transformFunctionLikeToExpression(node, location, name, container) { var savedConvertedLoopState = convertedLoopState; @@ -83028,7 +84542,7 @@ var ts; return updated; } function visitVariableDeclarationList(node) { - if (node.flags & 3 || node.transformFlags & 262144) { + if (node.flags & 3 || node.transformFlags & 524288) { if (node.flags & 3) { enableSubstitutionsForBlockScopedBindings(); } @@ -83039,7 +84553,7 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 262144 + if (node.transformFlags & 524288 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -83241,7 +84755,7 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 524288 && + if ((property.transformFlags & 1048576 && hierarchyFacts & 4) || (hasComputed = ts.Debug.checkDefined(property.name).kind === 162)) { numInitialProperties = i; @@ -83467,7 +84981,7 @@ var ts; } function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 524288) !== 0; + var containsYield = (node.initializer.transformFlags & 1048576) !== 0; var emitFlags = 0; if (currentState.containsLexicalThis) emitFlags |= 8; @@ -83511,7 +85025,7 @@ var ts; var loopBody = factory.createBlock(statements, true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 524288) !== 0; + var containsYield = (node.statement.transformFlags & 1048576) !== 0; var emitFlags = 524288; if (currentState.containsLexicalThis) emitFlags |= 8; @@ -83626,7 +85140,7 @@ var ts; } } else { - loopParameters.push(factory.createParameterDeclaration(undefined, undefined, undefined, name)); + loopParameters.push(factory.createParameterDeclaration(undefined, undefined, name)); var checkFlags = resolver.getNodeCheckFlags(decl); if (checkFlags & 4194304 || hasCapturedBindingsInForHead) { var outParamName = factory.createUniqueName("out_" + ts.idText(name)); @@ -83738,10 +85252,10 @@ var ts; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); if (node.kind === 172) { - updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + updated = factory.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); } else { - updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body); + updated = factory.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 98304, 0); convertedLoopState = savedConvertedLoopState; @@ -83821,7 +85335,7 @@ var ts; return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { - if (node.transformFlags & 16384 || + if (node.transformFlags & 32768 || node.expression.kind === 106 || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -83829,7 +85343,7 @@ var ts; ts.setEmitFlags(thisArg, 4); } var resultingCall = void 0; - if (node.transformFlags & 16384) { + if (node.transformFlags & 32768) { resultingCall = factory.createFunctionApplyCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 106 ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, true, false, false)); } else { @@ -84260,10 +85774,10 @@ var ts; case 247: return visitReturnStatement(node); default: - if (node.transformFlags & 524288) { + if (node.transformFlags & 1048576) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (2048 | 2097152)) { + else if (node.transformFlags & (2048 | 4194304)) { return ts.visitEachChild(node, visitor, context); } else { @@ -84307,7 +85821,7 @@ var ts; } function visitFunctionDeclaration(node) { if (node.asteriskToken) { - node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(undefined, node.modifiers, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body)), node), node); + node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(node.modifiers, undefined, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformGeneratorFunctionBody(node.body)), node), node); } else { var savedInGeneratorFunctionBody = inGeneratorFunctionBody; @@ -84401,7 +85915,7 @@ var ts; return ts.setTextRange(factory.createBlock(statements, body.multiLine), body); } function visitVariableStatement(node) { - if (node.transformFlags & 524288) { + if (node.transformFlags & 1048576) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -85074,7 +86588,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 524288) !== 0; + return !!node && (node.transformFlags & 1048576) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -85503,7 +87017,7 @@ var ts; currentExceptionBlock = undefined; withBlockStack = undefined; var buildResult = buildStatements(); - return emitHelpers().createGeneratorHelper(ts.setEmitFlags(factory.createFunctionExpression(undefined, undefined, undefined, undefined, [factory.createParameterDeclaration(undefined, undefined, undefined, state)], undefined, factory.createBlock(buildResult, buildResult.length > 0)), 524288)); + return emitHelpers().createGeneratorHelper(ts.setEmitFlags(factory.createFunctionExpression(undefined, undefined, undefined, undefined, [factory.createParameterDeclaration(undefined, undefined, state)], undefined, factory.createBlock(buildResult, buildResult.length > 0)), 524288)); } function buildStatements() { if (operations) { @@ -85804,7 +87318,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 4194304 || + node.transformFlags & 8388608 || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -85860,8 +87374,8 @@ var ts; jsonSourceFile ? jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory.createObjectLiteralExpression() : factory.createFunctionExpression(undefined, undefined, undefined, undefined, __spreadArray([ - factory.createParameterDeclaration(undefined, undefined, undefined, "require"), - factory.createParameterDeclaration(undefined, undefined, undefined, "exports") + factory.createParameterDeclaration(undefined, undefined, "require"), + factory.createParameterDeclaration(undefined, undefined, "exports") ], importAliasNames, true), undefined, transformAsynchronousModuleBody(node)) ], false))) ]), node.statements)); @@ -85871,7 +87385,7 @@ var ts; function transformUMDModule(node) { var _a = collectAsynchronousDependencies(node, false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions); - var umdHeader = factory.createFunctionExpression(undefined, undefined, undefined, undefined, [factory.createParameterDeclaration(undefined, undefined, undefined, "factory")], undefined, ts.setTextRange(factory.createBlock([ + var umdHeader = factory.createFunctionExpression(undefined, undefined, undefined, undefined, [factory.createParameterDeclaration(undefined, undefined, "factory")], undefined, ts.setTextRange(factory.createBlock([ factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([ factory.createVariableStatement(undefined, [ factory.createVariableDeclaration("v", undefined, undefined, factory.createCallExpression(factory.createIdentifier("factory"), undefined, [ @@ -85893,8 +87407,8 @@ var ts; var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([ factory.createExpressionStatement(factory.createCallExpression(umdHeader, undefined, [ factory.createFunctionExpression(undefined, undefined, undefined, undefined, __spreadArray([ - factory.createParameterDeclaration(undefined, undefined, undefined, "require"), - factory.createParameterDeclaration(undefined, undefined, undefined, "exports") + factory.createParameterDeclaration(undefined, undefined, "require"), + factory.createParameterDeclaration(undefined, undefined, "exports") ], importAliasNames, true), undefined, transformAsynchronousModuleBody(node)) ])) ]), node.statements)); @@ -85909,7 +87423,7 @@ var ts; var amdDependency = _a[_i]; if (amdDependency.name) { aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); - importAliasNames.push(factory.createParameterDeclaration(undefined, undefined, undefined, amdDependency.name)); + importAliasNames.push(factory.createParameterDeclaration(undefined, undefined, amdDependency.name)); } else { unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); @@ -85923,7 +87437,7 @@ var ts; if (includeNonAmdDependencies && importAliasName) { ts.setEmitFlags(importAliasName, 4); aliasedModuleNames.push(externalModuleName); - importAliasNames.push(factory.createParameterDeclaration(undefined, undefined, undefined, importAliasName)); + importAliasNames.push(factory.createParameterDeclaration(undefined, undefined, importAliasName)); } else { unaliasedModuleNames.push(externalModuleName); @@ -86010,7 +87524,7 @@ var ts; } } function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (4194304 | 4096 | 67108864))) { + if (!(node.transformFlags & (8388608 | 4096 | 268435456))) { return node; } switch (node.kind) { @@ -86151,7 +87665,7 @@ var ts; var externalModuleName = ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions); var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), visitor); var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 8192); + var containsLexicalThis = !!(node.transformFlags & 16384); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -86177,8 +87691,8 @@ var ts; var resolve = factory.createUniqueName("resolve"); var reject = factory.createUniqueName("reject"); var parameters = [ - factory.createParameterDeclaration(undefined, undefined, undefined, resolve), - factory.createParameterDeclaration(undefined, undefined, undefined, reject) + factory.createParameterDeclaration(undefined, undefined, resolve), + factory.createParameterDeclaration(undefined, undefined, reject) ]; var body = factory.createBlock([ factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), undefined, [factory.createArrayLiteralExpression([arg || factory.createOmittedExpression()]), resolve, reject])) @@ -86365,7 +87879,7 @@ var ts; function visitFunctionDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, visitor), undefined, ts.visitEachChild(node.body, visitor, context)), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, visitor), undefined, ts.visitEachChild(node.body, visitor, context)), node), node)); } else { statements = ts.append(statements, ts.visitEachChild(node, visitor, context)); @@ -86382,7 +87896,7 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, visitor), ts.visitNodes(node.members, visitor)), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), factory.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, visitor), ts.visitNodes(node.members, visitor)), node), node)); } else { statements = ts.append(statements, ts.visitEachChild(node, visitor, context)); @@ -86782,7 +88296,7 @@ var ts; var noSubstitution; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608)) { return node; } var id = ts.getOriginalNodeId(node); @@ -86795,8 +88309,8 @@ var ts; var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); var moduleBodyFunction = factory.createFunctionExpression(undefined, undefined, undefined, undefined, [ - factory.createParameterDeclaration(undefined, undefined, undefined, exportFunction), - factory.createParameterDeclaration(undefined, undefined, undefined, contextObject) + factory.createParameterDeclaration(undefined, undefined, exportFunction), + factory.createParameterDeclaration(undefined, undefined, contextObject) ], undefined, moduleBodyBlock); var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions); var dependencies = factory.createArrayLiteralExpression(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); @@ -86856,7 +88370,7 @@ var ts; ts.addRange(statements, hoistedStatements); ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); - var modifiers = node.transformFlags & 1048576 ? + var modifiers = node.transformFlags & 2097152 ? factory.createModifiersFromModifierFlags(256) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -86912,7 +88426,7 @@ var ts; if (localNames) { condition = factory.createLogicalAnd(condition, factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(localNames, "hasOwnProperty"), undefined, [n]))); } - return factory.createFunctionDeclaration(undefined, undefined, undefined, exportStarFunction, undefined, [factory.createParameterDeclaration(undefined, undefined, undefined, m)], undefined, factory.createBlock([ + return factory.createFunctionDeclaration(undefined, undefined, exportStarFunction, undefined, [factory.createParameterDeclaration(undefined, undefined, m)], undefined, factory.createBlock([ factory.createVariableStatement(undefined, factory.createVariableDeclarationList([ factory.createVariableDeclaration(exports, undefined, undefined, factory.createObjectLiteralExpression([])) ])), @@ -86967,7 +88481,7 @@ var ts; break; } } - setters.push(factory.createFunctionExpression(undefined, undefined, undefined, undefined, [factory.createParameterDeclaration(undefined, undefined, undefined, parameterName)], undefined, factory.createBlock(statements, true))); + setters.push(factory.createFunctionExpression(undefined, undefined, undefined, undefined, [factory.createParameterDeclaration(undefined, undefined, parameterName)], undefined, factory.createBlock(statements, true))); } return factory.createArrayLiteralExpression(setters, true); } @@ -87032,7 +88546,7 @@ var ts; } function visitFunctionDeclaration(node) { if (ts.hasSyntacticModifier(node, 1)) { - hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, visitor, ts.isBlock))); + hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.asteriskToken, factory.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, visitor, ts.isBlock))); } else { hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, visitor, context)); @@ -87050,7 +88564,7 @@ var ts; var statements; var name = factory.getLocalName(node); hoistVariableDeclaration(name); - statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, visitor, ts.isDecorator), undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)), node))), node)); + statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); @@ -87397,7 +88911,7 @@ var ts; return node; } function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (4096 | 4194304 | 67108864))) { + if (!(node.transformFlags & (4096 | 8388608 | 268435456))) { return node; } switch (node.kind) { @@ -87718,7 +89232,7 @@ var ts; function visitor(node) { switch (node.kind) { case 265: - return ts.getEmitScriptTarget(compilerOptions) >= ts.ModuleKind.ES2020 ? visitImportEqualsDeclaration(node) : undefined; + return ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.Node16 ? visitImportEqualsDeclaration(node) : undefined; case 271: return visitExportAssignment(node); case 272: @@ -87735,7 +89249,7 @@ var ts; } if (!importRequireStatements) { var createRequireName = factory.createUniqueName("_createRequire", 16 | 32); - var importStatement = factory.createImportDeclaration(undefined, undefined, factory.createImportClause(false, undefined, factory.createNamedImports([ + var importStatement = factory.createImportDeclaration(undefined, factory.createImportClause(false, undefined, factory.createNamedImports([ factory.createImportSpecifier(false, factory.createIdentifier("createRequire"), createRequireName) ])), factory.createStringLiteral("module")); var requireHelperName = factory.createUniqueName("__require", 16 | 32); @@ -87761,7 +89275,7 @@ var ts; } function appendExportsOfImportEqualsDeclaration(statements, node) { if (ts.hasSyntacticModifier(node, 1)) { - statements = ts.append(statements, factory.createExportDeclaration(undefined, undefined, node.isTypeOnly, factory.createNamedExports([factory.createExportSpecifier(false, undefined, ts.idText(node.name))]))); + statements = ts.append(statements, factory.createExportDeclaration(undefined, node.isTypeOnly, factory.createNamedExports([factory.createExportSpecifier(false, undefined, ts.idText(node.name))]))); } return statements; } @@ -87777,9 +89291,9 @@ var ts; } var oldIdentifier = node.exportClause.name; var synthName = factory.getGeneratedNameForNode(oldIdentifier); - var importDecl = factory.createImportDeclaration(undefined, undefined, factory.createImportClause(false, undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier, node.assertClause); + var importDecl = factory.createImportDeclaration(undefined, factory.createImportClause(false, undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier, node.assertClause); ts.setOriginalNode(importDecl, node.exportClause); - var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration(undefined, undefined, false, factory.createNamedExports([factory.createExportSpecifier(false, synthName, oldIdentifier)])); + var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration(undefined, false, factory.createNamedExports([factory.createExportSpecifier(false, synthName, oldIdentifier)])); ts.setOriginalNode(exportDecl, node); return [importDecl, exportDecl]; } @@ -88005,7 +89519,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.SyntaxKind[node.kind])); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(node.kind))); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 254 || node.kind === 203) { @@ -88202,7 +89716,7 @@ var ts; ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1; default: - return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.SyntaxKind[node.parent.kind])); + return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind))); } } function getTypeParameterConstraintVisibilityError() { @@ -88352,7 +89866,8 @@ var ts; trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, reportNonlocalAugmentation: reportNonlocalAugmentation, - reportNonSerializableProperty: reportNonSerializableProperty + reportNonSerializableProperty: reportNonSerializableProperty, + reportImportTypeNodeResolutionModeOverride: reportImportTypeNodeResolutionModeOverride, }; var errorNameNode; var errorFallbackNode; @@ -88474,6 +89989,11 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName)); } } + function reportImportTypeNodeResolutionModeOverride() { + if (!ts.isNightly() && (errorNameNode || errorFallbackNode)) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ @@ -88513,7 +90033,7 @@ var ts; resultHasExternalModuleIndicator = false; needsDeclare = false; var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(135)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], true, [], [], false, []); + var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([factory.createModifier(135)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], true, [], [], false, []); return newFile; } needsDeclare = true; @@ -88648,7 +90168,7 @@ var ts; }); return ret; } - function filterBindingPatternInitializers(name) { + function filterBindingPatternInitializersAndRenamings(name) { if (name.kind === 79) { return name; } @@ -88664,7 +90184,10 @@ var ts; if (elem.kind === 227) { return elem; } - return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + if (elem.propertyName && ts.isIdentifier(elem.propertyName) && ts.isIdentifier(elem.name) && !elem.symbol.isReferenced) { + return factory.updateBindingElement(elem, elem.dotDotDotToken, undefined, elem.propertyName, shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializersAndRenamings(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); } } function ensureParameter(p, modifierMask, type) { @@ -88673,7 +90196,7 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } - var newParam = factory.updateParameterDeclaration(p, undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57)) : undefined, ensureType(p, type || p.type, true), ensureNoInitializer(p)); + var newParam = factory.updateParameterDeclaration(p, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57)) : undefined, ensureType(p, type || p.type, true), ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } @@ -88719,7 +90242,7 @@ var ts; if (node.kind === 164 || node.kind === 167 || node.kind === 166) { - if (!node.initializer) + if (ts.isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } @@ -88801,7 +90324,7 @@ var ts; } } if (!newValueParameter) { - newValueParameter = factory.createParameterDeclaration(undefined, undefined, undefined, "value"); + newValueParameter = factory.createParameterDeclaration(undefined, undefined, "value"); } newParams = ts.append(newParams, newValueParameter); } @@ -88856,7 +90379,7 @@ var ts; return; if (decl.moduleReference.kind === 277) { var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); - return factory.updateImportEqualsDeclaration(decl, undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + return factory.updateImportEqualsDeclaration(decl, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } else { var oldDiag = getSymbolAccessibilityDiagnostic; @@ -88868,29 +90391,29 @@ var ts; } function transformImportDeclaration(decl) { if (!decl.importClause) { - return factory.updateImportDeclaration(decl, undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; if (!decl.importClause.namedBindings) { - return visibleDefaultBinding && factory.updateImportDeclaration(decl, undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return visibleDefaultBinding && factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } if (decl.importClause.namedBindings.kind === 268) { var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : undefined; - return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; + return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; } var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); if ((bindingList && bindingList.length) || visibleDefaultBinding) { - return factory.updateImportDeclaration(decl, undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } if (resolver.isImportRequiredByAugmentation(decl)) { - return factory.updateImportDeclaration(decl, undefined, decl.modifiers, undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } } function getResolutionModeOverrideForClauseInNightly(assertClause) { var mode = ts.getResolutionModeOverrideForClause(assertClause); if (mode !== undefined) { if (!ts.isNightly()) { - context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); } return assertClause; } @@ -88900,7 +90423,7 @@ var ts; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.Debug.formatSyntaxKind(i.kind))); } var priorNeedsDeclare = needsDeclare; needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); @@ -88956,7 +90479,7 @@ var ts; if (ts.hasEffectiveModifier(input, 8)) { if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; - return cleanup(factory.createPropertyDeclaration(undefined, ensureModifiers(input), input.name, undefined, undefined, undefined)); + return cleanup(factory.createPropertyDeclaration(ensureModifiers(input), input.name, undefined, undefined, undefined)); } } if (canProduceDiagnostic && !suppressNewDiagnosticContexts) { @@ -88985,14 +90508,14 @@ var ts; case 175: return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); case 171: { - var ctor = factory.createConstructorDeclaration(undefined, ensureModifiers(input), updateParamsList(input, input.parameters, 0), undefined); + var ctor = factory.createConstructorDeclaration(ensureModifiers(input), updateParamsList(input, input.parameters, 0), undefined); return cleanup(ctor); } case 169: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(undefined); } - var sig = factory.createMethodDeclaration(undefined, ensureModifiers(input), undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined); + var sig = factory.createMethodDeclaration(ensureModifiers(input), undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined); return cleanup(sig); } case 172: { @@ -89000,19 +90523,19 @@ var ts; return cleanup(undefined); } var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); - return cleanup(factory.updateGetAccessorDeclaration(input, undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8)), ensureType(input, accessorType), undefined)); + return cleanup(factory.updateGetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8)), ensureType(input, accessorType), undefined)); } case 173: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(undefined); } - return cleanup(factory.updateSetAccessorDeclaration(input, undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8)), undefined)); + return cleanup(factory.updateSetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8)), undefined)); } case 167: if (ts.isPrivateIdentifier(input.name)) { return cleanup(undefined); } - return cleanup(factory.updatePropertyDeclaration(input, undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); + return cleanup(factory.updatePropertyDeclaration(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); case 166: if (ts.isPrivateIdentifier(input.name)) { return cleanup(undefined); @@ -89028,7 +90551,7 @@ var ts; return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } case 176: { - return cleanup(factory.updateIndexSignature(input, undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130))); + return cleanup(factory.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130))); } case 254: { if (ts.isBindingPattern(input.name)) { @@ -89065,7 +90588,7 @@ var ts; return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.assertions, input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); } - default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.SyntaxKind[input.kind])); + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(input.kind))); } } if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) { @@ -89106,7 +90629,7 @@ var ts; resultHasExternalModuleIndicator = true; } resultHasScopeMarker = true; - return factory.updateExportDeclaration(input, undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); + return factory.updateExportDeclaration(input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); } case 271: { if (ts.isSourceFile(input.parent)) { @@ -89128,7 +90651,7 @@ var ts; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135)] : [], factory.createVariableDeclarationList([varDecl], 2)); preserveJsDoc(statement, input); ts.removeAllComments(input); - return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + return [statement, factory.updateExportAssignment(input, input.modifiers, newId)]; } } } @@ -89140,7 +90663,7 @@ var ts; if (ts.isImportEqualsDeclaration(statement) || ts.hasEffectiveModifier(statement, 512) || !ts.canHaveModifiers(statement)) { return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (125951 ^ 1)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (257023 ^ 1)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { @@ -89175,15 +90698,15 @@ var ts; var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 259: - return cleanup(factory.updateTypeAliasDeclaration(input, undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + return cleanup(factory.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 258: { - return cleanup(factory.updateInterfaceDeclaration(input, undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + return cleanup(factory.updateInterfaceDeclaration(input, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 256: { - var clean = cleanup(factory.updateFunctionDeclaration(input, undefined, ensureModifiers(input), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + var clean = cleanup(factory.updateFunctionDeclaration(input, ensureModifiers(input), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); if (clean && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { var props = resolver.getPropertiesOfContainerFunction(input); - var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(undefined, undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16); + var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16); ts.setParent(fakespace_1, enclosingDeclaration); fakespace_1.locals = ts.createSymbolTable(props); fakespace_1.symbol = props[0].parent; @@ -89208,19 +90731,19 @@ var ts; declarations = ts.mapDefined(declarations, function (declaration) { return factory.updateModifiers(declaration, 0); }); } else { - declarations.push(factory.createExportDeclaration(undefined, undefined, false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) { + declarations.push(factory.createExportDeclaration(undefined, false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) { var gen = _a[0], exp = _a[1]; return factory.createExportSpecifier(false, gen, exp); })))); } - var namespaceDecl = factory.createModuleDeclaration(undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16); + var namespaceDecl = factory.createModuleDeclaration(ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16); if (!ts.hasEffectiveModifier(clean, 512)) { return [clean, namespaceDecl]; } var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513) | 2); - var cleanDeclaration = factory.updateFunctionDeclaration(clean, undefined, modifiers, undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, undefined); - var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, undefined, modifiers, namespaceDecl.name, namespaceDecl.body); - var exportDefaultDeclaration = factory.createExportAssignment(undefined, undefined, false, namespaceDecl.name); + var cleanDeclaration = factory.updateFunctionDeclaration(clean, modifiers, undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, undefined); + var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, modifiers, namespaceDecl.name, namespaceDecl.body); + var exportDefaultDeclaration = factory.createExportAssignment(undefined, false, namespaceDecl.name); if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; } @@ -89257,7 +90780,7 @@ var ts; needsScopeFixMarker = oldNeedsScopeFix; resultHasScopeMarker = oldHasScopeFix; var mods = ensureModifiers(input); - return cleanup(factory.updateModuleDeclaration(input, undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; @@ -89267,7 +90790,7 @@ var ts; var id = ts.getOriginalNodeId(inner); var body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); - return cleanup(factory.updateModuleDeclaration(input, undefined, mods, input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, input.name, body)); } } case 257: { @@ -89284,7 +90807,7 @@ var ts; return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 79) { - return preserveJsDoc(factory.createPropertyDeclaration(undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + return preserveJsDoc(factory.createPropertyDeclaration(ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } else { return walkBindingPattern(param.name); @@ -89299,7 +90822,7 @@ var ts; elems = ts.concatenate(elems, walkBindingPattern(elem.name)); } elems = elems || []; - elems.push(factory.createPropertyDeclaration(undefined, ensureModifiers(param), elem.name, undefined, ensureType(elem, undefined), undefined)); + elems.push(factory.createPropertyDeclaration(ensureModifiers(param), elem.name, undefined, ensureType(elem, undefined), undefined)); } return elems; } @@ -89308,7 +90831,7 @@ var ts; } var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); }); var privateIdentifier = hasPrivateIdentifier ? [ - factory.createPropertyDeclaration(undefined, undefined, factory.createPrivateIdentifier("#private"), undefined, undefined, undefined) + factory.createPropertyDeclaration(undefined, factory.createPrivateIdentifier("#private"), undefined, undefined, undefined) ] : undefined; var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree)); var members = factory.createNodeArray(memberNodes); @@ -89333,18 +90856,18 @@ var ts; } return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 104; })), visitDeclarationSubtree)); })); - return [statement, cleanup(factory.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; + return [statement, cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members))]; } else { var heritageClauses = transformHeritageClauses(input.heritageClauses); - return cleanup(factory.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + return cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members)); } } case 237: { return cleanup(transformVariableStatement(input)); } case 260: { - return cleanup(factory.updateEnumDeclaration(input, undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(factory.updateEnumDeclaration(input, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; var constValue = resolver.getConstantValue(m); @@ -89352,7 +90875,7 @@ var ts; })))); } } - return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.SyntaxKind[input.kind])); + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.Debug.formatSyntaxKind(input.kind))); function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; @@ -89426,12 +90949,12 @@ var ts; var currentFlags = ts.getEffectiveModifierFlags(node); var newFlags = ensureModifierFlags(node); if (currentFlags === newFlags) { - return node.modifiers; + return ts.visitArray(node.modifiers, function (n) { return ts.tryCast(n, ts.isModifier); }, ts.isModifier); } return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 125951 ^ (4 | 256 | 16384); + var mask = 257023 ^ (4 | 256 | 16384); var additions = (needsDeclare && !isAlwaysType(node)) ? 2 : 0; var parentIsFile = node.parent.kind === 305; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { @@ -89469,7 +90992,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 125951 ^ 4; } + if (modifierMask === void 0) { modifierMask = 257023 ^ 4; } if (modifierAdditions === void 0) { modifierAdditions = 0; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 && !(flags & 1)) { @@ -89576,6 +91099,7 @@ var ts; var transformers = []; ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory)); transformers.push(ts.transformTypeScript); + transformers.push(ts.transformLegacyDecorators); transformers.push(ts.transformClassFields); if (ts.getJSXTransformEnabled(compilerOptions)) { transformers.push(ts.transformJsx); @@ -90220,7 +91744,6 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; - var exportedModulesFromDeclarationEmit; enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); exit(); @@ -90229,7 +91752,6 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, - exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath; @@ -90282,13 +91804,14 @@ var ts; return; } var version = ts.version; - ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), false); + var buildInfo = { bundle: bundle, program: program, version: version }; + ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText(buildInfo), false, undefined, { buildInfo: buildInfo }); } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) { if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) { return; } - if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit) { emitSkipped = true; return; } @@ -90313,7 +91836,7 @@ var ts; substituteNode: transform.substituteNode, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, compilerOptions); transform.dispose(); if (bundleBuildInfo) bundleBuildInfo.js = printer.bundleFileInfo; @@ -90345,7 +91868,7 @@ var ts; noEmitHelpers: true, module: compilerOptions.module, target: compilerOptions.target, - sourceMap: compilerOptions.sourceMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, inlineSourceMap: compilerOptions.inlineSourceMap, extendedDiagnostics: compilerOptions.extendedDiagnostics, onlyPrintJsDocStyle: true, @@ -90363,16 +91886,12 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: !forceDtsEmit && compilerOptions.declarationMap, + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform, declarationPrinter, { + sourceMap: printerOptions.sourceMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 305) { - var sourceFile = declarationTransform.transformed[0]; - exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; - } } declarationTransform.dispose(); if (bundleBuildInfo) @@ -90391,7 +91910,8 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, mapOptions) { + var sourceFileOrBundle = transform.transformed[0]; var bundle = sourceFileOrBundle.kind === 306 ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 305 ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; @@ -90423,12 +91943,17 @@ var ts; if (sourceMapFilePath) { var sourceMap = sourceMapGenerator.toString(); ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, false, sourceFiles); + if (printer.bundleFileInfo) + printer.bundleFileInfo.mapHash = ts.computeSignature(sourceMap, ts.maybeBind(host, host.createHash)); } } else { writer.writeLine(); } - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos }); + var text = writer.getText(); + ts.writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos, diagnostics: transform.diagnostics }); + if (printer.bundleFileInfo) + printer.bundleFileInfo.hash = ts.computeSignature(text, ts.maybeBind(host, host.createHash)); writer.clear(); } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { @@ -90553,30 +92078,50 @@ var ts; }); } function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) { + var createHash = ts.maybeBind(host, host.createHash); var _a = getOutputPathsForBundle(config.options, false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath)); - if (!buildInfoText) + var buildInfo; + if (host.getBuildInfo) { + var hostBuildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); + if (!hostBuildInfo) + return buildInfoPath; + buildInfo = hostBuildInfo; + } + else { + var buildInfoText = host.readFile(buildInfoPath); + if (!buildInfoText) + return buildInfoPath; + buildInfo = getBuildInfo(buildInfoText); + } + if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationFilePath && !buildInfo.bundle.dts)) return buildInfoPath; var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath)); if (!jsFileText) return jsFilePath; + if (ts.computeSignature(jsFileText, createHash) !== buildInfo.bundle.js.hash) + return jsFilePath; var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap) return sourceMapFilePath || "inline sourcemap decoding"; + if (sourceMapFilePath && ts.computeSignature(sourceMapText, createHash) !== buildInfo.bundle.js.mapHash) + return sourceMapFilePath; var declarationText = declarationFilePath && host.readFile(declarationFilePath); if (declarationFilePath && !declarationText) return declarationFilePath; + if (declarationFilePath && ts.computeSignature(declarationText, createHash) !== buildInfo.bundle.dts.hash) + return declarationFilePath; var declarationMapText = declarationMapPath && host.readFile(declarationMapPath); if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding"; - var buildInfo = getBuildInfo(buildInfoText); - if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts)) - return buildInfoPath; + if (declarationMapPath && ts.computeSignature(declarationMapText, createHash) !== buildInfo.bundle.dts.mapHash) + return declarationMapPath; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, true); var outputFiles = []; var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); }); var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host); + var changedDtsText; + var changedDtsData; var emitHost = { getPrependNodes: ts.memoize(function () { return __spreadArray(__spreadArray([], prependNodes, true), [ownPrependInput], false); }), getCanonicalFileName: host.getCanonicalFileName, @@ -90592,7 +92137,7 @@ var ts; getResolvedProjectReferenceToRedirect: ts.returnUndefined, getProjectReferenceRedirect: ts.returnUndefined, isSourceOfProjectReferenceRedirect: ts.returnFalse, - writeFile: function (name, text, writeByteOrderMark) { + writeFile: function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { switch (name) { case jsFilePath: if (jsFileText === text) @@ -90603,19 +92148,24 @@ var ts; return; break; case buildInfoPath: - var newBuildInfo = getBuildInfo(text); + var newBuildInfo = data.buildInfo; newBuildInfo.program = buildInfo.program; + if (newBuildInfo.program && changedDtsText !== undefined && config.options.composite) { + newBuildInfo.program.outSignature = ts.computeSignature(changedDtsText, createHash, changedDtsData); + } var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles; newBuildInfo.bundle.js.sources = js.sources; if (dts) { newBuildInfo.bundle.dts.sources = dts.sources; } newBuildInfo.bundle.sourceFiles = sourceFiles; - outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark }); + outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark, buildInfo: newBuildInfo }); return; case declarationFilePath: if (declarationText === text) return; + changedDtsText = text; + changedDtsData = data; break; case declarationMapPath: if (declarationMapText === text) @@ -90634,6 +92184,7 @@ var ts; getSourceFileFromReference: ts.returnUndefined, redirectTargetsMap: ts.createMultiMap(), getFileIncludeReasons: ts.notImplemented, + createHash: createHash, }; emitFiles(ts.notImplementedResolver, emitHost, undefined, ts.getTransformers(config.options, customTransformers)); return outputFiles; @@ -91628,8 +93179,7 @@ var ts; } } function emitParameter(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); @@ -91639,14 +93189,13 @@ var ts; else { emitTypeAnnotation(node.type); } - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } function emitPropertySignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); @@ -91654,8 +93203,7 @@ var ts; writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); emit(node.exclamationToken); @@ -91665,7 +93213,6 @@ var ts; } function emitMethodSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); @@ -91676,16 +93223,13 @@ var ts; popNameGenerationScope(node); } function emitMethodDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.asteriskToken); emit(node.name); emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitClassStaticBlockDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("static"); emitBlockFunctionBody(node.body); } @@ -91695,8 +93239,7 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword(node.kind === 172 ? "get" : "set"); writeSpace(); emit(node.name); @@ -91704,8 +93247,6 @@ var ts; } function emitCallSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); @@ -91714,8 +93255,6 @@ var ts; } function emitConstructSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -91725,7 +93264,6 @@ var ts; popNameGenerationScope(node); } function emitIndexSignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); @@ -92102,7 +93640,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitSignatureAndBody(node, emitArrowFunctionHead); } @@ -92553,7 +94090,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitFunctionDeclarationOrExpression(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); emit(node.asteriskToken); @@ -92605,8 +94141,8 @@ var ts; if (!ts.nodeIsSynthesized(body) && currentSourceFile && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { return false; } - if (getLeadingLineTerminatorCount(body, body.statements, 2) - || getClosingLineTerminatorCount(body, body.statements, 2)) { + if (getLeadingLineTerminatorCount(body, ts.firstOrUndefined(body.statements), 2) + || getClosingLineTerminatorCount(body, ts.lastOrUndefined(body.statements), 2, body.statements)) { return false; } var previousStatement; @@ -92653,8 +94189,7 @@ var ts; } function emitClassDeclarationOrExpression(node) { ts.forEach(node.members, generateMemberNames); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword("class"); if (node.name) { writeSpace(); @@ -92675,7 +94210,6 @@ var ts; } } function emitInterfaceDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("interface"); writeSpace(); @@ -92688,7 +94222,6 @@ var ts; writePunctuation("}"); } function emitTypeAliasDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("type"); writeSpace(); @@ -93282,8 +94815,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference", data: directive.fileName }); writeLine(); } - for (var _d = 0, types_24 = types; _d < types_24.length; _d++) { - var directive = types_24[_d]; + for (var _d = 0, types_23 = types; _d < types_23.length; _d++) { + var directive = types_23[_d]; var pos = writer.getTextPos(); var resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.impliedNodeFormat) ? "resolution-mode=\"".concat(directive.resolutionMode === ts.ModuleKind.ESNext ? "import" : "require", "\"") @@ -93447,12 +94980,47 @@ var ts; emit(node); write = savedWrite; } - function emitModifiers(node, modifiers) { - if (modifiers && modifiers.length) { - emitList(node, modifiers, 262656); - writeSpace(); + function emitDecoratorsAndModifiers(node, modifiers) { + if (modifiers === null || modifiers === void 0 ? void 0 : modifiers.length) { + if (ts.every(modifiers, ts.isModifier)) { + return emitModifiers(node, modifiers); + } + if (ts.every(modifiers, ts.isDecorator)) { + return emitDecorators(node, modifiers); + } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(modifiers); + var lastMode = void 0; + var mode = void 0; + var start = 0; + var pos = 0; + while (start < modifiers.length) { + while (pos < modifiers.length) { + var modifier = modifiers[pos]; + mode = ts.isDecorator(modifier) ? "decorators" : "modifiers"; + if (lastMode === undefined) { + lastMode = mode; + } + else if (mode !== lastMode) { + break; + } + pos++; + } + var textRange = { pos: -1, end: -1 }; + if (start === 0) + textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) + textRange.end = modifiers.end; + emitNodeListItems(emit, node, modifiers, lastMode === "modifiers" ? 2359808 : 2146305, undefined, start, pos - start, false, textRange); + start = pos; + lastMode = mode; + pos++; + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(modifiers); } } + function emitModifiers(node, modifiers) { + emitList(node, modifiers, 2359808); + } function emitTypeAnnotation(node) { if (node) { writePunctuation(":"); @@ -93530,10 +95098,8 @@ var ts; && parameter.pos === parentNode.pos && ts.isArrowFunction(parentNode) && !parentNode.type - && !ts.some(parentNode.decorators) && !ts.some(parentNode.modifiers) && !ts.some(parentNode.typeParameters) - && !ts.some(parameter.decorators) && !ts.some(parameter.modifiers) && !parameter.dotDotDotToken && !parameter.questionToken @@ -93589,12 +95155,8 @@ var ts; } var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 32768) { - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); return; } if (format & 15360) { @@ -93603,9 +95165,7 @@ var ts; emitTrailingCommentsOfPosition(children.pos, true); } } - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); if (isEmpty) { if (format & 1 && !(preserveSourceNewlines && (!parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { writeLine(); @@ -93615,99 +95175,99 @@ var ts; } } else { - ts.Debug.type(children); - var mayEmitInterveningComments = (format & 262144) === 0; - var shouldEmitInterveningComments = mayEmitInterveningComments; - var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); - if (leadingLineTerminatorCount) { - writeLine(leadingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (format & 256) { - writeSpace(); + emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, children.hasTrailingComma, children); + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); + if (format & 15360) { + if (isEmpty && children) { + emitLeadingCommentsOfPosition(children.end); } - if (format & 128) { - increaseIndent(); + writePunctuation(getClosingBracket(format)); + } + } + function emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, hasTrailingComma, childrenTextRange) { + var mayEmitInterveningComments = (format & 262144) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children[start], format); + if (leadingLineTerminatorCount) { + writeLine(leadingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (format & 256) { + writeSpace(); + } + if (format & 128) { + increaseIndent(); + } + var emitListItem = getEmitListItem(emit, parenthesizerRule); + var previousSibling; + var previousSourceFileTextKind; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + if (format & 32) { + writeLine(); + writeDelimiter(format); } - var emitListItem = getEmitListItem(emit, parenthesizerRule); - var previousSibling = void 0; - var previousSourceFileTextKind = void 0; - var shouldDecreaseIndentAfterEmit = false; - for (var i = 0; i < count; i++) { - var child = children[start + i]; - if (format & 32) { - writeLine(); - writeDelimiter(format); - } - else if (previousSibling) { - if (format & 60 && previousSibling.end !== (parentNode ? parentNode.end : -1)) { - emitLeadingCommentsOfPosition(previousSibling.end); - } - writeDelimiter(format); - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); - if (separatingLineTerminatorCount > 0) { - if ((format & (3 | 128)) === 0) { - increaseIndent(); - shouldDecreaseIndentAfterEmit = true; - } - writeLine(separatingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (previousSibling && format & 512) { - writeSpace(); - } - } - previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); - if (shouldEmitInterveningComments) { - var commentRange = ts.getCommentRange(child); - emitTrailingCommentsOfPosition(commentRange.pos); + else if (previousSibling) { + if (format & 60 && previousSibling.end !== (parentNode ? parentNode.end : -1)) { + emitLeadingCommentsOfPosition(previousSibling.end); } - else { - shouldEmitInterveningComments = mayEmitInterveningComments; + writeDelimiter(format); + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); + if (separatingLineTerminatorCount > 0) { + if ((format & (3 | 128)) === 0) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(separatingLineTerminatorCount); + shouldEmitInterveningComments = false; } - nextListElementPos = child.pos; - emitListItem(child, emit, parenthesizerRule, i); - if (shouldDecreaseIndentAfterEmit) { - decreaseIndent(); - shouldDecreaseIndentAfterEmit = false; + else if (previousSibling && format & 512) { + writeSpace(); } - previousSibling = child; } - var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; - var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024); - var hasTrailingComma = (children === null || children === void 0 ? void 0 : children.hasTrailingComma) && (format & 64) && (format & 16); - if (hasTrailingComma) { - if (previousSibling && !skipTrailingComments) { - emitTokenWithComment(27, previousSibling.end, writePunctuation, previousSibling); - } - else { - writePunctuation(","); - } + previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); + if (shouldEmitInterveningComments) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); } - if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60) && !skipTrailingComments) { - emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); + else { + shouldEmitInterveningComments = mayEmitInterveningComments; } - if (format & 128) { + nextListElementPos = child.pos; + emitListItem(child, emit, parenthesizerRule, i); + if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; } - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format); - if (closingLineTerminatorCount) { - writeLine(closingLineTerminatorCount); + previousSibling = child; + } + var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; + var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024); + var emitTrailingComma = hasTrailingComma && (format & 64) && (format & 16); + if (emitTrailingComma) { + if (previousSibling && !skipTrailingComments) { + emitTokenWithComment(27, previousSibling.end, writePunctuation, previousSibling); } - else if (format & (2097152 | 256)) { - writeSpace(); + else { + writePunctuation(","); } } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60) && !skipTrailingComments) { + emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange === null || childrenTextRange === void 0 ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end); } - if (format & 15360) { - if (isEmpty && children) { - emitLeadingCommentsOfPosition(children.end); - } - writePunctuation(getClosingBracket(format)); + if (format & 128) { + decreaseIndent(); + } + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children[start + count - 1], format, childrenTextRange); + if (closingLineTerminatorCount) { + writeLine(closingLineTerminatorCount); + } + else if (format & (2097152 | 256)) { + writeSpace(); } } function writeLiteral(s) { @@ -93831,31 +95391,30 @@ var ts; decreaseIndent(); } } - function getLeadingLineTerminatorCount(parentNode, children, format) { + function getLeadingLineTerminatorCount(parentNode, firstChild, format) { if (format & 2 || preserveSourceNewlines) { if (format & 65536) { return 1; } - var firstChild_1 = children[0]; - if (firstChild_1 === undefined) { + if (firstChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (firstChild_1.pos === nextListElementPos) { + if (firstChild.pos === nextListElementPos) { return 0; } - if (firstChild_1.kind === 11) { + if (firstChild.kind === 11) { return 0; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && - !ts.nodeIsSynthesized(firstChild_1) && - (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { + !ts.nodeIsSynthesized(firstChild) && + (!firstChild.parent || ts.getOriginalNode(firstChild.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild.pos, parentNode.pos, currentSourceFile, includeComments); }); } - return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; + return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; } - if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) { + if (synthesizedNodeStartsOnNewLine(firstChild, format)) { return 1; } } @@ -93887,18 +95446,17 @@ var ts; } return format & 1 ? 1 : 0; } - function getClosingLineTerminatorCount(parentNode, children, format) { + function getClosingLineTerminatorCount(parentNode, lastChild, format, childrenTextRange) { if (format & 2 || preserveSourceNewlines) { if (format & 65536) { return 1; } - var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { - var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; + var end_1 = childrenTextRange && !ts.positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; @@ -93921,14 +95479,14 @@ var ts; return lines; } function writeLineSeparatorsAndIndentBefore(node, parent) { - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0); + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, node, 0); if (leadingNewlines) { writeLinesAndIndent(leadingNewlines, false); } return !!leadingNewlines; } function writeLineSeparatorsAfter(node, parent) { - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0); + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, node, 0, undefined); if (trailingNewlines) { writeLine(trailingNewlines); } @@ -95258,7 +96816,6 @@ var ts; if (system === void 0) { system = ts.sys; } var existingDirectories = new ts.Map(); var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); - var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash; function getSourceFile(fileName, languageVersionOrOptions, onError) { var text; try { @@ -95288,7 +96845,7 @@ var ts; function writeFile(fileName, data, writeByteOrderMark, onError) { try { ts.performance.mark("beforeIOWrite"); - ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -95298,34 +96855,6 @@ var ts; } } } - var outputFingerprints; - function writeFileWorker(fileName, data, writeByteOrderMark) { - if (!ts.isWatchSet(options) || !system.getModifiedTime) { - system.writeFile(fileName, data, writeByteOrderMark); - return; - } - if (!outputFingerprints) { - outputFingerprints = new ts.Map(); - } - var hash = computeHash(data); - var mtimeBefore = system.getModifiedTime(fileName); - if (mtimeBefore) { - var fingerprint = outputFingerprints.get(fileName); - if (fingerprint && - fingerprint.byteOrderMark === writeByteOrderMark && - fingerprint.hash === hash && - fingerprint.mtime.getTime() === mtimeBefore.getTime()) { - return; - } - } - system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; - outputFingerprints.set(fileName, { - hash: hash, - byteOrderMark: writeByteOrderMark, - mtime: mtimeAfter - }); - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -95428,7 +96957,7 @@ var ts; originalWriteFile.call.apply(originalWriteFile, __spreadArray([host, fileName, data], rest, false)); }; } - if (originalDirectoryExists && originalCreateDirectory) { + if (originalDirectoryExists) { host.directoryExists = function (directory) { var key = toPath(directory); var value = directoryExistsCache.get(key); @@ -95438,11 +96967,13 @@ var ts; directoryExistsCache.set(key, !!newValue); return newValue; }; - host.createDirectory = function (directory) { - var key = toPath(directory); - directoryExistsCache.delete(key); - originalCreateDirectory.call(host, directory); - }; + if (originalCreateDirectory) { + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } } return { originalReadFile: originalReadFile, @@ -95875,6 +97406,11 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, options) { + var result = getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options); + return typeof result === "object" ? result.impliedNodeFormat : result; + } + ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) { switch (ts.getEmitModuleResolutionKind(options)) { case ts.ModuleResolutionKind.Node16: case ts.ModuleResolutionKind.NodeNext: @@ -95886,11 +97422,16 @@ var ts; return undefined; } function lookupFromPackageJson() { - var scope = ts.getPackageScopeForPath(fileName, packageJsonInfoCache, host, options); - return (scope === null || scope === void 0 ? void 0 : scope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + var state = ts.getTemporaryModuleResolutionState(packageJsonInfoCache, host, options); + var packageJsonLocations = []; + state.failedLookupLocations = packageJsonLocations; + state.affectingLocations = packageJsonLocations; + var packageJsonScope = ts.getPackageScopeForPath(fileName, state); + var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope }; } } - ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + ts.getImpliedNodeFormatForFileWorker = getImpliedNodeFormatForFileWorker; ts.plainJSErrors = new ts.Set([ ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0.code, ts.Diagnostics.A_module_cannot_have_multiple_default_exports.code, @@ -95980,6 +97521,9 @@ var ts; ts.Diagnostics.extends_clause_already_seen.code, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + ts.Diagnostics.Class_constructor_may_not_be_a_generator.code, + ts.Diagnostics.Class_constructor_may_not_be_an_accessor.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]); function shouldProgramCreateNewSourceFiles(program, newOptions) { if (!program) @@ -96165,7 +97709,7 @@ var ts; for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); - if (shouldCreateNewSourceFile || !newFile || + if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } @@ -96495,7 +98039,7 @@ var ts; }); } function tryReuseStructureFromOldProgram() { - var _a; + var _a, _b; if (!oldProgram) { return 0; } @@ -96523,12 +98067,15 @@ var ts; var seenPackageNames = new ts.Map(); for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; + var sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options); var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), undefined, shouldCreateNewSourceFile); + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, sourceFileOptions, undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat) + : host.getSourceFile(oldSourceFile.fileName, sourceFileOptions, undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat); if (!newSourceFile) { return 0; } + newSourceFile.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope; ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); var fileChanged = void 0; if (oldSourceFile.redirectInfo) { @@ -96561,27 +98108,32 @@ var ts; seenPackageNames.set(packageName, newKind); } if (fileChanged) { - if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { - structureIsReused = 1; - } - if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + if (oldSourceFile.impliedNodeFormat !== newSourceFile.impliedNodeFormat) { structureIsReused = 1; } - if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { structureIsReused = 1; } - collectExternalModuleReferences(newSourceFile); - if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + else if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { structureIsReused = 1; } - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { structureIsReused = 1; } - if ((oldSourceFile.flags & 6291456) !== (newSourceFile.flags & 6291456)) { - structureIsReused = 1; - } - if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - structureIsReused = 1; + else { + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + structureIsReused = 1; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + structureIsReused = 1; + } + else if ((oldSourceFile.flags & 6291456) !== (newSourceFile.flags & 6291456)) { + structureIsReused = 1; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + structureIsReused = 1; + } } modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); } @@ -96595,17 +98147,17 @@ var ts; return structureIsReused; } var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); - for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) { - var oldFile = oldSourceFiles_3[_b]; + for (var _c = 0, oldSourceFiles_3 = oldSourceFiles; _c < oldSourceFiles_3.length; _c++) { + var oldFile = oldSourceFiles_3[_c]; if (!ts.contains(modifiedFiles, oldFile)) { - for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) { - var moduleName = _d[_c]; + for (var _d = 0, _e = oldFile.ambientModuleNames; _d < _e.length; _d++) { + var moduleName = _e[_d]; ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); } } } - for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) { - var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile; + for (var _f = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _f < modifiedSourceFiles_1.length; _f++) { + var _g = modifiedSourceFiles_1[_f], oldSourceFile = _g.oldFile, newSourceFile = _g.newFile; var moduleNames = getModuleNames(newSourceFile); var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, oldSourceFile, ts.moduleResolutionIsEqualTo); @@ -96630,13 +98182,13 @@ var ts; if (structureIsReused !== 2) { return structureIsReused; } - if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host))) { + if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_b = host.hasChangedAutomaticTypeDirectiveNames) === null || _b === void 0 ? void 0 : _b.call(host))) { return 1; } missingFilePaths = oldProgram.getMissingFilePaths(); ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); - for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) { - var newSourceFile = newSourceFiles_1[_g]; + for (var _h = 0, newSourceFiles_1 = newSourceFiles; _h < newSourceFiles_1.length; _h++) { + var newSourceFile = newSourceFiles_1[_h]; filesByName.set(newSourceFile.path, newSourceFile); } var oldFilesByNameMap = oldProgram.getFilesByNameMap(); @@ -96695,6 +98247,7 @@ var ts; getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); }, redirectTargetsMap: redirectTargetsMap, getFileIncludeReasons: program.getFileIncludeReasons, + createHash: ts.maybeBind(host, host.createHash), }; } function writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data) { @@ -97007,7 +98560,7 @@ var ts; } } function walkArray(nodes, parent) { - if (parent.decorators === nodes && !options.experimentalDecorators) { + if (ts.canHaveModifiers(parent) && parent.modifiers === nodes && ts.some(nodes, ts.isDecorator) && !options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { @@ -97034,7 +98587,7 @@ var ts; if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 124) { + if (ts.isModifier(modifier) && modifier.kind !== 124) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); } } @@ -97042,7 +98595,7 @@ var ts; } break; case 164: - if (nodes === parent.modifiers) { + if (nodes === parent.modifiers && ts.some(nodes, ts.isModifier)) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -97154,7 +98707,7 @@ var ts; } function createSyntheticImport(text, file) { var externalHelpersModuleReference = ts.factory.createStringLiteral(text); - var importDecl = ts.factory.createImportDeclaration(undefined, undefined, undefined, externalHelpersModuleReference, undefined); + var importDecl = ts.factory.createImportDeclaration(undefined, undefined, externalHelpersModuleReference, undefined); ts.addEmitFlags(importDecl, 67108864); ts.setParent(externalHelpersModuleReference, importDecl); ts.setParent(importDecl, file); @@ -97335,13 +98888,16 @@ var ts; addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) { + var _a; var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; redirect.resolvedPath = resolvedPath; redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + redirect.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + redirect.packageJsonScope = sourceFileOptions.packageJsonScope; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { @@ -97366,14 +98922,14 @@ var ts; return result; } function getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options) { - var impliedNodeFormat = getImpliedNodeFormatForFile(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); - return { - languageVersion: ts.getEmitScriptTarget(options), - impliedNodeFormat: impliedNodeFormat, - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(options) - }; + var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); + var languageVersion = ts.getEmitScriptTarget(options); + var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options); + return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) : + { languageVersion: languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator }; } function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { + var _a, _b; var path = toPath(fileName); if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(path); @@ -97443,12 +98999,13 @@ var ts; redirectedPath = toPath(redirect); } } - var file = host.getSourceFile(fileName, getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options), function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile); + var sourceFileOptions = getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options); + var file = host.getSourceFile(fileName, sourceFileOptions, function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile || (((_a = oldProgram === null || oldProgram === void 0 ? void 0 : oldProgram.getSourceFileByPath(toPath(fileName))) === null || _a === void 0 ? void 0 : _a.impliedNodeFormat) !== sourceFileOptions.impliedNodeFormat)); if (packageId) { var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName, sourceFileOptions); redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, redirectedPath); addFileIncludeReason(dupFile, reason); @@ -97468,6 +99025,8 @@ var ts; file.path = path; file.resolvedPath = toPath(fileName); file.originalFileName = originalFileName; + file.packageJsonLocations = ((_b = sourceFileOptions.packageJsonLocations) === null || _b === void 0 ? void 0 : _b.length) ? sourceFileOptions.packageJsonLocations : undefined; + file.packageJsonScope = sourceFileOptions.packageJsonScope; addFileIncludeReason(file, reason); if (host.useCaseSensitiveFileNames()) { var pathLowerCase = ts.toFileNameLowerCase(path); @@ -97594,13 +99153,13 @@ var ts; ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); var mode = ref.resolutionMode || file.impliedNodeFormat; if (mode && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { - programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); + programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); } processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, }); } } function processTypeReferenceDirective(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -98044,7 +99603,7 @@ var ts; fileIncludeReasons = undefined; var location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason); var fileIncludeReasonDetails = fileIncludeReasons && ts.chainDiagnosticMessages(fileIncludeReasons, ts.Diagnostics.The_file_is_in_the_program_because_Colon); - var redirectInfo = file && ts.explainIfFileIsRedirect(file); + var redirectInfo = file && ts.explainIfFileIsRedirectAndImpliedFormat(file); var chain = ts.chainDiagnosticMessages.apply(void 0, __spreadArray([redirectInfo ? fileIncludeReasonDetails ? __spreadArray([fileIncludeReasonDetails], redirectInfo, true) : redirectInfo : fileIncludeReasonDetails, diagnostic], args || ts.emptyArray, false)); return location && isReferenceFileLocation(location) ? ts.createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : @@ -98111,7 +99670,7 @@ var ts; break; } var matchedByInclude = ts.getMatchedIncludeSpec(program, fileName); - if (!matchedByInclude) + if (!matchedByInclude || !ts.isString(matchedByInclude)) return undefined; configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude); message = ts.Diagnostics.File_is_matched_by_include_pattern_specified_here; @@ -98589,8 +100148,8 @@ var ts; (function (ts) { function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) { var outputFiles = []; - var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit; - return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; + var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics; + return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -98601,13 +100160,9 @@ var ts; function createManyToManyPathMap() { function create(forward, reverse, deleted) { var map = { - clone: function () { return create(new ts.Map(forward), new ts.Map(reverse), deleted && new ts.Set(deleted)); }, - forEach: function (fn) { return forward.forEach(fn); }, getKeys: function (v) { return reverse.get(v); }, getValues: function (k) { return forward.get(k); }, - hasKey: function (k) { return forward.has(k); }, keys: function () { return forward.keys(); }, - deletedKeys: function () { return deleted; }, deleteKey: function (k) { (deleted || (deleted = new ts.Set())).add(k); var set = forward.get(k); @@ -98634,11 +100189,6 @@ var ts; }); return map; }, - clear: function () { - forward.clear(); - reverse.clear(); - deleted === null || deleted === void 0 ? void 0 : deleted.clear(); - } }; return map; } @@ -98742,35 +100292,45 @@ var ts; } BuilderState.canReuseOldState = canReuseOldState; function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b, _c; var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? createManyToManyPathMap() : undefined; var exportedModulesMap = referencedMap ? createManyToManyPathMap() : undefined; - var hasCalledUpdateShapeSignature = new ts.Set(); var useOldState = canReuseOldState(referencedMap, oldState); newProgram.getTypeChecker(); - for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + for (var _i = 0, _d = newProgram.getSourceFiles(); _i < _d.length; _i++) { + var sourceFile = _d[_i]; var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); - var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined; + var oldUncommittedSignature = useOldState ? (_a = oldState.oldSignatures) === null || _a === void 0 ? void 0 : _a.get(sourceFile.resolvedPath) : undefined; + var signature = oldUncommittedSignature === undefined ? + useOldState ? (_b = oldState.fileInfos.get(sourceFile.resolvedPath)) === null || _b === void 0 ? void 0 : _b.signature : undefined : + oldUncommittedSignature || undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { referencedMap.set(sourceFile.resolvedPath, newReferences); } if (useOldState) { - var exportedModules = oldState.exportedModulesMap.getValues(sourceFile.resolvedPath); + var oldUncommittedExportedModules = (_c = oldState.oldExportedModulesMap) === null || _c === void 0 ? void 0 : _c.get(sourceFile.resolvedPath); + var exportedModules = oldUncommittedExportedModules === undefined ? + oldState.exportedModulesMap.getValues(sourceFile.resolvedPath) : + oldUncommittedExportedModules || undefined; if (exportedModules) { exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, impliedFormat: sourceFile.impliedNodeFormat }); + fileInfos.set(sourceFile.resolvedPath, { + version: version_2, + signature: signature, + affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, + impliedFormat: sourceFile.impliedNodeFormat + }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } @@ -98780,93 +100340,81 @@ var ts; state.allFileNames = undefined; } BuilderState.releaseCache = releaseCache; - function clone(state) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var _a, _b; - return { - fileInfos: new ts.Map(state.fileInfos), - referencedMap: (_a = state.referencedMap) === null || _a === void 0 ? void 0 : _a.clone(), - exportedModulesMap: (_b = state.exportedModulesMap) === null || _b === void 0 ? void 0 : _b.clone(), - hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), - useFileVersionAsSignature: state.useFileVersionAsSignature, - }; + var result = getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); + return result; } - BuilderState.clone = clone; - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { - var signatureCache = cacheToUpdateSignature || new ts.Map(); + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var sourceFile = programOfThisState.getSourceFileByPath(path); if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); - if (!cacheToUpdateSignature) { - updateSignaturesFromCache(state, signatureCache); - } - return result; + return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName); } - BuilderState.getFilesAffectedBy = getFilesAffectedBy; - function updateSignaturesFromCache(state, signatureCache) { - signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); }); - } - BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + BuilderState.getFilesAffectedByWithOldState = getFilesAffectedByWithOldState; function updateSignatureOfFile(state, signature, path) { state.fileInfos.get(path).signature = signature; - state.hasCalledUpdateShapeSignature.add(path); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(path); } BuilderState.updateSignatureOfFile = updateSignatureOfFile; - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache, useFileVersionAsSignature) { + function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName, useFileVersionAsSignature) { + var _a; if (useFileVersionAsSignature === void 0) { useFileVersionAsSignature = state.useFileVersionAsSignature; } - ts.Debug.assert(!!sourceFile); - ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); - if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) { + if ((_a = state.hasCalledUpdateShapeSignature) === null || _a === void 0 ? void 0 : _a.has(sourceFile.resolvedPath)) return false; - } var info = state.fileInfos.get(sourceFile.resolvedPath); - if (!info) - return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) { - var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, true, cancellationToken, undefined, true); - var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); - if (firstDts_1) { - ts.Debug.assert(ts.isDeclarationFileName(firstDts_1.name), "File extension for signature expected to be dts", function () { return "Found: ".concat(ts.getAnyExtensionFromPath(firstDts_1.name), " for ").concat(firstDts_1.name, ":: All output files: ").concat(JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; }))); }); - latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); - if (exportedModulesMapCache && latestSignature !== prevSignature) { - updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + programOfThisState.emit(sourceFile, function (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) { + ts.Debug.assert(ts.isDeclarationFileName(fileName), "File extension for signature expected to be dts: Got:: ".concat(fileName)); + latestSignature = ts.computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data); + if (latestSignature !== prevSignature) { + updateExportedModules(state, sourceFile, sourceFiles[0].exportedModulesFromDeclarationEmit); } - } + }, cancellationToken, true, undefined, true); } if (latestSignature === undefined) { latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { + if (state.exportedModulesMap && latestSignature !== prevSignature) { + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); var references = state.referencedMap ? state.referencedMap.getValues(sourceFile.resolvedPath) : undefined; if (references) { - exportedModulesMapCache.set(sourceFile.resolvedPath, references); + state.exportedModulesMap.set(sourceFile.resolvedPath, references); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } } } - cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); + (state.oldSignatures || (state.oldSignatures = new ts.Map())).set(sourceFile.resolvedPath, prevSignature || false); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(sourceFile.resolvedPath); + info.signature = latestSignature; return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; - function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + function updateExportedModules(state, sourceFile, exportedModulesFromDeclarationEmit) { + if (!state.exportedModulesMap) + return; + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); if (!exportedModulesFromDeclarationEmit) { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); return; } var exportedModules; exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFilesFromImportedModuleSymbol(symbol)); }); if (exportedModules) { - exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules); + state.exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } function addExportedModule(exportedModulePaths) { if (exportedModulePaths === null || exportedModulePaths === void 0 ? void 0 : exportedModulePaths.length) { @@ -98878,15 +100426,6 @@ var ts; } } BuilderState.updateExportedModules = updateExportedModules; - function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { - var _a; - if (exportedModulesMapCache) { - ts.Debug.assert(!!state.exportedModulesMap); - (_a = exportedModulesMapCache.deletedKeys()) === null || _a === void 0 ? void 0 : _a.forEach(function (path) { return state.exportedModulesMap.deleteKey(path); }); - exportedModulesMapCache.forEach(function (exportedModules, path) { return state.exportedModulesMap.set(path, exportedModules); }); - } - } - BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; function getAllDependencies(state, programOfThisState, sourceFile) { var compilerOptions = programOfThisState.getCompilerOptions(); if (ts.outFile(compilerOptions)) { @@ -98970,7 +100509,7 @@ var ts; } return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cancellationToken, computeHash, getCanonicalFileName) { if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -98986,7 +100525,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, computeHash, getCanonicalFileName)) { queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } @@ -99001,29 +100540,31 @@ var ts; return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); } function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; - if (!ts.outFile(compilerOptions)) { + var outFilePath = ts.outFile(compilerOptions); + if (!outFilePath) { state.semanticDiagnosticsPerFile = new ts.Map(); } + else if (compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.outSignature) && outFilePath === ts.outFile(oldState === null || oldState === void 0 ? void 0 : oldState.compilerOptions)) { + state.outSignature = oldState === null || oldState === void 0 ? void 0 : oldState.outSignature; + } state.changedFilesSet = new ts.Set(); + state.latestChangedDtsFile = compilerOptions.composite ? oldState === null || oldState === void 0 ? void 0 : oldState.latestChangedDtsFile : undefined; var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + var canCopyEmitSignatures = compilerOptions.composite && + (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && + !outFilePath && + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); if (useOldState) { - if (!oldState.currentChangedFilePath) { - var affectedSignatures = oldState.currentAffectedFilesSignatures; - ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); - } - var changedFilesSet = oldState.changedFilesSet; - if (canCopySemanticDiagnostics) { - ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); - } - changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); }); - if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) { + (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); + if (!outFilePath && oldState.affectedFilesPendingEmit) { state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice(); state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind); state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; @@ -99040,6 +100581,7 @@ var ts; if (!useOldState || !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || oldInfo.version !== info.version || + oldInfo.impliedFormat !== info.impliedFormat || !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { state.changedFilesSet.add(sourceFilePath); @@ -99059,24 +100601,22 @@ var ts; state.semanticDiagnosticsFromOldState.add(sourceFilePath); } } + if (canCopyEmitSignatures) { + var oldEmitSignature = oldState.emitSignatures.get(sourceFilePath); + if (oldEmitSignature) + (state.emitSignatures || (state.emitSignatures = new ts.Map())).set(sourceFilePath, oldEmitSignature); + } }); if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) { ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, undefined) .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); }); } - else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { + else if (oldCompilerOptions && !outFilePath && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1); }); ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set(); } - if (useOldState) { - ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { - if (state.fileInfos.has(sourceFilePath) && state.fileInfos.get(sourceFilePath).impliedFormat !== info.impliedFormat) { - state.changedFilesSet.add(sourceFilePath); - } - }); - } - state.buildInfoEmitPending = !!state.changedFilesSet.size; + state.buildInfoEmitPending = !useOldState || state.changedFilesSet.size !== (((_b = oldState.changedFilesSet) === null || _b === void 0 ? void 0 : _b.size) || 0); return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -99109,33 +100649,40 @@ var ts; ts.BuilderState.releaseCache(state); state.program = undefined; } - function cloneBuilderProgramState(state) { - var _a; - var newState = ts.BuilderState.clone(state); - newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile); - newState.changedFilesSet = new ts.Set(state.changedFilesSet); - newState.affectedFiles = state.affectedFiles; - newState.affectedFilesIndex = state.affectedFilesIndex; - newState.currentChangedFilePath = state.currentChangedFilePath; - newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures); - newState.currentAffectedFilesExportedModulesMap = (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clone(); - newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles); - newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; - newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState); - newState.program = state.program; - newState.compilerOptions = state.compilerOptions; - newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(); - newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind); - newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; - newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles); - newState.programEmitComplete = state.programEmitComplete; - return newState; + function backupBuilderProgramEmitState(state) { + var outFilePath = ts.outFile(state.compilerOptions); + ts.Debug.assert(!state.changedFilesSet.size || outFilePath); + return { + affectedFilesPendingEmit: state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(), + affectedFilesPendingEmitKind: state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind), + affectedFilesPendingEmitIndex: state.affectedFilesPendingEmitIndex, + seenEmittedFiles: state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles), + programEmitComplete: state.programEmitComplete, + emitSignatures: state.emitSignatures && new ts.Map(state.emitSignatures), + outSignature: state.outSignature, + latestChangedDtsFile: state.latestChangedDtsFile, + hasChangedEmitSignature: state.hasChangedEmitSignature, + changedFilesSet: outFilePath ? new ts.Set(state.changedFilesSet) : undefined, + }; + } + function restoreBuilderProgramEmitState(state, savedEmitState) { + state.affectedFilesPendingEmit = savedEmitState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitKind = savedEmitState.affectedFilesPendingEmitKind; + state.affectedFilesPendingEmitIndex = savedEmitState.affectedFilesPendingEmitIndex; + state.seenEmittedFiles = savedEmitState.seenEmittedFiles; + state.programEmitComplete = savedEmitState.programEmitComplete; + state.emitSignatures = savedEmitState.emitSignatures; + state.outSignature = savedEmitState.outSignature; + state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile; + state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; + if (savedEmitState.changedFilesSet) + state.changedFilesSet = savedEmitState.changedFilesSet; } function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath)); } - function getNextAffectedFile(state, cancellationToken, computeHash, host) { - var _a; + function getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { @@ -99145,17 +100692,15 @@ var ts; var affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.resolvedPath)) { state.affectedFilesIndex = affectedFilesIndex; - handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); return affectedFile; } affectedFilesIndex++; } state.changedFilesSet.delete(state.currentChangedFilePath); state.currentChangedFilePath = undefined; - ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); - state.currentAffectedFilesSignatures.clear(); - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); - (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clear(); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); state.affectedFiles = undefined; } var nextKey = state.changedFilesSet.keys().next(); @@ -99168,12 +100713,7 @@ var ts; ts.Debug.assert(!state.semanticDiagnosticsPerFile); return program; } - if (!state.currentAffectedFilesSignatures) - state.currentAffectedFilesSignatures = new ts.Map(); - if (state.exportedModulesMap) { - state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap()); - } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedByWithOldState(state, program, nextKey.value, cancellationToken, computeHash, getCanonicalFileName); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; if (!state.seenAffectedFiles) @@ -99216,26 +100756,24 @@ var ts; }); } } - function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { removeDiagnosticsOfLibraryFiles(state); - ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, cancellationToken, computeHash, getCanonicalFileName); return; } - ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: ".concat(affectedFile.fileName)); if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; - handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); } - function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, host) { + function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { var program = ts.Debug.checkDefined(state.program); var sourceFile = program.getSourceFileByPath(path); if (sourceFile) { - ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap, !host.disableUseFileVersionAsSignature); + ts.BuilderState.updateShapeSignature(state, program, sourceFile, cancellationToken, computeHash, getCanonicalFileName, !host.disableUseFileVersionAsSignature); if (ts.getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, 0); } @@ -99251,34 +100789,21 @@ var ts; return !state.semanticDiagnosticsFromOldState.size; } function isChangedSignature(state, path) { - var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path); - var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; + var oldSignature = ts.Debug.checkDefined(state.oldSignatures).get(path) || undefined; + var newSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; return newSignature !== oldSignature; } - function forEachKeyOfExportedModulesMap(state, filePath, fn) { - var keys = state.currentAffectedFilesExportedModulesMap.getKeys(filePath); - var result = keys && ts.forEachKey(keys, fn); - if (result) - return result; - keys = state.exportedModulesMap.getKeys(filePath); - return keys && ts.forEachKey(keys, function (exportedFromPath) { - var _a; - return !state.currentAffectedFilesExportedModulesMap.hasKey(exportedFromPath) && - !((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(exportedFromPath)) ? - fn(exportedFromPath) : - undefined; - }); - } - function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host) { var _a; if (!((_a = state.fileInfos.get(filePath)) === null || _a === void 0 ? void 0 : _a.affectsGlobalScope)) return false; ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, state.program, undefined) - .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, host); }); + .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, getCanonicalFileName, host); }); removeDiagnosticsOfLibraryFiles(state); return true; } - function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a; if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) return; if (!isChangedSignature(state, affectedFile.resolvedPath)) @@ -99291,9 +100816,9 @@ var ts; var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { seenFileNamesMap.set(currentPath, true); - if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host)) return; - handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, host); + handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host); if (isChangedSignature(state, currentPath)) { var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath); queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); @@ -99301,31 +100826,29 @@ var ts; } } } - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); var seenFileAndExportsOfFile = new ts.Set(); - forEachKeyOfExportedModulesMap(state, affectedFile.resolvedPath, function (exportedFromPath) { - if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, host)) + (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; var references = state.referencedMap.getKeys(exportedFromPath); return references && ts.forEachKey(references, function (filePath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); }); } - function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) return undefined; - if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; - handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, host); - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); - forEachKeyOfExportedModulesMap(state, filePath, function (exportedFromPath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host); + (_a = state.exportedModulesMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); - (_a = state.referencedMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (referencingFilePath) { + (_b = state.referencedMap.getKeys(filePath)) === null || _b === void 0 ? void 0 : _b.forEach(function (referencingFilePath) { return !seenFileAndExportsOfFile.has(referencingFilePath) && - handleDtsMayChangeOf(state, referencingFilePath, cancellationToken, computeHash, host); + handleDtsMayChangeOf(state, referencingFilePath, cancellationToken, computeHash, getCanonicalFileName, host); }); return undefined; } @@ -99339,12 +100862,12 @@ var ts; } else { state.seenAffectedFiles.add(affected.resolvedPath); + state.buildInfoEmitPending = true; if (emitKind !== undefined) { (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind); } if (isPendingEmit) { state.affectedFilesPendingEmitIndex++; - state.buildInfoEmitPending = true; } else { state.affectedFilesIndex++; @@ -99376,29 +100899,65 @@ var ts; } return ts.filterSemanticDiagnostics(diagnostics, state.compilerOptions); } + function isProgramBundleEmitBuildInfo(info) { + return !!ts.outFile(info.options || {}); + } + ts.isProgramBundleEmitBuildInfo = isProgramBundleEmitBuildInfo; function getProgramBuildInfo(state, getCanonicalFileName) { - if (ts.outFile(state.compilerOptions)) - return undefined; + var outFilePath = ts.outFile(state.compilerOptions); + if (outFilePath && !state.compilerOptions.composite) + return; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); + var latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : undefined; + if (outFilePath) { + var fileNames_1 = []; + var fileInfos_1 = []; + state.program.getRootFileNames().forEach(function (f) { + var sourceFile = state.program.getSourceFile(f); + if (!sourceFile) + return; + fileNames_1.push(relativeToBuildInfo(sourceFile.resolvedPath)); + fileInfos_1.push(sourceFile.version); + }); + var result_15 = { + fileNames: fileNames_1, + fileInfos: fileInfos_1, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsBundleEmitBuildInfo"), + outSignature: state.outSignature, + latestChangedDtsFile: latestChangedDtsFile, + }; + return result_15; + } var fileNames = []; var fileNameToFileId = new ts.Map(); var fileIdsList; var fileNamesToFileIdListId; + var emitSignatures; var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var _b, _c; var key = _a[0], value = _a[1]; var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); - var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + var oldSignature = (_b = state.oldSignatures) === null || _b === void 0 ? void 0 : _b.get(key); + var actualSignature = oldSignature !== undefined ? oldSignature || undefined : value.signature; + if (state.compilerOptions.composite) { + var file = state.program.getSourceFileByPath(key); + if (!ts.isJsonSourceFile(file) && ts.sourceFileMayBeEmitted(file, state.program)) { + var emitSignature = (_c = state.emitSignatures) === null || _c === void 0 ? void 0 : _c.get(key); + if (emitSignature !== actualSignature) { + (emitSignatures || (emitSignatures = [])).push(emitSignature === undefined ? fileId : [fileId, emitSignature]); + } + } + } return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? { version: value.version, signature: undefined, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : value.version : actualSignature !== undefined ? - signature === undefined ? + oldSignature === undefined ? value : - { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : + { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }; }); var referencedMap; @@ -99412,16 +100971,12 @@ var ts; if (state.exportedModulesMap) { exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var _a; - if (state.currentAffectedFilesExportedModulesMap) { - if ((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(key)) { - return undefined; - } - var newValue = state.currentAffectedFilesExportedModulesMap.getValues(key); - if (newValue) { - return [toFileId(key), toFileIdListId(newValue)]; - } - } - return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + var oldValue = (_a = state.oldExportedModulesMap) === null || _a === void 0 ? void 0 : _a.get(key); + if (oldValue === undefined) + return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue) + return [toFileId(key), toFileIdListId(oldValue)]; + return undefined; }); } var semanticDiagnosticsPerFile; @@ -99432,9 +100987,7 @@ var ts; (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ toFileId(key), - state.hasReusableDiagnostic ? - value : - convertToReusableDiagnostics(value, relativeToBuildInfo) + convertToReusableDiagnostics(value, relativeToBuildInfo) ] : toFileId(key)); } @@ -99449,16 +101002,27 @@ var ts; } } } - return { + var changeFileSet; + if (state.changedFilesSet.size) { + for (var _d = 0, _e = ts.arrayFrom(state.changedFilesSet.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { + var path = _e[_d]; + (changeFileSet || (changeFileSet = [])).push(toFileId(path)); + } + } + var result = { fileNames: fileNames, fileInfos: fileInfos, - options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsMultiFileEmitBuildInfo"), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, affectedFilesPendingEmit: affectedFilesPendingEmit, + changeFileSet: changeFileSet, + emitSignatures: emitSignatures, + latestChangedDtsFile: latestChangedDtsFile, }; + return result; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } @@ -99483,21 +101047,18 @@ var ts; } return fileIdListId; } - } - function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { - var result; - var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var name = _a[_i]; - var optionKey = name.toLowerCase(); - var optionInfo = optionsNameMap.get(optionKey); - if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || - optionKey === "strict" || - optionKey === "skiplibcheck" || optionKey === "skipdefaultlibcheck") { - (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); + function convertToProgramBuildInfoCompilerOptions(options, optionKey) { + var result; + var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo[optionKey]) { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfoEnsuringAbsolutePath); + } } + return result; } - return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { if (option) { @@ -99571,6 +101132,41 @@ var ts; return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; } ts.getBuilderCreationParameters = getBuilderCreationParameters; + function getTextHandlingSourceMapForSignature(text, data) { + return (data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text; + } + function computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data) { + var _a; + text = getTextHandlingSourceMapForSignature(text, data); + var sourceFileDirectory; + if ((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length) { + text += data.diagnostics.map(function (diagnostic) { + return "".concat(locationInfo(diagnostic)).concat(ts.DiagnosticCategory[diagnostic.category]).concat(diagnostic.code, ": ").concat(flattenDiagnosticMessageText(diagnostic.messageText)); + }).join("\n"); + } + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(text); + function flattenDiagnosticMessageText(diagnostic) { + return ts.isString(diagnostic) ? + diagnostic : + diagnostic === undefined ? + "" : + !diagnostic.next ? + diagnostic.messageText : + diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText).join("\n"); + } + function locationInfo(diagnostic) { + if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) + return "(".concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + if (sourceFileDirectory === undefined) + sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath); + return "".concat(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceFileDirectory, diagnostic.file.resolvedPath, getCanonicalFileName)), "(").concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + } + } + ts.computeSignatureWithDiagnostics = computeSignatureWithDiagnostics; + function computeSignature(text, computeHash, data) { + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); + } + ts.computeSignature = computeSignature; function createBuilderProgram(kind, _a) { var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; var oldState = oldProgram && oldProgram.getState(); @@ -99582,7 +101178,6 @@ var ts; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); var computeHash = ts.maybeBind(host, host.createHash); var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); - var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; newProgram = undefined; oldProgram = undefined; @@ -99590,21 +101185,13 @@ var ts; var getState = function () { return state; }; var builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics); builderProgram.getState = getState; - builderProgram.backupState = function () { - ts.Debug.assert(backupState === undefined); - backupState = cloneBuilderProgramState(state); - }; - builderProgram.restoreState = function () { - state = ts.Debug.checkDefined(backupState); - backupState = undefined; - }; + builderProgram.saveEmitState = function () { return backupBuilderProgramEmitState(state); }; + builderProgram.restoreEmitState = function (saved) { return restoreBuilderProgramEmitState(state, saved); }; + builderProgram.hasChangedEmitSignature = function () { return !!state.hasChangedEmitSignature; }; builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); }; builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; builderProgram.emit = emit; - builderProgram.releaseProgram = function () { - releaseCache(state); - backupState = undefined; - }; + builderProgram.releaseProgram = function () { return releaseCache(state); }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; } @@ -99626,7 +101213,7 @@ var ts; return ts.emitSkippedWithNoDiagnostics; } function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); var emitKind = 1; var isPendingEmitFile = false; if (!affected) { @@ -99649,34 +101236,60 @@ var ts; affected = program; } } - return toAffectedFileEmitResult(state, ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, affected !== state.program && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + return toAffectedFileEmitResult(state, ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0, customTransformers), affected, emitKind, isPendingEmitFile); } - function getWriteFileUpdatingSignatureCallback(writeFile) { + function getWriteFileCallback(writeFile, customTransformers) { return function (fileName, text, writeByteOrderMark, onError, sourceFiles, data) { - var _a; + var _a, _b, _c, _d, _e, _f, _g; if (ts.isDeclarationFileName(fileName)) { - ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); - var file = sourceFiles[0]; - var info = state.fileInfos.get(file.resolvedPath); - var signature = ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.get(file.resolvedPath)) || info.signature; - if (signature === file.version) { - var newSignature = (computeHash || ts.generateDjb2Hash)((data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text); - if (newSignature !== file.version) { - if (host.storeFilesChangingSignatureDuringEmit) - (state.filesChangingSignature || (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); - if (state.exportedModulesMap) - ts.BuilderState.updateExportedModules(file, file.exportedModulesFromDeclarationEmit, state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap())); - if (state.affectedFiles && state.affectedFilesIndex < state.affectedFiles.length) { - state.currentAffectedFilesSignatures.set(file.resolvedPath, newSignature); - } - else { - info.signature = newSignature; - if (state.exportedModulesMap) - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + if (!ts.outFile(state.compilerOptions)) { + ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); + var emitSignature = void 0; + if (!customTransformers) { + var file = sourceFiles[0]; + var info = state.fileInfos.get(file.resolvedPath); + if (info.signature === file.version) { + var signature = computeSignatureWithDiagnostics(file, text, computeHash, getCanonicalFileName, data); + if (!((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length)) + emitSignature = signature; + if (signature !== file.version) { + if (host.storeFilesChangingSignatureDuringEmit) + ((_b = state.filesChangingSignature) !== null && _b !== void 0 ? _b : (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); + if (state.exportedModulesMap) + ts.BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit); + if (state.affectedFiles) { + var existing = (_c = state.oldSignatures) === null || _c === void 0 ? void 0 : _c.get(file.resolvedPath); + if (existing === undefined) + ((_d = state.oldSignatures) !== null && _d !== void 0 ? _d : (state.oldSignatures = new ts.Map())).set(file.resolvedPath, info.signature || false); + info.signature = signature; + } + else { + info.signature = signature; + (_e = state.oldExportedModulesMap) === null || _e === void 0 ? void 0 : _e.clear(); + } + } } } + if (state.compilerOptions.composite) { + var filePath = sourceFiles[0].resolvedPath; + var oldSignature = (_f = state.emitSignatures) === null || _f === void 0 ? void 0 : _f.get(filePath); + emitSignature !== null && emitSignature !== void 0 ? emitSignature : (emitSignature = computeSignature(text, computeHash, data)); + if (emitSignature === oldSignature) + return; + ((_g = state.emitSignatures) !== null && _g !== void 0 ? _g : (state.emitSignatures = new ts.Map())).set(filePath, emitSignature); + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; + } + } + else if (state.compilerOptions.composite) { + var newSignature = computeSignature(text, computeHash, data); + if (newSignature === state.outSignature) + return; + state.outSignature = newSignature; + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; } } if (writeFile) @@ -99726,13 +101339,13 @@ var ts; } } } - return ts.Debug.checkDefined(state.program).emit(targetSourceFile, !ts.outFile(state.compilerOptions) && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + return ts.Debug.checkDefined(state.program).emit(targetSourceFile, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers); } function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { while (true) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); if (!affected) { return undefined; } @@ -99790,29 +101403,59 @@ var ts; { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; } ts.toBuilderStateFileInfo = toBuilderStateFileInfo; - function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { - var _a; + function createBuilderProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a, _b, _c, _d; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var filePaths = program.fileNames.map(toPath); - var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); - var fileInfos = new ts.Map(); - program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); - var state = { - fileInfos: fileInfos, - compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, - referencedMap: toManyToManyPathMap(program.referencedMap), - exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), - hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), - affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, - }; + var state; + var filePaths; + var filePathsSetList; + var latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : undefined; + if (isProgramBundleEmitBuildInfo(program)) { + state = { + fileInfos: new ts.Map(), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + latestChangedDtsFile: latestChangedDtsFile, + outSignature: program.outSignature, + }; + } + else { + filePaths = (_a = program.fileNames) === null || _a === void 0 ? void 0 : _a.map(toPath); + filePathsSetList = (_b = program.fileIdsList) === null || _b === void 0 ? void 0 : _b.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); + var fileInfos_2 = new ts.Map(); + var emitSignatures_1 = ((_c = program.options) === null || _c === void 0 ? void 0 : _c.composite) && !ts.outFile(program.options) ? new ts.Map() : undefined; + program.fileInfos.forEach(function (fileInfo, index) { + var path = toFilePath(index + 1); + var stateFileInfo = toBuilderStateFileInfo(fileInfo); + fileInfos_2.set(path, stateFileInfo); + if (emitSignatures_1 && stateFileInfo.signature) + emitSignatures_1.set(path, stateFileInfo.signature); + }); + (_d = program.emitSignatures) === null || _d === void 0 ? void 0 : _d.forEach(function (value) { + if (ts.isNumber(value)) + emitSignatures_1.delete(toFilePath(value)); + else + emitSignatures_1.set(toFilePath(value[0]), value[1]); + }); + state = { + fileInfos: fileInfos_2, + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toManyToManyPathMap(program.referencedMap), + exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), + hasReusableDiagnostic: true, + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, + changedFilesSet: new ts.Set(ts.map(program.changeFileSet, toFilePath)), + latestChangedDtsFile: latestChangedDtsFile, + emitSignatures: (emitSignatures_1 === null || emitSignatures_1 === void 0 ? void 0 : emitSignatures_1.size) ? emitSignatures_1 : undefined, + }; + } return { getState: function () { return state; }, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: ts.notImplemented, getProgramOrUndefined: ts.returnUndefined, releaseProgram: ts.noop, @@ -99832,6 +101475,7 @@ var ts; getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented, emitBuildInfo: ts.notImplemented, close: ts.noop, + hasChangedEmitSignature: ts.returnFalse, }; function toPath(path) { return ts.toPath(path, buildInfoDirectory, getCanonicalFileName); @@ -99857,12 +101501,24 @@ var ts; return map; } } - ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; + ts.createBuilderProgramUsingProgramBuildInfo = createBuilderProgramUsingProgramBuildInfo; + function getBuildInfoFileVersionMap(program, buildInfoPath, host) { + var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var fileInfos = new ts.Map(); + program.fileInfos.forEach(function (fileInfo, index) { + var path = ts.toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName); + var version = ts.isString(fileInfo) ? fileInfo : fileInfo.version; + fileInfos.set(path, version); + }); + return fileInfos; + } + ts.getBuildInfoFileVersionMap = getBuildInfoFileVersionMap; function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { return { getState: ts.notImplemented, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: getProgram, getProgramOrUndefined: function () { return getState().program; }, releaseProgram: function () { return getState().program = undefined; }, @@ -99914,7 +101570,7 @@ var ts; path; } ts.removeIgnoredPath = removeIgnoredPath; - function canWatchDirectory(dirPath) { + function canWatchDirectoryOrFile(dirPath) { var rootLength = ts.getRootLength(dirPath); if (dirPath.length === rootLength) { return false; @@ -99946,15 +101602,19 @@ var ts; } return true; } - ts.canWatchDirectory = canWatchDirectory; + ts.canWatchDirectoryOrFile = canWatchDirectoryOrFile; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var resolutionsWithFailedLookups = []; + var resolutionsWithOnlyAffectingLocations = []; var resolvedFileToResolution = ts.createMultiMap(); + var impliedFormatPackageJsons = new ts.Map(); var hasChangedAutomaticTypeDirectiveNames = false; + var affectingPathChecksForFile; + var affectingPathChecks; var failedLookupChecks; var startsWithPathChecks; var isInDirectoryChecks; @@ -99970,6 +101630,7 @@ var ts; var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; var customFailedLookupPaths = new ts.Map(); var directoryWatchesOfFailedLookups = new ts.Map(); + var fileWatchesOfAffectingLocations = new ts.Map(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); var rootPath = (rootDir && resolutionHost.toPath(rootDir)); var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0; @@ -99978,7 +101639,7 @@ var ts; getModuleResolutionCache: function () { return moduleResolutionCache; }, startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, - startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + startCachingPerDirectoryResolution: startCachingPerDirectoryResolution, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -100009,6 +101670,7 @@ var ts; } function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + ts.clearMap(fileWatchesOfAffectingLocations, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); @@ -100016,10 +101678,15 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; + resolutionsWithOnlyAffectingLocations.length = 0; failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; - clearPerDirectoryResolutions(); + affectingPathChecks = undefined; + affectingPathChecksForFile = undefined; + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); + impliedFormatPackageJsons.clear(); hasChangedAutomaticTypeDirectiveNames = false; } function startRecordingFilesWithChangedResolutions() { @@ -100048,35 +101715,68 @@ var ts; return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } - function clearPerDirectoryResolutions() { - moduleResolutionCache.clear(); - typeReferenceDirectiveResolutionCache.clear(); + function startCachingPerDirectoryResolution() { + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } - function finishCachingPerDirectoryResolution() { + function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = undefined; - clearPerDirectoryResolutions(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + if (newProgram !== oldProgram) { + newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFiles().forEach(function (newFile) { + var _a, _b, _c; + var expected = ts.isExternalOrCommonJsModule(newFile) ? (_b = (_a = newFile.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0 : 0; + var existing = (_c = impliedFormatPackageJsons.get(newFile.path)) !== null && _c !== void 0 ? _c : ts.emptyArray; + for (var i = existing.length; i < expected; i++) { + createFileWatcherOfAffectingLocation(newFile.packageJsonLocations[i], false); + } + if (existing.length > expected) { + for (var i = expected; i < existing.length; i++) { + fileWatchesOfAffectingLocations.get(existing[i]).files--; + } + } + if (expected) + impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations); + else + impliedFormatPackageJsons.delete(newFile.path); + }); + impliedFormatPackageJsons.forEach(function (existing, path) { + if (!(newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFileByPath(path))) { + existing.forEach(function (location) { return fileWatchesOfAffectingLocations.get(location).files--; }); + impliedFormatPackageJsons.delete(path); + } + }); + } directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); + fileWatchesOfAffectingLocations.forEach(function (watcher, path) { + if (watcher.files === 0 && watcher.resolutions === 0) { + fileWatchesOfAffectingLocations.delete(path); + watcher.watcher.close(); + } + }); hasChangedAutomaticTypeDirectiveNames = false; } function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference, _containingSourceFile, mode) { - var _a; + var _a, _b; var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); if (!resolutionHost.getGlobalCache) { return primaryResult; } var globalCache = resolutionHost.getGlobalCache(); if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _c = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _c.resolvedModule, failedLookupLocations = _c.failedLookupLocations, affectingLocations = _c.affectingLocations; if (resolvedModule) { primaryResult.resolvedModule = resolvedModule; (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = primaryResult.affectingLocations).push.apply(_b, affectingLocations); return primaryResult; } } @@ -100265,7 +101965,7 @@ var ts; dirPath = ts.getDirectoryPath(dirPath); } if (ts.isNodeModulesDirectory(dirPath)) { - return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + return canWatchDirectoryOrFile(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; var subDirectoryPath, subDirectory; @@ -100282,7 +101982,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + return canWatchDirectoryOrFile(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -100310,10 +102010,11 @@ var ts; } function watchFailedLookupLocationOfResolution(resolution) { ts.Debug.assert(!!resolution.refCount); - var failedLookupLocations = resolution.failedLookupLocations; - if (!failedLookupLocations.length) + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (!failedLookupLocations.length && !affectingLocations.length) return; - resolutionsWithFailedLookups.push(resolution); + if (failedLookupLocations.length) + resolutionsWithFailedLookups.push(resolution); var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; @@ -100337,12 +102038,85 @@ var ts; if (setAtRoot) { setDirectoryWatcher(rootDir, rootPath, true); } + watchAffectingLocationsOfResolution(resolution, !failedLookupLocations.length); + } + function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { + ts.Debug.assert(!!resolution.refCount); + var affectingLocations = resolution.affectingLocations; + if (!affectingLocations.length) + return; + if (addToResolutionsWithOnlyAffectingLocations) + resolutionsWithOnlyAffectingLocations.push(resolution); + for (var _i = 0, affectingLocations_1 = affectingLocations; _i < affectingLocations_1.length; _i++) { + var affectingLocation = affectingLocations_1[_i]; + createFileWatcherOfAffectingLocation(affectingLocation, true); + } + } + function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) { + var fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation); + if (fileWatcher) { + if (forResolution) + fileWatcher.resolutions++; + else + fileWatcher.files++; + return; + } + var locationToWatch = affectingLocation; + if (resolutionHost.realpath) { + locationToWatch = resolutionHost.realpath(affectingLocation); + if (affectingLocation !== locationToWatch) { + var fileWatcher_1 = fileWatchesOfAffectingLocations.get(locationToWatch); + if (fileWatcher_1) { + if (forResolution) + fileWatcher_1.resolutions++; + else + fileWatcher_1.files++; + fileWatcher_1.paths.add(affectingLocation); + fileWatchesOfAffectingLocations.set(affectingLocation, fileWatcher_1); + return; + } + } + } + var paths = new ts.Set(); + paths.add(locationToWatch); + var actualWatcher = canWatchDirectoryOrFile(resolutionHost.toPath(locationToWatch)) ? + resolutionHost.watchAffectingFileLocation(locationToWatch, function (fileName, eventKind) { + cachedDirectoryStructureHost === null || cachedDirectoryStructureHost === void 0 ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + paths.forEach(function (path) { + if (watcher.resolutions) + (affectingPathChecks !== null && affectingPathChecks !== void 0 ? affectingPathChecks : (affectingPathChecks = new ts.Set())).add(path); + if (watcher.files) + (affectingPathChecksForFile !== null && affectingPathChecksForFile !== void 0 ? affectingPathChecksForFile : (affectingPathChecksForFile = new ts.Set())).add(path); + packageJsonMap === null || packageJsonMap === void 0 ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); + }); + resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); + }) : ts.noopFileWatcher; + var watcher = { + watcher: actualWatcher !== ts.noopFileWatcher ? { + close: function () { + actualWatcher.close(); + actualWatcher = ts.noopFileWatcher; + } + } : actualWatcher, + resolutions: forResolution ? 1 : 0, + files: forResolution ? 0 : 1, + paths: paths, + }; + fileWatchesOfAffectingLocations.set(locationToWatch, watcher); + if (affectingLocation !== locationToWatch) { + fileWatchesOfAffectingLocations.set(affectingLocation, watcher); + paths.add(affectingLocation); + } } function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { var program = resolutionHost.getCurrentProgram(); if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) { resolutions.forEach(watchFailedLookupLocationOfResolution); } + else { + resolutions.forEach(function (resolution) { return watchAffectingLocationsOfResolution(resolution, true); }); + } } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); @@ -100364,37 +102138,44 @@ var ts; if (resolved && resolved.resolvedFileName) { resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution); } - if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { - return; - } - var failedLookupLocations = resolution.failedLookupLocations; - var removeAtRoot = false; - for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { - var failedLookupLocation = failedLookupLocations_2[_i]; - var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (toWatch) { - var dirPath = toWatch.dirPath; - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - if (dirPath === rootPath) { - removeAtRoot = true; - } - else { - removeDirectoryWatcher(dirPath); - } + } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); } } - if (removeAtRoot) { - removeDirectoryWatcher(rootPath); + else if (affectingLocations.length) { + ts.unorderedRemoveItem(resolutionsWithOnlyAffectingLocations, resolution); + } + for (var _a = 0, affectingLocations_2 = affectingLocations; _a < affectingLocations_2.length; _a++) { + var affectingLocation = affectingLocations_2[_a]; + var watcher = fileWatchesOfAffectingLocations.get(affectingLocation); + watcher.resolutions--; } } function removeDirectoryWatcher(dirPath) { @@ -100443,7 +102224,7 @@ var ts; resolution.isInvalidated = invalidated = true; for (var _a = 0, _b = ts.Debug.checkDefined(resolution.files); _a < _b.length; _a++) { var containingFilePath = _b[_a]; - (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile); } } @@ -100464,7 +102245,7 @@ var ts; } function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { if (isCreatingWatchedDirectory) { - (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = new ts.Set())).add(fileOrDirectoryPath); } else { var updatedPath = removeIgnoredPath(fileOrDirectoryPath); @@ -100477,7 +102258,7 @@ var ts; var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { @@ -100487,7 +102268,7 @@ var ts; if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { return false; } - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); if (packagePath) (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); @@ -100496,22 +102277,46 @@ var ts; resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { - return false; + var _a; + var invalidated = false; + if (affectingPathChecksForFile) { + (_a = resolutionHost.getCurrentProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFiles().forEach(function (f) { + if (ts.some(f.packageJsonLocations, function (location) { return affectingPathChecksForFile.has(location); })) { + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(f.path); + invalidated = true; + } + }); + affectingPathChecksForFile = undefined; + } + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks && !affectingPathChecks) { + return invalidated; + } + invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach(function (_value, path) { return isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : undefined; }); } - var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; + invalidated = invalidateResolutions(resolutionsWithOnlyAffectingLocations, canInvalidatedFailedLookupResolutionWithAffectingLocation) || invalidated; + affectingPathChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { - return resolution.failedLookupLocations.some(function (location) { - var locationPath = resolutionHost.toPath(location); - return ts.contains(failedLookupChecks, locationPath) || - ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || - (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); - }); + if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) + return true; + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) + return false; + return resolution.failedLookupLocations.some(function (location) { return isInvalidatedFailedLookup(resolutionHost.toPath(location)); }); + } + function isInvalidatedFailedLookup(locationPath) { + return (failedLookupChecks === null || failedLookupChecks === void 0 ? void 0 : failedLookupChecks.has(locationPath)) || + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + ts.firstDefinedIterator((isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath) ? true : undefined; }); + } + function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) { + return !!affectingPathChecks && resolution.affectingLocations.some(function (location) { return affectingPathChecks.has(location); }); } function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); @@ -100557,7 +102362,7 @@ var ts; function directoryExistsForTypeRootWatch(nodeTypesDirectory) { var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); var dirPath = resolutionHost.toPath(dir); - return dirPath === rootPath || canWatchDirectory(dirPath); + return dirPath === rootPath || canWatchDirectoryOrFile(dirPath); } } ts.createResolutionCache = createResolutionCache; @@ -100642,7 +102447,7 @@ var ts; var info = getInfo(importingSourceFileName, host); var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences, options); return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, undefined, options.overrideImportMode); }) || - getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences); + getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences, options) { if (options === void 0) { options = {}; } @@ -100713,7 +102518,7 @@ var ts; return nodeModulesSpecifiers; } if (!specifier && !modulePath.isRedirect) { - var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences); + var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); if (ts.pathIsBareSpecifier(local)) { pathsSpecifiers = ts.append(pathsSpecifiers, local); } @@ -100731,7 +102536,7 @@ var ts; var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); return { getCanonicalFileName: getCanonicalFileName, importingSourceFileName: importingSourceFileName, sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, _a) { + function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, _a) { var ending = _a.ending, relativePreference = _a.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var sourceDirectory = info.sourceDirectory, getCanonicalFileName = info.getCanonicalFileName; @@ -100745,9 +102550,8 @@ var ts; if (!relativeToBaseUrl) { return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); - var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths; + var fromPaths = paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, getAllowedEndings(ending, compilerOptions, importMode), host, compilerOptions); + var nonRelative = fromPaths === undefined && baseUrl !== undefined ? removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) : fromPaths; if (!nonRelative) { return relativePath; } @@ -100813,9 +102617,9 @@ var ts; var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -100834,10 +102638,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_17 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; - if (result_16) - return result_16; + if (result_17) + return result_17; } }); }); @@ -100872,7 +102676,7 @@ var ts; importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules; }); var sortedPaths = []; - var _loop_32 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -100896,9 +102700,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_10 = _loop_32(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_10 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -100944,28 +102748,59 @@ var ts; return ambientModuleDeclare.name.text; } } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + function getAllowedEndings(preferredEnding, compilerOptions, importMode) { + if (ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && importMode === ts.ModuleKind.ESNext) { + return [2]; + } + switch (preferredEnding) { + case 2: return [2, 0, 1]; + case 1: return [1, 0, 2]; + case 0: return [0, 1, 2]; + default: ts.Debug.assertNever(preferredEnding); + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(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 ({ + ending: ending, + value: removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) + }); }); + if (ts.tryGetExtensionFromPath(pattern)) { + candidates.push({ ending: undefined, value: relativeToBaseUrl }); + } if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix) || - !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); - return key.replace("*", matchedStar); + var prefix = pattern.substring(0, indexOfStar); + var suffix = pattern.substring(indexOfStar + 1); + for (var _b = 0, candidates_3 = candidates; _b < candidates_3.length; _b++) { + var _c = candidates_3[_b], ending = _c.ending, value = _c.value; + if (value.length >= prefix.length + suffix.length && + ts.startsWith(value, prefix) && + ts.endsWith(value, suffix) && + validateEnding({ ending: ending, value: value })) { + var matchedStar = value.substring(prefix.length, value.length - suffix.length); + return { value: key.replace("*", matchedStar) }; + } } } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; + else if (ts.some(candidates, function (c) { return c.ending !== 0 && pattern === c.value; }) || + ts.some(candidates, function (c) { return c.ending === 0 && pattern === c.value && validateEnding(c); })) { + return { value: key }; } + }; + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } + function validateEnding(_a) { + var ending = _a.ending, value = _a.value; + return ending !== 0 || value === removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions, host); + } } function tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, exports, conditions, mode) { if (mode === void 0) { mode = 0; } @@ -101048,10 +102883,10 @@ var ts; if (!parts) { return undefined; } + var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var moduleSpecifier = path; var isPackageRootPath = false; if (!packageNameOnly) { - var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var packageRootIndex = parts.packageRootIndex; var moduleFileName = void 0; while (true) { @@ -101094,11 +102929,13 @@ var ts; var packageRootPath = path.substring(0, packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); var moduleFileToTry = path; + var maybeBlockedByTypesVersions = false; var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) { var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); + var importMode = overrideMode || importingSourceFile.impliedNodeFormat; if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { - var conditions = ["node", overrideMode || importingSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext ? "import" : "require", "types"]; + var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"]; var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, ts.getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions) : undefined; @@ -101117,13 +102954,16 @@ var ts; : undefined; if (versionPaths) { var subModuleName = path.slice(packageRootPath.length + 1); - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0, options), versionPaths.paths); - if (fromPaths !== undefined) { + var fromPaths = tryGetModuleNameFromPaths(subModuleName, versionPaths.paths, getAllowedEndings(preferences.ending, options, importMode), host, options); + if (fromPaths === undefined) { + maybeBlockedByTypesVersions = true; + } + else { moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths); } } var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; - if (ts.isString(mainFileRelative)) { + if (ts.isString(mainFileRelative) && !(maybeBlockedByTypesVersions && ts.matchPatternOrExact(ts.tryParsePatterns(versionPaths.paths), mainFileRelative))) { var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) { return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry }; @@ -101402,21 +103242,41 @@ var ts; var file = _c[_i]; write("".concat(toFileName(file, relativeFileName))); (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write(" ".concat(fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText)); }); - (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); + (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); } } ts.explainFiles = explainFiles; - function explainIfFileIsRedirect(file, fileNameConvertor) { + function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { + var _a; var result; if (file.path !== file.resolvedPath) { - (result || (result = [])).push(ts.chainDiagnosticMessages(undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); } if (file.redirectInfo) { - (result || (result = [])).push(ts.chainDiagnosticMessages(undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); + } + if (ts.isExternalOrCommonJsModule(file)) { + switch (file.impliedNodeFormat) { + case ts.ModuleKind.ESNext: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(undefined, ts.Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + break; + case ts.ModuleKind.CommonJS: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(undefined, file.packageJsonScope.packageJsonContent.type ? + ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : + ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + else if ((_a = file.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(undefined, ts.Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found)); + } + break; + } } return result; } - ts.explainIfFileIsRedirect = explainIfFileIsRedirect; + ts.explainIfFileIsRedirectAndImpliedFormat = explainIfFileIsRedirectAndImpliedFormat; function getMatchedFileSpec(program, fileName) { var _a; var configFile = program.getCompilerOptions().configFile; @@ -101433,6 +103293,8 @@ var ts; var configFile = program.getCompilerOptions().configFile; if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedIncludeSpecs)) return undefined; + if (configFile.configFileSpecs.isDefaultIncludeSpec) + return true; var isJsonFile = ts.fileExtensionIs(fileName, ".json"); var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); var useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); @@ -101497,9 +103359,11 @@ var ts; if (matchedByFiles) return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Part_of_files_list_in_tsconfig_json); var matchedByInclude = getMatchedIncludeSpec(program, fileName); - return matchedByInclude ? + return ts.isString(matchedByInclude) ? ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) : - ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Root_file_specified_for_compilation); + ts.chainDiagnosticMessages(undefined, matchedByInclude ? + ts.Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : + ts.Diagnostics.Root_file_specified_for_compilation); case ts.FileIncludeKind.SourceFromProjectReference: case ts.FileIncludeKind.OutputFromProjectReference: var isOutput = reason.kind === ts.FileIncludeKind.OutputFromProjectReference; @@ -101605,11 +103469,19 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", + AffectingFileLocation: "File location affecting resolution", TypeRoots: "Type roots", ConfigFileOfReferencedProject: "Config file of referened project", ExtendedConfigOfReferencedProject: "Extended config file of referenced project", WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", PackageJson: "package.json file", + ClosedScriptInfo: "Closed Script info", + ConfigFileForInferredRoot: "Config file for the inferred project root", + NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache", + MissingSourceMapFile: "Missing source map file", + NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root", + MissingGeneratedFile: "Missing generated file", + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -101712,6 +103584,7 @@ var ts; createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, storeFilesChangingSignatureDuringEmit: system.storeFilesChangingSignatureDuringEmit, + now: ts.maybeBind(system, system.now), }; } ts.createProgramHost = createProgramHost; @@ -101767,20 +103640,26 @@ var ts; var ts; (function (ts) { function readBuilderProgram(compilerOptions, host) { - if (ts.outFile(compilerOptions)) - return undefined; var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions); if (!buildInfoPath) return undefined; - var content = host.readFile(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); + var buildInfo; + if (host.getBuildInfo) { + buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); + if (!buildInfo) + return undefined; + } + else { + var content = host.readFile(buildInfoPath); + if (!content) + return undefined; + buildInfo = ts.getBuildInfo(content); + } if (buildInfo.version !== ts.version) return undefined; if (!buildInfo.program) return undefined; - return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); + return ts.createBuilderProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); } ts.readBuilderProgram = readBuilderProgram; function createIncrementalCompilerHost(options, system) { @@ -101833,14 +103712,12 @@ var ts; var builderProgram; var reloadLevel; var missingFilesMap; - var packageJsonMap; var watchedWildcardDirectories; var timerToUpdateProgram; var timerToInvalidateFailedLookupResolutions; var parsedConfigs; var sharedExtendedConfigFileWatchers; var extendedConfigCache = host.extendedConfigCache; - var changesAffectResolution = false; var reportFileChangeDetectedOnCreateProgram = false; var sourceFilesCache = new ts.Map(); var missingFilePathsRequestedForRelease; @@ -101894,6 +103771,7 @@ var ts; compilerHost.getCompilationSettings = function () { return compilerOptions; }; compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect); compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); }; + compilerHost.watchAffectingFileLocation = function (file, cb) { return watchFile(file, cb, ts.PollingInterval.High, watchOptions, ts.WatchType.AffectingFileLocation); }; compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); }; compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations; @@ -101924,6 +103802,9 @@ var ts; return host.resolveTypeReferenceDirectives.apply(host, args); }) : (function (typeDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference, containingFileMode); }); + compilerHost.getModuleResolutionCache = host.resolveModuleNames ? + ts.maybeBind(host, host.getModuleResolutionCache) : + (function () { return resolutionCache.getModuleResolutionCache(); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); @@ -101971,10 +103852,6 @@ var ts; }); parsedConfigs = undefined; } - if (packageJsonMap) { - ts.clearMap(packageJsonMap, ts.closeFileWatcher); - packageJsonMap = undefined; - } } function getCurrentBuilderProgram() { return builderProgram; @@ -101988,11 +103865,11 @@ var ts; var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); - if (program && (changesAffectResolution || ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions))) { + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { resolutionCache.clear(); } } - var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution); + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { @@ -102008,7 +103885,6 @@ var ts; } createNewProgram(hasInvalidatedResolution); } - changesAffectResolution = false; reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); @@ -102027,14 +103903,10 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + var oldProgram = getCurrentProgram(); builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); - var packageCacheEntries = ts.map(resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [compilerHost.realpath ? toPath(compilerHost.realpath(path)) : path, data]; - }); - resolutionCache.finishCachingPerDirectoryResolution(); + resolutionCache.finishCachingPerDirectoryResolution(builderProgram.getProgram(), oldProgram); ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath); - ts.updatePackageJsonWatch(packageCacheEntries, packageJsonMap || (packageJsonMap = new ts.Map()), watchPackageJsonLookupPath); if (needsUpdateInTypeRootWatch) { resolutionCache.updateTypeRootsWatch(); } @@ -102103,9 +103975,6 @@ var ts; sourceFilesCache.set(path, false); } } - if (sourceFile) { - sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); - } return sourceFile; } return hostSourceFile.sourceFile; @@ -102211,6 +104080,7 @@ var ts; } function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; rootFileNames = ts.getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions); if (ts.updateErrorForNoInputFiles(rootFileNames, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; @@ -102310,17 +104180,6 @@ var ts; ts.noopFileWatcher : watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } - function watchPackageJsonLookupPath(packageJsonPath) { - return sourceFilesCache.has(packageJsonPath) ? - ts.noopFileWatcher : - watchFilePath(packageJsonPath, packageJsonPath, onPackageJsonChange, ts.PollingInterval.High, watchOptions, ts.WatchType.PackageJson); - } - function onPackageJsonChange(fileName, eventKind, path) { - updateCachedSystemWithFile(fileName, path, eventKind); - reloadLevel = ts.ConfigFileProgramReloadLevel.Full; - changesAffectResolution = true; - scheduleProgramUpdate(); - } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { @@ -102451,11 +104310,14 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream"; - UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate"; - UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream"; - UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate"; - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["OutOfDateBuildInfo"] = 7] = "OutOfDateBuildInfo"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 8] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 9] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 10] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 11] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["UpToDateWithInputFileText"] = 12] = "UpToDateWithInputFileText"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 13] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ForceBuild"] = 14] = "ForceBuild"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); function resolveConfigFileProjectName(project) { if (ts.fileExtensionIs(project, ".json")) { @@ -102493,9 +104355,10 @@ var ts; function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); }); } - function newer(date1, date2) { - return date2 > date1 ? date2 : date1; + function getCurrentTime(host) { + return host.now ? host.now() : new Date(); } + ts.getCurrentTime = getCurrentTime; function isCircularBuildOrder(buildOrder) { return !!buildOrder && !!buildOrder.buildOrder; } @@ -102564,6 +104427,7 @@ var ts; compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); }; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); + compilerHost.getModuleResolutionCache = ts.maybeBind(host, host.getModuleResolutionCache); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { @@ -102579,6 +104443,7 @@ var ts; return ts.loadWithTypeDirectiveCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader_4); }; } + compilerHost.getBuildInfo = function (fileName, configFilePath) { return getBuildInfo(state, fileName, toResolvedConfigFilePath(state, configFilePath), undefined); }; var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -102594,8 +104459,9 @@ var ts; resolvedConfigFilePaths: new ts.Map(), configFileCache: new ts.Map(), projectStatus: new ts.Map(), - buildInfoChecked: new ts.Map(), extendedConfigCache: new ts.Map(), + buildInfoCache: new ts.Map(), + outputTimeStamps: new ts.Map(), builderPrograms: new ts.Map(), diagnostics: new ts.Map(), projectPendingBuild: new ts.Map(), @@ -102610,13 +104476,13 @@ var ts; allProjectBuildPending: true, needsSummary: true, watchAllProjectsPending: watch, - currentInvalidatedProject: undefined, watch: watch, allWatchedWildcardDirectories: new ts.Map(), allWatchedInputFiles: new ts.Map(), allWatchedConfigFiles: new ts.Map(), allWatchedExtendedConfigFiles: new ts.Map(), allWatchedPackageJsonFiles: new ts.Map(), + filesWatched: new ts.Map(), lastCachedPackageJsonLookups: new ts.Map(), timerToBuildInvalidatedProject: undefined, reportFileChangeDetected: false, @@ -102718,11 +104584,12 @@ var ts; var noopOnDelete = { onDeleteValue: ts.noop }; ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete); - ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.buildInfoCache, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.outputTimeStamps, currentProjects, noopOnDelete); if (state.watch) { ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher }); state.allWatchedExtendedConfigFiles.forEach(function (watcher) { @@ -102835,7 +104702,6 @@ var ts; })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {})); function doneInvalidatedProject(state, projectPath) { state.projectPendingBuild.delete(projectPath); - state.currentInvalidatedProject = undefined; return state.diagnostics.has(projectPath) ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; @@ -103008,16 +104874,16 @@ var ts; } function emit(writeFileCallback, cancellationToken, customTransformers) { var _a; - var _b, _c; + var _b, _c, _d; ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.Emit); - program.backupState(); + var saved = program.saveEmitState(); var declDiagnostics; var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; var outputFiles = []; - var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, undefined, undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, false, customTransformers || ((_c = (_b = state.host).getCustomTransformers) === null || _c === void 0 ? void 0 : _c.call(_b, project))).emitResult; + var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, undefined, undefined, function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark, buildInfo: data === null || data === void 0 ? void 0 : data.buildInfo }); }, cancellationToken, false, customTransformers || ((_c = (_b = state.host).getCustomTransformers) === null || _c === void 0 ? void 0 : _c.call(_b, project))).emitResult; if (declDiagnostics) { - program.restoreState(); + program.restoreEmitState(saved); (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step); return { emitSkipped: true, @@ -103025,36 +104891,38 @@ var ts; }; } var host = state.host, compilerHost = state.compilerHost; - var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; - var newestDeclarationFileContentChangedTime = minimumDate; - var anyDtsChanged = false; + var resultFlags = ((_d = program.hasChangedEmitSignature) === null || _d === void 0 ? void 0 : _d.call(program)) ? BuildResultFlags.None : BuildResultFlags.DeclarationOutputUnchanged; var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var options = program.getCompilerOptions(); + var isIncremental = ts.isIncrementalCompilation(options); + var outputTimeStampMap; + var now; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; - var priorChangeTime; - if (!anyDtsChanged && ts.isDeclarationFileName(name)) { - if (host.fileExists(name) && state.readFileWithCache(name) === text) { - priorChangeTime = host.getModifiedTime(name); - } - else { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - anyDtsChanged = true; - } - } + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; + var path = toPath(state, name); emittedOutputs.set(toPath(state, name), name); + if (buildInfo) + setBuildInfo(state, buildInfo, projectPath, options, resultFlags); ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); - if (priorChangeTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + if (!isIncremental && state.watch) { + (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); } }); - finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); + finishEmit(emitterDiagnostics, emittedOutputs, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); return emitResult; } function emitBuildInfo(writeFileCallback, cancellationToken) { ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.EmitBuildInfo); - var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken); + var emitResult = program.emitBuildInfo(function (name, text, writeByteOrderMark, onError, sourceFiles, data) { + if (data === null || data === void 0 ? void 0 : data.buildInfo) + setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), BuildResultFlags.DeclarationOutputUnchanged); + if (writeFileCallback) + writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); + else + state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); + }, cancellationToken); if (emitResult.diagnostics.length) { reportErrors(state, emitResult.diagnostics); state.diagnostics.set(projectPath, __spreadArray(__spreadArray([], state.diagnostics.get(projectPath), true), emitResult.diagnostics, true)); @@ -103067,7 +104935,7 @@ var ts; step = BuildStep.QueueReferencingProjects; return emitResult; } - function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) { + function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) { var _a; var emitDiagnostics = emitterDiagnostics.getDiagnostics(); if (emitDiagnostics.length) { @@ -103077,13 +104945,10 @@ var ts; if (state.write) { emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); }); } - var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); + updateOutputTimestampsWorker(state, config, projectPath, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); state.diagnostics.delete(projectPath); state.projectStatus.set(projectPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ? - maximumDate : - newestDeclarationFileContentChangedTime, oldestOutputFileName: oldestOutputFileName }); afterProgramDone(state, program, config); @@ -103116,12 +104981,21 @@ var ts; ts.Debug.assert(!!outputFiles.length); var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; + var existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var _b, _c; + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; emittedOutputs.set(toPath(state, name), name); + if (buildInfo) { + if (((_b = buildInfo.program) === null || _b === void 0 ? void 0 : _b.outSignature) !== ((_c = existingBuildInfo.program) === null || _c === void 0 ? void 0 : _c.outSignature)) { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + } + setBuildInfo(state, buildInfo, projectPath, config.options, resultFlags); + } ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); }); - var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged); + var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, outputFiles[0].name, resultFlags); return { emitSkipped: false, diagnostics: emitDiagnostics }; } function executeSteps(till, cancellationToken, writeFile, customTransformers) { @@ -103170,16 +105044,11 @@ var ts; !!ts.getConfigFileParsingDiagnostics(config).length || !ts.isIncrementalCompilation(config.options); } - function getNextInvalidatedProject(state, buildOrder, reportQueue) { + function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { if (!state.projectPendingBuild.size) return undefined; if (isCircularBuildOrder(buildOrder)) return undefined; - if (state.currentInvalidatedProject) { - return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ? - state.currentInvalidatedProject : - undefined; - } var options = state.options, projectPendingBuild = state.projectPendingBuild; for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { var project = buildOrder[projectIndex]; @@ -103211,9 +105080,9 @@ var ts; watchPackageJsonFiles(state, project, projectPath, config); } var status = getUpToDateStatus(state, config, projectPath); - verboseReportProjectStatus(state, project, status); if (!options.force) { if (status.type === ts.UpToDateStatusType.UpToDate) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); if (options.dry) { @@ -103221,12 +105090,20 @@ var ts; } continue; } - if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) { + if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes || status.type === ts.UpToDateStatusType.UpToDateWithInputFileText) { reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); - return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder); + return { + kind: InvalidatedProjectKind.UpdateOutputFileStamps, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config + }; } } if (status.type === ts.UpToDateStatusType.UpstreamBlocked) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); if (options.verbose) { @@ -103237,16 +105114,36 @@ var ts; continue; } if (status.type === ts.UpToDateStatusType.ContainerOnly) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); continue; } - return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ? - InvalidatedProjectKind.Build : - InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder); + return { + kind: needsBuild(state, status, config) ? + InvalidatedProjectKind.Build : + InvalidatedProjectKind.UpdateBundle, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config, + }; } return undefined; } + function createInvalidatedProjectWithInfo(state, info, buildOrder) { + verboseReportProjectStatus(state, info.project, info.status); + return info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps ? + createBuildOrUpdateInvalidedProject(info.kind, state, info.project, info.projectPath, info.projectIndex, info.config, buildOrder) : + createUpdateOutputFileStampsProject(state, info.project, info.projectPath, info.config, buildOrder); + } + function getNextInvalidatedProject(state, buildOrder, reportQueue) { + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); + if (!info) + return info; + return createInvalidatedProjectWithInfo(state, info, buildOrder); + } function listEmittedFile(_a, proj, file) { var write = _a.write; if (write && proj.options.listEmittedFiles) { @@ -103264,7 +105161,7 @@ var ts; } function afterProgramDone(state, program, config) { if (program) { - if (program && state.write) + if (state.write) ts.listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); @@ -103277,7 +105174,7 @@ var ts; state.projectCompilerOptions = state.baseCompilerOptions; } function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) { - var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions()); + var canEmitBuildInfo = program && !ts.outFile(program.getCompilerOptions()); reportAndStoreErrors(state, resolvedPath, diagnostics); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: "".concat(errorType, " errors") }); if (canEmitBuildInfo) @@ -103285,8 +105182,102 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } + function isFileWatcherWithModifiedTime(value) { + return !!value.watcher; + } + function getModifiedTime(state, fileName) { + var path = toPath(state, fileName); + var existing = state.filesWatched.get(path); + if (state.watch && !!existing) { + if (!isFileWatcherWithModifiedTime(existing)) + return existing; + if (existing.modifiedTime) + return existing.modifiedTime; + } + var result = ts.getModifiedTime(state.host, fileName); + if (state.watch) { + if (existing) + existing.modifiedTime = result; + else + state.filesWatched.set(path, result); + } + return result; + } + function watchFile(state, file, callback, pollingInterval, options, watchType, project) { + var path = toPath(state, file); + var existing = state.filesWatched.get(path); + if (existing && isFileWatcherWithModifiedTime(existing)) { + existing.callbacks.push(callback); + } + else { + var watcher = state.watchFile(file, function (fileName, eventKind, modifiedTime) { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + existing.modifiedTime = modifiedTime; + existing.callbacks.forEach(function (cb) { return cb(fileName, eventKind, modifiedTime); }); + }, pollingInterval, options, watchType, project); + state.filesWatched.set(path, { callbacks: [callback], watcher: watcher, modifiedTime: existing }); + } + return { + close: function () { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + if (existing.callbacks.length === 1) { + state.filesWatched.delete(path); + ts.closeFileWatcherOf(existing); + } + else { + ts.unorderedRemoveItem(existing.callbacks, callback); + } + } + }; + } + function getOutputTimeStampMap(state, resolvedConfigFilePath) { + if (!state.watch) + return undefined; + var result = state.outputTimeStamps.get(resolvedConfigFilePath); + if (!result) + state.outputTimeStamps.set(resolvedConfigFilePath, result = new ts.Map()); + return result; + } + function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) { + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(options); + var existing = getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath); + var modifiedTime = getCurrentTime(state.host); + if (existing) { + existing.buildInfo = buildInfo; + existing.modifiedTime = modifiedTime; + if (!(resultFlags & BuildResultFlags.DeclarationOutputUnchanged)) + existing.latestChangedDtsTime = modifiedTime; + } + else { + state.buildInfoCache.set(resolvedConfigPath, { + path: toPath(state, buildInfoPath), + buildInfo: buildInfo, + modifiedTime: modifiedTime, + latestChangedDtsTime: resultFlags & BuildResultFlags.DeclarationOutputUnchanged ? undefined : modifiedTime, + }); + } + } + function getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + return (existing === null || existing === void 0 ? void 0 : existing.path) === path ? existing : undefined; + } + function getBuildInfo(state, buildInfoPath, resolvedConfigPath, modifiedTime) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + if (existing !== undefined && existing.path === path) { + return existing.buildInfo || undefined; + } + var value = state.readFileWithCache(buildInfoPath); + var buildInfo = value ? ts.getBuildInfo(value) : undefined; + ts.Debug.assert(modifiedTime || !buildInfo); + state.buildInfoCache.set(resolvedConfigPath, { path: path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || ts.missingFileModifiedTime }); + return buildInfo; + } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { - var tsconfigTime = ts.getModifiedTime(state.host, configFile); + var tsconfigTime = getModifiedTime(state, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -103296,76 +105287,22 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { - var force = !!state.options.force; - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - var host = state.host; - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: ts.UpToDateStatusType.Unbuildable, - reason: "".concat(inputFile, " does not exist") - }; - } - if (!force) { - var inputTime = ts.getModifiedTime(host, inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - } + var _a, _b; if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) { return { type: ts.UpToDateStatusType.ContainerOnly }; } - var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - if (!force) { - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = ts.getModifiedTime(host, output); - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - if (ts.isDeclarationFileName(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; + var referenceStatuses; + var force = !!state.options.force; if (project.projectReferences) { state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream }); - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); + for (var _i = 0, _c = project.projectReferences; _i < _c.length; _i++) { + var ref = _c[_i]; var resolvedRef = ts.resolveProjectReferencePath(ref); var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef); - var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath); + var resolvedConfig = parseConfigFile(state, resolvedRef, resolvedRefPath); + var refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath); if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream || refStatus.type === ts.UpToDateStatusType.ContainerOnly) { continue; @@ -103384,65 +105321,168 @@ var ts; upstreamProjectName: ref.path }; } - if (!force && !missingOutputFileName) { - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + if (!force) + (referenceStatuses || (referenceStatuses = [])).push({ ref: ref, refStatus: refStatus, resolvedRefPath: resolvedRefPath, resolvedConfig: resolvedConfig }); + } + } + if (force) + return { type: ts.UpToDateStatusType.ForceBuild }; + var host = state.host; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); + var oldestOutputFileName; + var oldestOutputFileTime = maximumDate; + var buildInfoTime; + var buildInfoProgram; + var buildInfoVersionMap; + if (buildInfoPath) { + var buildInfoCacheEntry_1 = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath); + buildInfoTime = (buildInfoCacheEntry_1 === null || buildInfoCacheEntry_1 === void 0 ? void 0 : buildInfoCacheEntry_1.modifiedTime) || ts.getModifiedTime(host, buildInfoPath); + if (buildInfoTime === ts.missingFileModifiedTime) { + if (!buildInfoCacheEntry_1) { + state.buildInfoCache.set(resolvedPath, { + path: toPath(state, buildInfoPath), + buildInfo: false, + modifiedTime: buildInfoTime + }); + } + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: buildInfoPath + }; + } + var buildInfo = ts.Debug.checkDefined(getBuildInfo(state, buildInfoPath, resolvedPath, buildInfoTime)); + if ((buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + return { + type: ts.UpToDateStatusType.TsVersionOutputOfDate, + version: buildInfo.version + }; + } + 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))) { return { - type: ts.UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path + type: ts.UpToDateStatusType.OutOfDateBuildInfo, + buildInfoFile: buildInfoPath }; } + buildInfoProgram = buildInfo.program; } + oldestOutputFileTime = buildInfoTime; + oldestOutputFileName = buildInfoPath; } - if (missingOutputFileName !== undefined) { - return { - type: ts.UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + var pseudoInputUpToDate = false; + for (var _d = 0, _e = project.fileNames; _d < _e.length; _d++) { + var inputFile = _e[_d]; + var inputTime = getModifiedTime(state, inputFile); + if (inputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.Unbuildable, + reason: "".concat(inputFile, " does not exist") + }; + } + if (buildInfoTime && buildInfoTime < inputTime) { + var version_3 = void 0; + var currentVersion = void 0; + if (buildInfoProgram) { + if (!buildInfoVersionMap) + buildInfoVersionMap = ts.getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + version_3 = buildInfoVersionMap.get(toPath(state, inputFile)); + var text = version_3 ? state.readFileWithCache(inputFile) : undefined; + currentVersion = text && (host.createHash || ts.generateDjb2Hash)(text); + if (version_3 && version_3 === currentVersion) + pseudoInputUpToDate = true; + } + if (!version_3 || version_3 !== currentVersion) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: buildInfoPath, + newerInputFileName: inputFile + }; + } + } + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - if (isOutOfDateWithInputs) { - return { - type: ts.UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; + if (!buildInfoPath) { + var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, resolvedPath); + for (var _f = 0, outputs_1 = outputs; _f < outputs_1.length; _f++) { + var output = outputs_1[_f]; + var path = toPath(state, output); + var outputTime = outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.get(path); + if (!outputTime) { + outputTime = ts.getModifiedTime(state.host, output); + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.set(path, outputTime); + } + if (outputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: output + }; + } + if (outputTime < newestInputFileTime) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: output, + newerInputFileName: newestInputFileName + }; + } + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + } } - else { - var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); - if (configStatus) - return configStatus; - var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); - if (extendedConfigStatus) - return extendedConfigStatus; - var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { - var path = _a[0]; - return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); - }); - if (dependentPackageFileStatus) - return dependentPackageFileStatus; - } - if (!force && !state.buildInfoChecked.has(resolvedPath)) { - state.buildInfoChecked.set(resolvedPath, true); - var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); - if (buildInfoPath) { - var value = state.readFileWithCache(buildInfoPath); - var buildInfo = value && ts.getBuildInfo(value); - if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + var seenRefs = buildInfoPath ? new ts.Set() : undefined; + var buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath); + seenRefs === null || seenRefs === void 0 ? void 0 : seenRefs.add(resolvedPath); + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (referenceStatuses) { + for (var _g = 0, referenceStatuses_1 = referenceStatuses; _g < referenceStatuses_1.length; _g++) { + var _h = referenceStatuses_1[_g], ref = _h.ref, refStatus = _h.refStatus, resolvedConfig = _h.resolvedConfig, resolvedRefPath = _h.resolvedRefPath; + usesPrepend = usesPrepend || !!(ref.prepend); + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + if (buildInfoCacheEntry && hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath)) { return { - type: ts.UpToDateStatusType.TsVersionOutputOfDate, - version: buildInfo.version + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: buildInfoPath, + newerProjectName: ref.path }; } + var newestDeclarationFileContentChangedTime = getLatestChangedDtsTime(state, resolvedConfig.options, resolvedRefPath); + if (newestDeclarationFileContentChangedTime && newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { + var path = _a[0]; + return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); + }); + if (dependentPackageFileStatus) + return dependentPackageFileStatus; if (usesPrepend && pseudoUpToDate) { return { type: ts.UpToDateStatusType.OutOfDateWithPrepend, @@ -103451,15 +105491,35 @@ var ts; }; } return { - type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + type: pseudoUpToDate ? + ts.UpToDateStatusType.UpToDateWithUpstreamTypes : + pseudoInputUpToDate ? + ts.UpToDateStatusType.UpToDateWithInputFileText : + ts.UpToDateStatusType.UpToDate, newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, oldestOutputFileName: oldestOutputFileName }; } + function hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath) { + if (seenRefs.has(resolvedRefPath)) + return false; + seenRefs.add(resolvedRefPath); + var refBuildInfo = state.buildInfoCache.get(resolvedRefPath); + if (refBuildInfo.path === buildInfoCacheEntry.path) + return true; + if (resolvedConfig.projectReferences) { + for (var _i = 0, _a = resolvedConfig.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRef = ts.resolveProjectReferencePath(ref); + var resolvedRefPath_1 = toResolvedConfigFilePath(state, resolvedRef); + var resolvedConfig_1 = parseConfigFile(state, resolvedRef, resolvedRefPath_1); + if (hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig_1, resolvedRefPath_1)) + return true; + } + } + return false; + } function getUpToDateStatus(state, project, resolvedPath) { if (project === undefined) { return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; @@ -103472,39 +105532,67 @@ var ts; state.projectStatus.set(resolvedPath, actual); return actual; } - function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) { if (proj.options.noEmit) - return priorNewestUpdateTime; + return; + var now; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(proj.options); + if (buildInfoPath) { + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(toPath(state, buildInfoPath)))) { + if (!!state.options.verbose) + reportStatus(state, verboseMessage, proj.options.configFilePath); + state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); + getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; + } + state.outputTimeStamps.delete(projectPath); + return; + } var host = state.host; var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, projectPath); + var modifiedOutputs = outputTimeStampMap ? new ts.Set() : undefined; if (!skipOutputs || outputs.length !== skipOutputs.size) { var reportVerbose = !!state.options.verbose; - var now = host.now ? host.now() : new Date(); for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { var file = outputs_2[_i]; - if (skipOutputs && skipOutputs.has(toPath(state, file))) { + var path = toPath(state, file); + if (skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(path)) continue; - } if (reportVerbose) { reportVerbose = false; reportStatus(state, verboseMessage, proj.options.configFilePath); } - if (ts.isDeclarationFileName(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); + host.setModifiedTime(file, now || (now = getCurrentTime(state.host))); + if (outputTimeStampMap) { + outputTimeStampMap.set(path, now); + modifiedOutputs.add(path); } - host.setModifiedTime(file, now); } } - return priorNewestUpdateTime; + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.forEach(function (_value, key) { + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) + outputTimeStampMap.delete(key); + }); + } + function getLatestChangedDtsTime(state, options, resolvedConfigPath) { + if (!options.composite) + return undefined; + var entry = ts.Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); + if (entry.latestChangedDtsTime !== undefined) + return entry.latestChangedDtsTime || undefined; + var latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? + state.host.getModifiedTime(ts.getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, ts.getDirectoryPath(entry.path))) : + undefined; + entry.latestChangedDtsTime = latestChangedDtsTime || false; + return latestChangedDtsTime; } function updateOutputTimestamps(state, proj, resolvedPath) { if (state.options.dry) { return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath); } - var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); + updateOutputTimestampsWorker(state, proj, resolvedPath, ts.Diagnostics.Updating_output_timestamps_of_project_0); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: priorNewestUpdateTime, oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames()) }); } @@ -103543,6 +105631,7 @@ var ts; } break; } + case ts.UpToDateStatusType.UpToDateWithInputFileText: case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: case ts.UpToDateStatusType.OutOfDateWithPrepend: if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { @@ -103650,9 +105739,9 @@ var ts; function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) { state.reportFileChangeDetected = true; invalidateProject(state, resolvedPath, reloadLevel); - scheduleBuildInvalidatedProject(state); + scheduleBuildInvalidatedProject(state, 250, true); } - function scheduleBuildInvalidatedProject(state) { + function scheduleBuildInvalidatedProject(state, time, changeDetected) { var hostWithWatch = state.hostWithWatch; if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; @@ -103660,24 +105749,35 @@ var ts; if (state.timerToBuildInvalidatedProject) { hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject); } - state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state); + state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, state, changeDetected); } - function buildNextInvalidatedProject(state) { + function buildNextInvalidatedProject(state, changeDetected) { state.timerToBuildInvalidatedProject = undefined; if (state.reportFileChangeDetected) { state.reportFileChangeDetected = false; state.projectErrorsReported.clear(); reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation); } + var projectsBuilt = 0; var buildOrder = getBuildOrder(state); var invalidatedProject = getNextInvalidatedProject(state, buildOrder, false); if (invalidatedProject) { invalidatedProject.done(); - if (state.projectPendingBuild.size) { - if (state.watch && !state.timerToBuildInvalidatedProject) { - scheduleBuildInvalidatedProject(state); + projectsBuilt++; + while (state.projectPendingBuild.size) { + if (state.timerToBuildInvalidatedProject) + return; + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, false); + if (!info) + break; + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps && (changeDetected || projectsBuilt === 5)) { + scheduleBuildInvalidatedProject(state, 100, false); + return; } - return; + var project = createInvalidatedProjectWithInfo(state, info, buildOrder); + project.done(); + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps) + projectsBuilt++; } } disableCache(state); @@ -103686,12 +105786,10 @@ var ts; function watchConfigFile(state, resolved, resolvedPath, parsed) { if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; - state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(resolved, function () { - invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); - }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); + state.allWatchedConfigFiles.set(resolvedPath, watchFile(state, resolved, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(state, extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -103723,7 +105821,7 @@ var ts; if (!state.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), { - createNewValue: function (_path, input) { return state.watchFile(input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, + createNewValue: function (_path, input) { return watchFile(state, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -103731,7 +105829,7 @@ var ts; if (!state.watch || !state.lastCachedPackageJsonLookups) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), new ts.Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), { - createNewValue: function (path, _input) { return state.watchFile(path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, + createNewValue: function (path, _input) { return watchFile(state, path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -103777,8 +105875,6 @@ var ts; return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath); }, invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); }, - buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); }, - getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); }, close: function () { return stopWatching(state); }, }; } @@ -103855,25 +105951,26 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { - if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { - return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); - } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); case ts.UpToDateStatusType.OutOfDateWithUpstream: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.OutputMissing: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName)); + case ts.UpToDateStatusType.OutOfDateBuildInfo: + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), relName(state, status.buildInfoFile)); case ts.UpToDateStatusType.UpToDate: if (status.newestInputFileTime !== undefined) { - return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); } break; case ts.UpToDateStatusType.OutOfDateWithPrepend: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName)); + case ts.UpToDateStatusType.UpToDateWithInputFileText: + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, relName(state, configFileName)); case ts.UpToDateStatusType.UpstreamOutOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName)); case ts.UpToDateStatusType.UpstreamBlocked: @@ -103884,6 +105981,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason); case ts.UpToDateStatusType.TsVersionOutputOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, ts.version); + case ts.UpToDateStatusType.ForceBuild: + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); case ts.UpToDateStatusType.ContainerOnly: case ts.UpToDateStatusType.ComputingUpstream: break; @@ -104700,6 +106799,7 @@ var ts; } })(ts || (ts = {})); // This file actually uses arguments passed on commandline and executes it +// enable deprecation logging ts.Debug.loggingHost = { log: function (_level, s) { ts.sys.write("".concat(s || "").concat(ts.sys.newLine)); diff --git a/tsserver/tsserver.js b/tsserver/tsserver.js index 2cd21081..481cb586 100644 --- a/tsserver/tsserver.js +++ b/tsserver/tsserver.js @@ -92,15 +92,24 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.7"; + ts.versionMajorMinor = "4.8"; // 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 = "4.7.2"; + ts.version = "4.8.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -306,8 +315,10 @@ var ts; return true; } ts.every = every; - function find(array, predicate) { - for (var i = 0; i < array.length; i++) { + function find(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { var value = array[i]; if (predicate(value, i)) { return value; @@ -316,8 +327,10 @@ var ts; return undefined; } ts.find = find; - function findLast(array, predicate) { - for (var i = array.length - 1; i >= 0; i--) { + function findLast(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { var value = array[i]; if (predicate(value, i)) { return value; @@ -328,7 +341,9 @@ var ts; ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate, startIndex) { - for (var i = startIndex || 0; i < array.length; i++) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -337,7 +352,9 @@ var ts; } ts.findIndex = findIndex; function findLastIndex(array, predicate, startIndex) { - for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { if (predicate(array[i], i)) { return i; } @@ -1115,7 +1132,7 @@ var ts; * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return array.length === 0 ? undefined : array[0]; + return array === undefined || array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -1127,7 +1144,7 @@ var ts; * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return array.length === 0 ? undefined : array[array.length - 1]; + return array === undefined || array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -1468,6 +1485,43 @@ var ts; return createMultiMap(); } ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; + function createQueue(items) { + var elements = (items === null || items === void 0 ? void 0 : items.slice()) || []; + var headIndex = 0; + function isEmpty() { + return headIndex === elements.length; + } + function enqueue() { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + elements.push.apply(elements, items); + } + function dequeue() { + if (isEmpty()) { + throw new Error("Queue is empty"); + } + var result = elements[headIndex]; + elements[headIndex] = undefined; // Don't keep referencing dequeued item + headIndex++; + // If more than half of the queue is empty, copy the remaining elements to the + // front and shrink the array (unless we'd be saving fewer than 100 slots) + if (headIndex > 100 && headIndex > (elements.length >> 1)) { + var newLength = elements.length - headIndex; + elements.copyWithin(/*target*/ 0, /*start*/ headIndex); + elements.length = newLength; + headIndex = 0; + } + return result; + } + return { + enqueue: enqueue, + dequeue: dequeue, + isEmpty: isEmpty, + }; + } + ts.createQueue = createQueue; /** * Creates a Set with custom equality and hash code functionality. This is useful when you * want to use something looser than object identity - e.g. "has the same span". @@ -1656,6 +1710,10 @@ var ts; /** Does nothing. */ function noop(_) { } ts.noop = noop; + ts.noopPush = { + push: noop, + length: 0 + }; /** Do nothing and return false */ function returnFalse() { return false; @@ -2011,7 +2069,7 @@ var ts; * and 1 insertion/deletion at 3 characters) */ function getSpellingSuggestion(name, candidates, getName) { - var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var maximumLengthDifference = Math.max(2, Math.floor(name.length * 0.34)); var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother. var bestCandidate; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -2238,6 +2296,7 @@ var ts; startsWith(candidate, prefix) && endsWith(candidate, suffix); } + ts.isPatternMatch = isPatternMatch; function and(f, g) { return function (arg) { return f(arg) && g(arg); }; } @@ -2430,6 +2489,7 @@ var ts; var currentAssertionLevel = 0 /* AssertionLevel.None */; Debug.currentLogLevel = LogLevel.Warning; Debug.isDebugging = false; + Debug.enableDeprecationWarnings = true; function getTypeScriptVersion() { return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version)); } @@ -2648,7 +2708,7 @@ var ts; return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; } if (isFlags) { - var result = ""; + var result = []; var remainingFlags = value; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; @@ -2656,12 +2716,12 @@ var ts; break; } if (enumValue !== 0 && enumValue & value) { - result = "".concat(result).concat(result ? "|" : "").concat(enumName); + result.push(enumName); remainingFlags &= ~enumValue; } } if (remainingFlags === 0) { - return result; + return result.join("|"); } } else { @@ -2675,7 +2735,15 @@ var ts; return value.toString(); } Debug.formatEnum = formatEnum; + var enumMemberCache = new ts.Map(); function getEnumMembers(enumObject) { + // Assuming enum objects do not change at runtime, we can cache the enum members list + // to reuse later. This saves us from reconstructing this each and every time we call + // a formatting function (which can be expensive for large enums like SyntaxKind). + var existing = enumMemberCache.get(enumObject); + if (existing) { + return existing; + } var result = []; for (var name in enumObject) { var value = enumObject[name]; @@ -2683,7 +2751,9 @@ var ts; result.push([value, name]); } } - return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + var sorted = ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + enumMemberCache.set(enumObject, sorted); + return sorted; } function formatSyntaxKind(kind) { return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); @@ -2729,6 +2799,22 @@ var ts; return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true); } Debug.formatFlowFlags = formatFlowFlags; + function formatRelationComparisonResult(result) { + return formatEnum(result, ts.RelationComparisonResult, /*isFlags*/ true); + } + Debug.formatRelationComparisonResult = formatRelationComparisonResult; + function formatCheckMode(mode) { + return formatEnum(mode, ts.CheckMode, /*isFlags*/ true); + } + Debug.formatCheckMode = formatCheckMode; + function formatSignatureCheckMode(mode) { + return formatEnum(mode, ts.SignatureCheckMode, /*isFlags*/ true); + } + Debug.formatSignatureCheckMode = formatSignatureCheckMode; + function formatTypeFacts(facts) { + return formatEnum(facts, ts.TypeFacts, /*isFlags*/ true); + } + Debug.formatTypeFacts = formatTypeFacts; var isDebugInfoEnabled = false; var extendedDebugModule; function extendedDebug() { @@ -3027,7 +3113,7 @@ var ts; function createWarningDeprecation(name, errorAfter, since, message) { var hasWrittenDeprecation = false; return function () { - if (!hasWrittenDeprecation) { + if (Debug.enableDeprecationWarnings && !hasWrittenDeprecation) { log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message)); hasWrittenDeprecation = true; } @@ -3046,6 +3132,7 @@ var ts; warn ? createWarningDeprecation(name, errorAfter, since, options.message) : ts.noop; } + Debug.createDeprecation = createDeprecation; function wrapFunction(deprecation, func) { return function () { deprecation(); @@ -3053,10 +3140,53 @@ var ts; }; } function deprecate(func, options) { - var deprecation = createDeprecation(getFunctionName(func), options); + var _a; + var deprecation = createDeprecation((_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : getFunctionName(func), options); return wrapFunction(deprecation, func); } Debug.deprecate = deprecate; + function formatVariance(varianceFlags) { + var variance = varianceFlags & 7 /* VarianceFlags.VarianceMask */; + var result = variance === 0 /* VarianceFlags.Invariant */ ? "in out" : + variance === 3 /* VarianceFlags.Bivariant */ ? "[bivariant]" : + variance === 2 /* VarianceFlags.Contravariant */ ? "in" : + variance === 1 /* VarianceFlags.Covariant */ ? "out" : + variance === 4 /* VarianceFlags.Independent */ ? "[independent]" : ""; + if (varianceFlags & 8 /* VarianceFlags.Unmeasurable */) { + result += " (unmeasurable)"; + } + else if (varianceFlags & 16 /* VarianceFlags.Unreliable */) { + result += " (unreliable)"; + } + return result; + } + Debug.formatVariance = formatVariance; + var DebugTypeMapper = /** @class */ (function () { + function DebugTypeMapper() { + } + DebugTypeMapper.prototype.__debugToString = function () { + var _a; + type(this); + switch (this.kind) { + case 3 /* TypeMapKind.Function */: return ((_a = this.debugInfo) === null || _a === void 0 ? void 0 : _a.call(this)) || "(function mapper)"; + case 0 /* TypeMapKind.Simple */: return "".concat(this.source.__debugTypeToString(), " -> ").concat(this.target.__debugTypeToString()); + case 1 /* TypeMapKind.Array */: return ts.zipWith(this.sources, this.targets || ts.map(this.sources, function () { return "any"; }), function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(typeof t === "string" ? t : t.__debugTypeToString()); }).join(", "); + case 2 /* TypeMapKind.Deferred */: return ts.zipWith(this.sources, this.targets, function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(t().__debugTypeToString()); }).join(", "); + case 5 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: return "m1: ".concat(this.mapper1.__debugToString().split("\n").join("\n "), "\nm2: ").concat(this.mapper2.__debugToString().split("\n").join("\n ")); + default: return assertNever(this); + } + }; + return DebugTypeMapper; + }()); + Debug.DebugTypeMapper = DebugTypeMapper; + function attachDebugPrototypeIfDebug(mapper) { + if (Debug.isDebugging) { + return Object.setPrototypeOf(mapper, DebugTypeMapper.prototype); + } + return mapper; + } + Debug.attachDebugPrototypeIfDebug = attachDebugPrototypeIfDebug; })(Debug = ts.Debug || (ts.Debug = {})); })(ts || (ts = {})); /* @internal */ @@ -3798,9 +3928,9 @@ var ts; eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } tracingEnabled.push = push; - function pop() { + function pop(results) { ts.Debug.assert(eventStack.length > 0); - writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); + writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp(), results); eventStack.length--; } tracingEnabled.pop = pop; @@ -3814,14 +3944,15 @@ var ts; tracingEnabled.popAll = popAll; // sample every 10ms var sampleInterval = 1000 * 10; - function writeStackEvent(index, endTime) { + function writeStackEvent(index, endTime, results) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { + ts.Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`"); writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } // test if [time,endTime) straddles a sampling point else if (sampleInterval - (time % sampleInterval) <= endTime - time) { - writeEvent("X", phase, name, args, "\"dur\":".concat(endTime - time), time); + writeEvent("X", phase, name, __assign(__assign({}, args), { results: results }), "\"dur\":".concat(endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { @@ -4320,6 +4451,7 @@ var ts; SyntaxKind[SyntaxKind["JSDocFunctionType"] = 317] = "JSDocFunctionType"; SyntaxKind[SyntaxKind["JSDocVariadicType"] = 318] = "JSDocVariadicType"; SyntaxKind[SyntaxKind["JSDocNamepathType"] = 319] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; /** @deprecated Use SyntaxKind.JSDoc */ SyntaxKind[SyntaxKind["JSDocComment"] = 320] = "JSDocComment"; SyntaxKind[SyntaxKind["JSDocText"] = 321] = "JSDocText"; @@ -4394,7 +4526,6 @@ var ts; SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 347] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 126] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 160] = "LastContextualKeyword"; - SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4468,6 +4599,7 @@ var ts; ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["In"] = 32768] = "In"; ModifierFlags[ModifierFlags["Out"] = 65536] = "Out"; + ModifierFlags[ModifierFlags["Decorator"] = 131072] = "Decorator"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. @@ -4475,7 +4607,8 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 116958] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 125951] = "All"; + ModifierFlags[ModifierFlags["All"] = 257023] = "All"; + ModifierFlags[ModifierFlags["Modifier"] = 125951] = "Modifier"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4660,6 +4793,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + NodeBuilderFlags[NodeBuilderFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; @@ -4700,6 +4834,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + TypeFormatFlags[TypeFormatFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -4711,7 +4846,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 848330091] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -5100,6 +5235,11 @@ var ts; // Flags that require TypeFlags.Union /* @internal */ ObjectFlags[ObjectFlags["ContainsIntersections"] = 16777216] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnionComputed"] = 33554432] = "IsUnknownLikeUnionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnion"] = 67108864] = "IsUnknownLikeUnion"; + /* @internal */ // Flags that require TypeFlags.Intersection /* @internal */ ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 16777216] = "IsNeverIntersectionComputed"; @@ -5185,9 +5325,10 @@ var ts; (function (TypeMapKind) { TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple"; TypeMapKind[TypeMapKind["Array"] = 1] = "Array"; - TypeMapKind[TypeMapKind["Function"] = 2] = "Function"; - TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite"; - TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged"; + TypeMapKind[TypeMapKind["Deferred"] = 2] = "Deferred"; + TypeMapKind[TypeMapKind["Function"] = 3] = "Function"; + TypeMapKind[TypeMapKind["Composite"] = 4] = "Composite"; + TypeMapKind[TypeMapKind["Merged"] = 5] = "Merged"; })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {})); var InferencePriority; (function (InferencePriority) { @@ -5566,25 +5707,24 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 4096] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; - TransformFlags[TransformFlags["ContainsLexicalSuper"] = 33554432] = "ContainsLexicalSuper"; - TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 67108864] = "ContainsUpdateExpressionForIdentifier"; - // Please leave this as 1 << 29. - // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. - // It is a good reminder of how much room we have left - TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 8192] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 32768] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 65536] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 131072] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 262144] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 524288] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 1048576] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 2097152] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 4194304] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 8388608] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 16777216] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsDecorators"] = 33554432] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 67108864] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsLexicalSuper"] = 134217728] = "ContainsLexicalSuper"; + TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 268435456] = "ContainsUpdateExpressionForIdentifier"; + TransformFlags[TransformFlags["ContainsPrivateIdentifierInExpression"] = 536870912] = "ContainsPrivateIdentifierInExpression"; + TransformFlags[TransformFlags["HasComputedFlags"] = -2147483648] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; @@ -5603,27 +5743,27 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 591310848] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 591306752] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 574529536] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 570433536] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 589443072] = "ModuleExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = -2147483648] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = -2147483648] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = -2147483648] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = -2072174592] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = -1937940480] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = -1937948672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = -2005057536] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = -2013249536] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = -2147344384] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = -1941676032] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; - TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 33562624] = "ContainsLexicalThisOrSuper"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = -2147278848] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = -2147450880] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = -2146893824] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = -2147483648] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = -2147418112] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = -2147450880] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 134234112] = "ContainsLexicalThisOrSuper"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 33562624] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 134234112] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -5796,7 +5936,7 @@ var ts; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["Modifiers"] = 2359808] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; @@ -6191,7 +6331,7 @@ var ts; }; } function createDirectoryWatcher(dirName, dirPath, fallbackOptions) { - var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName) { + var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName, modifiedTime) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" if (!ts.isString(relativeFileName)) return; @@ -6201,7 +6341,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); + fileCallback(fileName, FileWatcherEventKind.Changed, modifiedTime); } } }, @@ -6255,7 +6395,7 @@ var ts; } else { cache.set(path, { - watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options), + watcher: watchFile(fileName, function (fileName, eventKind, modifiedTime) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind, modifiedTime); }); }, pollingInterval, options), refCount: 1 }); } @@ -6283,7 +6423,8 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + // Pass modified times so tsc --build can use it + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime), modifiedTime); return true; } return false; @@ -6318,7 +6459,7 @@ var ts; */ /*@internal*/ function createDirectoryWatcherSupportingRecursive(_a) { - var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, directoryExists = _a.directoryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, fileSystemEntryExists = _a.fileSystemEntryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; var cache = new ts.Map(); var callbackCache = ts.createMultiMap(); var cacheToUpdateChildWatches = new ts.Map(); @@ -6418,7 +6559,7 @@ var ts; function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) { // Iterate through existing children and update the watches if needed var parentWatcher = cache.get(dirPath); - if (parentWatcher && directoryExists(dirName)) { + if (parentWatcher && fileSystemEntryExists(dirName, 1 /* FileSystemEntryKind.Directory */)) { // Schedule the update and postpone invoke for callbacks scheduleUpdateChildWatches(dirName, dirPath, fileName, options); return; @@ -6491,7 +6632,7 @@ var ts; if (!parentWatcher) return false; var newChildWatches; - var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { + var hasChanges = ts.enumerateInsertsAndDeletes(fileSystemEntryExists(parentDir, 1 /* FileSystemEntryKind.Directory */) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch @@ -6534,17 +6675,19 @@ var ts; })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {})); /*@internal*/ function createFileWatcherCallback(callback) { - return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + return function (_fileName, eventKind, modifiedTime) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", "", modifiedTime); }; } ts.createFileWatcherCallback = createFileWatcherCallback; - function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) { - return function (eventName) { + function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime) { + return function (eventName, _relativeFileName, modifiedTime) { if (eventName === "rename") { - callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + // Check time stamps rather than file system entry checks + modifiedTime || (modifiedTime = getModifiedTime(fileName) || ts.missingFileModifiedTime); + callback(fileName, modifiedTime !== ts.missingFileModifiedTime ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted, modifiedTime); } else { // Change - callback(fileName, FileWatcherEventKind.Changed); + callback(fileName, FileWatcherEventKind.Changed, modifiedTime); } }; } @@ -6568,11 +6711,12 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; + var pollingWatchFile = _a.pollingWatchFile, 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 dynamicPollingWatchFile; var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; + var hitSystemWatcherLimit = false; return { watchFile: watchFile, watchDirectory: watchDirectory @@ -6590,7 +6734,7 @@ var ts; case ts.WatchFileKind.FixedChunkSizePolling: return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: - return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), + return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); case ts.WatchFileKind.UseFsEventsOnParentDirectory: if (!nonPollingWatchFile) { @@ -6651,7 +6795,7 @@ var ts; hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - directoryExists: directoryExists, + fileSystemEntryExists: fileSystemEntryExists, getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories, watchDirectory: nonRecursiveWatchDirectory, realpath: realpath, @@ -6702,6 +6846,124 @@ var ts; }; } } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { + var lastDirectoryPartWithDirectorySeparator; + var lastDirectoryPart; + if (inodeWatching) { + lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substring(fileOrDirectory.lastIndexOf(ts.directorySeparator)); + lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); + } + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + if (watcher) { + watcher.close(); + watcher = undefined; + } + } + }; + function updateWatcher(createWatcher) { + // If watcher is not closed, update it + if (watcher) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + if (hitSystemWatcherLimit) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + try { + var presentWatcher = fsWatchWorker(fileOrDirectory, recursive, inodeWatching ? + callbackChangingToMissingFileSystemEntry : + callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { + callback("rename", ""); + updateWatcher(watchMissingFileSystemEntry); + }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + function callbackChangingToMissingFileSystemEntry(event, relativeName) { + // In some scenarios, file save operation fires event with fileName.ext~ instead of fileName.ext + // To ensure we see the file going missing and coming back up (file delete and then recreated) + // and watches being updated correctly we are calling back with fileName.ext as well as fileName.ext~ + // The worst is we have fired event that was not needed but we wont miss any changes + // especially in cases where file goes missing and watches wrong inode + var originalRelativeName; + if (relativeName && ts.endsWith(relativeName, "~")) { + originalRelativeName = relativeName; + relativeName = relativeName.slice(0, relativeName.length - 1); + } + // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations + // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path + if (event === "rename" && + (!relativeName || + relativeName === lastDirectoryPart || + ts.endsWith(relativeName, lastDirectoryPartWithDirectorySeparator))) { + var modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime; + if (originalRelativeName) + callback(event, originalRelativeName, modifiedTime); + callback(event, relativeName, modifiedTime); + if (inodeWatching) { + // If this was rename event, inode has changed means we need to update watcher + updateWatcher(modifiedTime === ts.missingFileModifiedTime ? watchMissingFileSystemEntry : watchPresentFileSystemEntry); + } + else if (modifiedTime === ts.missingFileModifiedTime) { + updateWatcher(watchMissingFileSystemEntry); + } + } + else { + if (originalRelativeName) + callback(event, originalRelativeName); + callback(event, relativeName); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return watchFile(fileOrDirectory, function (_fileName, eventKind, modifiedTime) { + if (eventKind === FileWatcherEventKind.Created) { + modifiedTime || (modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime); + if (modifiedTime !== ts.missingFileModifiedTime) { + callback("rename", "", modifiedTime); + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + updateWatcher(watchPresentFileSystemEntry); + } + } + }, fallbackPollingInterval, fallbackOptions); + } + } } ts.createSystemWatchFunctions = createSystemWatchFunctions; /** @@ -6739,7 +7001,6 @@ var ts; // not actually work. var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { - var _a; var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/; var _fs = require("fs"); var _path = require("path"); @@ -6749,41 +7010,41 @@ var ts; try { _crypto = require("crypto"); } - catch (_b) { + catch (_a) { _crypto = undefined; } var activeSession; var profilePath = "./profile.cpuprofile"; - var hitSystemWatcherLimit = false; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; + var fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); - var _c = createSystemWatchFunctions({ + var _b = createSystemWatchFunctions({ pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames), getModifiedTime: getModifiedTime, setTimeout: setTimeout, clearTimeout: clearTimeout, - fsWatch: fsWatch, + fsWatchWorker: fsWatchWorker, useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - fileExists: fileExists, + fileSystemEntryExists: fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch, - directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, realpath: realpath, 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); }, - }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; + inodeWatching: isLinuxOrMacOs, + sysLog: sysLog, + }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -7032,110 +7293,14 @@ var ts; // File changed eventKind = FileWatcherEventKind.Changed; } - callback(fileName, eventKind); + callback(fileName, eventKind, curr.mtime); } } - function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { - var options; - var lastDirectoryPartWithDirectorySeparator; - var lastDirectoryPart; - if (isLinuxOrMacOs) { - lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator)); - lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); - } - /** Watcher for the file system entry depending on whether it is missing or present */ - var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? - watchMissingFileSystemEntry() : - watchPresentFileSystemEntry(); - return { - close: function () { - // Close the watcher (either existing file system entry watcher or missing file system entry watcher) - watcher.close(); - watcher = undefined; - } - }; - /** - * Invoke the callback with rename and update the watcher if not closed - * @param createWatcher - */ - function invokeCallbackAndUpdateWatcher(createWatcher) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); - // Call the callback for current directory - callback("rename", ""); - // If watcher is not closed, update it - if (watcher) { - watcher.close(); - watcher = createWatcher(); - } - } - /** - * Watch the file or directory that is currently present - * and when the watched file or directory is deleted, switch to missing file system entry watcher - */ - function watchPresentFileSystemEntry() { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows - // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) - if (options === undefined) { - if (fsSupportsRecursiveFsWatch) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - } - if (hitSystemWatcherLimit) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - try { - var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ? - callbackChangingToMissingFileSystemEntry : - callback); - // Watch the missing file or directory or error - presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); - return presentWatcher; - } - catch (e) { - // Catch the exception and use polling instead - // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - // so instead of throwing error, use fs.watchFile - hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - } - function callbackChangingToMissingFileSystemEntry(event, relativeName) { - // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations - // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path - return event === "rename" && - (!relativeName || - relativeName === lastDirectoryPart || - (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && - !fileSystemEntryExists(fileOrDirectory, entryKind) ? - invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : - callback(event, relativeName); - } - /** - * Watch the file or directory using fs.watchFile since fs.watch threw exception - * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - */ - function watchPresentFileSystemEntryWithFsWatchFile() { - return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); - } - /** - * Watch the file or directory that is missing - * and switch to existing file or directory when the missing filesystem entry is created - */ - function watchMissingFileSystemEntry() { - return watchFile(fileOrDirectory, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { - // Call the callback for current file or directory - // For now it could be callback for the inner directory creation, - // but just return current directory, better than current no-op - invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); - } - }, fallbackPollingInterval, fallbackOptions); - } + function fsWatchWorker(fileOrDirectory, recursive, callback) { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + return _fs.watch(fileOrDirectory, fsSupportsRecursiveFsWatch ? + { persistent: true, recursive: !!recursive } : { persistent: true }, callback); } function readFileWorker(fileName, _encoding) { var buffer; @@ -7272,9 +7437,12 @@ var ts; function getDirectories(path) { return getAccessibleFileSystemEntries(path).directories.slice(); } + function fsRealPathHandlingLongPath(path) { + return path.length < 260 ? _fs.realpathSync.native(path) : _fs.realpathSync(path); + } function realpath(path) { try { - return realpathSync(path); + return fsRealpath(path); } catch (_a) { return path; @@ -7282,12 +7450,19 @@ var ts; } function getModifiedTime(path) { var _a; + // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve + // the CPU time performance. + var originalStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; try { return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime; } catch (e) { return undefined; } + finally { + Error.stackTraceLimit = originalStackTraceLimit; + } } function setModifiedTime(path, time) { try { @@ -8142,6 +8317,7 @@ var ts; String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + or_JSX_element_expected: diag(1145, ts.DiagnosticCategory.Error, "or_JSX_element_expected_1145", "'{' or JSX element expected."), Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), @@ -8195,6 +8371,7 @@ var ts; Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), _0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module: diag(1208, ts.DiagnosticCategory.Error, "_0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_imp_1208", "'{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module."), + Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0: diag(1209, ts.DiagnosticCategory.Error, "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209", "Invalid optional chain from new expression. Did you mean to call '{0}()'?"), Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode: diag(1210, ts.DiagnosticCategory.Error, "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210", "Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of '{0}'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode."), A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), @@ -8287,6 +8464,7 @@ var ts; infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Class_constructor_may_not_be_an_accessor: diag(1341, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_an_accessor_1341", "Class constructor may not be an accessor."), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), @@ -8305,6 +8483,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Class_constructor_may_not_be_a_generator: diag(1360, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_a_generator_1360", "Class constructor may not be a generator."), _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."), _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), @@ -8389,18 +8568,30 @@ var ts; Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, ts.DiagnosticCategory.Message, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."), Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments: diag(1450, ts.DiagnosticCategory.Message, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional assertion as arguments"), Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"), - Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "Resolution modes are only supported when `moduleResolution` is `node16` or `nodenext`."), + resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "'resolution-mode' assertions are only supported when `moduleResolution` is `node16` or `nodenext`."), resolution_mode_should_be_either_require_or_import: diag(1453, ts.DiagnosticCategory.Error, "resolution_mode_should_be_either_require_or_import_1453", "`resolution-mode` should be either `require` or `import`."), resolution_mode_can_only_be_set_for_type_only_imports: diag(1454, ts.DiagnosticCategory.Error, "resolution_mode_can_only_be_set_for_type_only_imports_1454", "`resolution-mode` can only be set for type-only imports."), resolution_mode_is_the_only_valid_key_for_type_import_assertions: diag(1455, ts.DiagnosticCategory.Error, "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455", "`resolution-mode` is the only valid key for type import assertions."), Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require: diag(1456, ts.DiagnosticCategory.Error, "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456", "Type import assertions should have exactly one key - `resolution-mode` - with value `import` or `require`."), + Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk: diag(1457, ts.DiagnosticCategory.Message, "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457", "Matched by default include pattern '**/*'"), + File_is_ECMAScript_module_because_0_has_field_type_with_value_module: diag(1458, ts.DiagnosticCategory.Message, "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458", "File is ECMAScript module because '{0}' has field \"type\" with value \"module\""), + File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module: diag(1459, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459", "File is CommonJS module because '{0}' has field \"type\" whose value is not \"module\""), + File_is_CommonJS_module_because_0_does_not_have_field_type: diag(1460, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_does_not_have_field_type_1460", "File is CommonJS module because '{0}' does not have field \"type\""), + File_is_CommonJS_module_because_package_json_was_not_found: diag(1461, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_package_json_was_not_found_1461", "File is CommonJS module because 'package.json' was not found"), The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."), - Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."), + Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported with 'require'. Use an ECMAScript import instead."), catch_or_finally_expected: diag(1472, ts.DiagnosticCategory.Error, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), An_import_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1473, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473", "An import declaration can only be used at the top level of a module."), An_export_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1474, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474", "An export declaration can only be used at the top level of a module."), Control_what_method_is_used_to_detect_module_format_JS_files: diag(1475, ts.DiagnosticCategory.Message, "Control_what_method_is_used_to_detect_module_format_JS_files_1475", "Control what method is used to detect module-format JS files."), auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules: diag(1476, ts.DiagnosticCategory.Message, "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476", "\"auto\": Treat files with imports, exports, import.meta, jsx (with jsx: react-jsx), or esm format (with module: node16+) as modules."), + An_instantiation_expression_cannot_be_followed_by_a_property_access: diag(1477, ts.DiagnosticCategory.Error, "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477", "An instantiation expression cannot be followed by a property access."), + Identifier_or_string_literal_expected: diag(1478, ts.DiagnosticCategory.Error, "Identifier_or_string_literal_expected_1478", "Identifier or string literal expected."), + The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead: diag(1479, ts.DiagnosticCategory.Error, "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479", "The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import(\"{0}\")' call instead."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module: diag(1480, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480", "To convert this file to an ECMAScript module, change its file extension to '{0}' or create a local package.json file with `{ \"type\": \"module\" }`."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1: diag(1481, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481", "To convert this file to an ECMAScript module, change its file extension to '{0}', or add the field `\"type\": \"module\"` to '{1}'."), + To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0: diag(1482, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482", "To convert this file to an ECMAScript module, add the field `\"type\": \"module\"` to '{0}'."), + To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module: diag(1483, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483", "To convert this file to an ECMAScript module, create a local package.json file with `{ \"type\": \"module\" }`."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8409,8 +8600,11 @@ var ts; Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."), The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."), + This_type_parameter_might_need_an_extends_0_constraint: diag(2208, ts.DiagnosticCategory.Error, "This_type_parameter_might_need_an_extends_0_constraint_2208", "This type parameter might need an `extends {0}` constraint."), The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2209, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209", "The project root is ambiguous, but is required to resolve export map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2210, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210", "The project root is ambiguous, but is required to resolve import map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), + Add_extends_constraint: diag(2211, ts.DiagnosticCategory.Message, "Add_extends_constraint_2211", "Add `extends` constraint."), + Add_extends_constraint_to_all_type_parameters: diag(2212, ts.DiagnosticCategory.Message, "Add_extends_constraint_to_all_type_parameters_2212", "Add `extends` constraint to all type parameters"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -8611,6 +8805,7 @@ var ts; Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + A_tuple_type_cannot_be_indexed_with_a_negative_value: diag(2514, ts.DiagnosticCategory.Error, "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514", "A tuple type cannot be indexed with a negative value."), Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), @@ -8893,6 +9088,12 @@ var ts; Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls: diag(2836, ts.DiagnosticCategory.Error, "Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls_2836", "Import assertions are not allowed on statements that transpile to commonjs 'require' calls."), Import_assertion_values_must_be_string_literal_expressions: diag(2837, ts.DiagnosticCategory.Error, "Import_assertion_values_must_be_string_literal_expressions_2837", "Import assertion values must be string literal expressions."), All_declarations_of_0_must_have_identical_constraints: diag(2838, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_constraints_2838", "All declarations of '{0}' must have identical constraints."), + This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value: diag(2839, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839", "This condition will always return '{0}' since JavaScript compares objects by reference, not value."), + An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes: diag(2840, ts.DiagnosticCategory.Error, "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840", "An interface cannot extend a primitive type like '{0}'; an interface can only extend named types and classes"), + The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(2841, ts.DiagnosticCategory.Error, "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841", "The type of this expression cannot be named without a 'resolution-mode' assertion, which is an unstable feature. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + _0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation: diag(2842, ts.DiagnosticCategory.Error, "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842", "'{0}' is an unused renaming of '{1}'. Did you intend to use it as a type annotation?"), + We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here: diag(2843, ts.DiagnosticCategory.Error, "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843", "We can only write a type for '{0}' by adding a type for the entire parameter here."), + Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2844, ts.DiagnosticCategory.Error, "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844", "Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -9000,7 +9201,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), - Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "Resolution mode assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "'resolution-mode' assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -9303,8 +9504,8 @@ var ts; Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Referenced_project_0_may_not_disable_emit: diag(6310, ts.DiagnosticCategory.Error, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."), - Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), - Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_1_is_older_than_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350", "Project '{0}' is out of date because output '{1}' is older than input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than output '{2}'"), Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), @@ -9348,6 +9549,8 @@ var ts; Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6396, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6397, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."), + 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"), 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."), @@ -9588,6 +9791,8 @@ var ts; Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, ts.DiagnosticCategory.Error, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."), The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."), + You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder: diag(8035, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035", "You cannot rename elements that are defined in a 'node_modules' folder."), + You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -9858,6 +10063,9 @@ var ts; For_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, ts.DiagnosticCategory.Error, "For_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'For await' loops cannot be used inside a class static block."), Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, ts.DiagnosticCategory.Error, "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."), A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, ts.DiagnosticCategory.Error, "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."), + _0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation: diag(18042, ts.DiagnosticCategory.Error, "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042", "'{0}' is a type and cannot be imported in JavaScript files. Use '{1}' in a JSDoc type annotation."), + Types_cannot_appear_in_export_declarations_in_JavaScript_files: diag(18043, ts.DiagnosticCategory.Error, "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043", "Types cannot appear in export declarations in JavaScript files."), + _0_is_automatically_exported_here: diag(18044, ts.DiagnosticCategory.Message, "_0_is_automatically_exported_here_18044", "'{0}' is automatically exported here."), }; })(ts || (ts = {})); var ts; @@ -12745,6 +12953,18 @@ var ts; } } ts.getAssignedName = getAssignedName; + function getDecorators(node) { + if (ts.hasDecorators(node)) { + return ts.filter(node.modifiers, ts.isDecorator); + } + } + ts.getDecorators = getDecorators; + function getModifiers(node) { + if (ts.hasSyntacticModifier(node, 125951 /* ModifierFlags.Modifier */)) { + return ts.filter(node.modifiers, isModifier); + } + } + ts.getModifiers = getModifiers; function getJSDocParameterTagsWorker(param, noCache) { if (param.name) { if (ts.isIdentifier(param.name)) { @@ -13015,6 +13235,12 @@ var ts; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + * + * This does *not* return type parameters from a jsdoc reference to a generic type, eg + * + * type Id = (x: T) => T + * /** @type {Id} / + * function id(x) { return x } */ function getEffectiveTypeParameterDeclarations(node) { if (ts.isJSDocSignature(node)) { @@ -13027,6 +13253,9 @@ var ts; if (node.typeParameters) { return node.typeParameters; } + if (ts.canHaveIllegalTypeParameters(node) && node.typeParameters) { + return node.typeParameters; + } if (ts.isInJSFile(node)) { var decls = ts.getJSDocTypeParameterDeclarations(node); if (decls.length) { @@ -13203,6 +13432,19 @@ var ts; return isLiteralKind(node.kind); } ts.isLiteralExpression = isLiteralExpression; + /** @internal */ + function isLiteralExpressionOfObject(node) { + switch (node.kind) { + case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 13 /* SyntaxKind.RegularExpressionLiteral */: + case 213 /* SyntaxKind.FunctionExpression */: + case 226 /* SyntaxKind.ClassExpression */: + return true; + } + return false; + } + ts.isLiteralExpressionOfObject = isLiteralExpressionOfObject; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { @@ -13412,6 +13654,10 @@ var ts; } ts.isMethodOrAccessor = isMethodOrAccessor; // Type members + function isModifierLike(node) { + return isModifier(node) || ts.isDecorator(node); + } + ts.isModifierLike = isModifierLike; function isTypeElement(node) { var kind = node.kind; return kind === 175 /* SyntaxKind.ConstructSignature */ @@ -14021,7 +14267,6 @@ var ts; case 254 /* SyntaxKind.VariableDeclaration */: case 164 /* SyntaxKind.Parameter */: case 203 /* SyntaxKind.BindingElement */: - case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: case 296 /* SyntaxKind.PropertyAssignment */: case 299 /* SyntaxKind.EnumMember */: @@ -14073,6 +14318,16 @@ var ts; return node.kind === 324 /* SyntaxKind.JSDocLink */ || node.kind === 325 /* SyntaxKind.JSDocLinkCode */ || node.kind === 326 /* SyntaxKind.JSDocLinkPlain */; } ts.isJSDocLinkLike = isJSDocLinkLike; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; // #endregion })(ts || (ts = {})); /* @internal */ @@ -14553,10 +14808,11 @@ var ts; } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { - if (nodeIsMissing(node) || !node.decorators) { + var lastDecorator = !nodeIsMissing(node) && ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + if (!lastDecorator) { return getTokenPosOfNode(node, sourceFile); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastDecorator.end); } ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { @@ -15942,7 +16198,7 @@ var ts; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { - return node.decorators !== undefined + return hasDecorators(node) && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; @@ -16018,6 +16274,8 @@ var ts; case 218 /* SyntaxKind.AwaitExpression */: case 231 /* SyntaxKind.MetaProperty */: return true; + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + return !ts.isHeritageClause(node.parent); case 161 /* SyntaxKind.QualifiedName */: while (node.parent.kind === 161 /* SyntaxKind.QualifiedName */) { node = node.parent; @@ -16189,9 +16447,6 @@ var ts; } ts.isVariableDeclarationInitializedToBareOrAccessedRequire = isVariableDeclarationInitializedToBareOrAccessedRequire; function isVariableDeclarationInitializedWithRequireHelper(node, allowAccessedRequire) { - if (node.kind === 203 /* SyntaxKind.BindingElement */) { - node = node.parent.parent; - } return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, /*requireStringLiteralLikeArgument*/ true); @@ -16843,16 +17098,6 @@ var ts; return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function hasRestParameter(s) { - var last = ts.lastOrUndefined(s.parameters); - return !!last && isRestParameter(last); - } - ts.hasRestParameter = hasRestParameter; - function isRestParameter(node) { - var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; - } - ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { return !!node.typeArguments; } @@ -16974,6 +17219,12 @@ var ts; return [child, node]; } ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild; + function skipTypeParentheses(node) { + while (ts.isParenthesizedTypeNode(node)) + node = node.type; + return node; + } + ts.skipTypeParentheses = skipTypeParentheses; function skipParentheses(node, excludeJSDocTypeAssertions) { var flags = excludeJSDocTypeAssertions ? 1 /* OuterExpressionKinds.Parentheses */ | 16 /* OuterExpressionKinds.ExcludeJSDocTypeAssertion */ : @@ -18720,6 +18971,10 @@ var ts; return hasEffectiveModifier(node, 64 /* ModifierFlags.Readonly */); } ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier; + function hasDecorators(node) { + return hasSyntacticModifier(node, 131072 /* ModifierFlags.Decorator */); + } + ts.hasDecorators = hasDecorators; function getSelectedEffectiveModifierFlags(node, flags) { return getEffectiveModifierFlags(node) & flags; } @@ -18797,7 +19052,7 @@ var ts; * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc. */ function getSyntacticModifierFlagsNoCache(node) { - var flags = modifiersToFlags(node.modifiers); + var flags = ts.canHaveModifiers(node) ? modifiersToFlags(node.modifiers) : 0 /* ModifierFlags.None */; if (node.flags & 4 /* NodeFlags.NestedNamespace */ || (node.kind === 79 /* SyntaxKind.Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* ModifierFlags.Export */; } @@ -18831,6 +19086,7 @@ var ts; case 159 /* SyntaxKind.OverrideKeyword */: return 16384 /* ModifierFlags.Override */; case 101 /* SyntaxKind.InKeyword */: return 32768 /* ModifierFlags.In */; case 144 /* SyntaxKind.OutKeyword */: return 65536 /* ModifierFlags.Out */; + case 165 /* SyntaxKind.Decorator */: return 131072 /* ModifierFlags.Decorator */; } return 0 /* ModifierFlags.None */; } @@ -19208,8 +19464,9 @@ var ts; * Moves the start position of a range past any decorators. */ function moveRangePastDecorators(node) { - return node.decorators && node.decorators.length > 0 - ? moveRangePos(node, node.decorators.end) + var lastDecorator = ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + return lastDecorator && !positionIsSynthesized(lastDecorator.end) + ? moveRangePos(node, lastDecorator.end) : node; } ts.moveRangePastDecorators = moveRangePastDecorators; @@ -19217,8 +19474,9 @@ var ts; * Moves the start position of a range past any decorators or modifiers. */ function moveRangePastModifiers(node) { - return node.modifiers && node.modifiers.length > 0 - ? moveRangePos(node, node.modifiers.end) + var lastModifier = ts.canHaveModifiers(node) ? ts.lastOrUndefined(node.modifiers) : undefined; + return lastModifier && !positionIsSynthesized(lastModifier.end) + ? moveRangePos(node, lastModifier.end) : moveRangePastDecorators(node); } ts.moveRangePastModifiers = moveRangePastModifiers; @@ -19340,7 +19598,8 @@ var ts; function getDeclarationModifierFlagsFromSymbol(s, isWrite) { if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 173 /* SyntaxKind.SetAccessor */; })) || s.valueDeclaration; + var declaration = (isWrite && s.declarations && ts.find(s.declarations, ts.isSetAccessorDeclaration)) + || (s.flags & 32768 /* SymbolFlags.GetAccessor */ && ts.find(s.declarations, ts.isGetAccessorDeclaration)) || s.valueDeclaration; var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* SymbolFlags.Class */ ? flags : flags & ~28 /* ModifierFlags.AccessibilityModifier */; } @@ -20013,8 +20272,9 @@ var ts; */ function isFileForcedToBeModuleByFormat(file) { // Excludes declaration files - they still require an explicit `export {}` or the like - // for back compat purposes. - return file.impliedNodeFormat === ts.ModuleKind.ESNext && !file.isDeclarationFile ? true : undefined; + // for back compat purposes. The only non-declaration files _not_ forced to be a module are `.js` files + // that aren't esm-mode (meaning not in a `type: module` scope). + return (file.impliedNodeFormat === ts.ModuleKind.ESNext || (ts.fileExtensionIsOneOf(file.fileName, [".cjs" /* Extension.Cjs */, ".cts" /* Extension.Cts */, ".mjs" /* Extension.Mjs */, ".mts" /* Extension.Mts */]))) && !file.isDeclarationFile ? true : undefined; } function getSetExternalModuleIndicator(options) { // TODO: Should this callback be cached? @@ -20022,7 +20282,7 @@ var ts; case ts.ModuleDetectionKind.Force: // All non-declaration files are modules, declaration files still do the usual isFileProbablyExternalModule return function (file) { - file.externalModuleIndicator = !file.isDeclarationFile || ts.isFileProbablyExternalModule(file); + file.externalModuleIndicator = ts.isFileProbablyExternalModule(file) || !file.isDeclarationFile || undefined; }; case ts.ModuleDetectionKind.Legacy: // Files are modules if they have imports, exports, or import.meta @@ -20037,10 +20297,7 @@ var ts; if (options.jsx === 4 /* JsxEmit.ReactJSX */ || options.jsx === 5 /* JsxEmit.ReactJSXDev */) { checks.push(isFileModuleFromUsingJSXTag); } - var moduleKind = getEmitModuleKind(options); - if (moduleKind === ts.ModuleKind.Node16 || moduleKind === ts.ModuleKind.NodeNext) { - checks.push(isFileForcedToBeModuleByFormat); - } + checks.push(isFileForcedToBeModuleByFormat); var combined_1 = ts.or.apply(void 0, checks); var callback = function (file) { return void (file.externalModuleIndicator = combined_1(file)); }; return callback; @@ -20082,7 +20339,8 @@ var ts; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; function getEmitModuleDetectionKind(options) { - return options.moduleDetection || ts.ModuleDetectionKind.Auto; + return options.moduleDetection || + (getEmitModuleKind(options) === ts.ModuleKind.Node16 || getEmitModuleKind(options) === ts.ModuleKind.NodeNext ? ts.ModuleDetectionKind.Force : ts.ModuleDetectionKind.Auto); } ts.getEmitModuleDetectionKind = getEmitModuleDetectionKind; function hasJsonModuleEmitEnabled(options) { @@ -20165,6 +20423,10 @@ var ts; return optionsHaveChanges(oldOptions, newOptions, ts.affectsEmitOptionDeclarations); } ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit; + function compilerOptionsAffectDeclarationPath(newOptions, oldOptions) { + return optionsHaveChanges(oldOptions, newOptions, ts.affectsDeclarationPathOptionDeclarations); + } + ts.compilerOptionsAffectDeclarationPath = compilerOptionsAffectDeclarationPath; function getCompilerOptionValue(options, option) { return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; } @@ -21105,8 +21367,12 @@ var ts; return node.parent.templateSpans; case 233 /* SyntaxKind.TemplateSpan */: return node.parent.templateSpans; - case 165 /* SyntaxKind.Decorator */: - return node.parent.decorators; + case 165 /* SyntaxKind.Decorator */: { + var parent_2 = node.parent; + return ts.canHaveDecorators(parent_2) ? parent_2.modifiers : + ts.canHaveIllegalDecorators(parent_2) ? parent_2.illegalDecorators : + undefined; + } case 291 /* SyntaxKind.HeritageClause */: return node.parent.heritageClauses; } @@ -21620,7 +21886,7 @@ var ts; * Wraps an expression in parentheses if it is needed in order to use the expression for * property or element access. */ - function parenthesizeLeftSideOfAccess(expression) { + function parenthesizeLeftSideOfAccess(expression, optionalChain) { // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exception is: // @@ -21629,7 +21895,8 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments) + && (optionalChain || !ts.isOptionalChain(emittedExpression))) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -22576,13 +22843,8 @@ var ts; function createBaseNode(kind) { return baseFactory.createBaseNode(kind); } - function createBaseDeclaration(kind, decorators, modifiers) { + function createBaseDeclaration(kind) { var node = createBaseNode(kind); - node.decorators = asNodeArray(decorators); - node.modifiers = asNodeArray(modifiers); - node.transformFlags |= - propagateChildrenFlags(node.decorators) | - propagateChildrenFlags(node.modifiers); // NOTE: The following properties are commonly set by the binder and are added here to // ensure declarations have a stable shape. node.symbol = undefined; // initialized by binder @@ -22591,10 +22853,15 @@ var ts; node.nextContainer = undefined; // initialized by binder return node; } - function createBaseNamedDeclaration(kind, decorators, modifiers, name) { - var node = createBaseDeclaration(kind, decorators, modifiers); + function createBaseNamedDeclaration(kind, modifiers, name) { + var node = createBaseDeclaration(kind); name = asName(name); node.name = name; + if (ts.canHaveModifiers(node)) { + node.modifiers = asNodeArray(modifiers); + node.transformFlags |= propagateChildrenFlags(node.modifiers); + // node.decorators = filter(node.modifiers, isDecorator); + } // The PropertyName of a member is allowed to be `await`. // We don't need to exclude `await` for type signatures since types // don't propagate child flags. @@ -22617,16 +22884,16 @@ var ts; } return node; } - function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.typeParameters = asNodeArray(typeParameters); node.transformFlags |= propagateChildrenFlags(node.typeParameters); if (typeParameters) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.parameters = createNodeArray(parameters); node.type = type; node.transformFlags |= @@ -22634,50 +22901,45 @@ var ts; propagateChildFlags(node.type); if (type) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used for quick info + node.typeArguments = undefined; return node; } - function updateBaseSignatureDeclaration(updated, original) { - // copy children used only for error reporting - if (original.typeArguments) + function finishUpdateBaseSignatureDeclaration(updated, original) { + if (updated !== original) { + // copy children used for quick info updated.typeArguments = original.typeArguments; + } return update(updated, original); } - function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { - var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); + function createBaseFunctionLikeDeclaration(kind, modifiers, name, typeParameters, parameters, type, body) { + var node = createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateBaseFunctionLikeDeclaration(updated, original) { - // copy children used only for error reporting - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - if (original.typeArguments) - updated.typeArguments = original.typeArguments; - return updateBaseSignatureDeclaration(updated, original); - } - function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.heritageClauses = asNodeArray(heritageClauses); node.transformFlags |= propagateChildrenFlags(node.heritageClauses); return node; } - function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses); + function createBaseClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members); return node; } - function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseBindingLikeDeclaration(kind, modifiers, name, initializer) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.initializer = initializer; node.transformFlags |= propagateChildFlags(node.initializer); return node; } - function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) { - var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer); + function createBaseVariableLikeDeclaration(kind, modifiers, name, type, initializer) { + var node = createBaseBindingLikeDeclaration(kind, modifiers, name, initializer); node.type = type; node.transformFlags |= propagateChildFlags(type); if (type) @@ -22773,7 +23035,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 132 /* SyntaxKind.AwaitKeyword */) { - node.transformFlags |= 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } return node; } @@ -22825,7 +23087,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(80 /* SyntaxKind.PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags |= 16777216 /* TransformFlags.ContainsClassFields */; return node; } // @@ -22872,14 +23134,14 @@ var ts; transformFlags = 1 /* TransformFlags.ContainsTypeScript */; break; case 106 /* SyntaxKind.SuperKeyword */: - transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 33554432 /* TransformFlags.ContainsLexicalSuper */; + transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 134217728 /* TransformFlags.ContainsLexicalSuper */; break; case 124 /* SyntaxKind.StaticKeyword */: transformFlags = 1024 /* TransformFlags.ContainsES2015 */; break; case 108 /* SyntaxKind.ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 8192 /* TransformFlags.ContainsLexicalThis */; + transformFlags = 16384 /* TransformFlags.ContainsLexicalThis */; break; } if (transformFlags) { @@ -22977,7 +23239,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 65536 /* TransformFlags.ContainsComputedPropertyName */; + 131072 /* TransformFlags.ContainsComputedPropertyName */; return node; } // @api @@ -22986,41 +23248,19 @@ var ts; ? update(createComputedPropertyName(expression), node) : node; } - function createTypeParameterDeclaration(modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } - var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, - /*decorators*/ undefined, modifiers, name); + // + // Signature elements + // + // @api + function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) { + var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, modifiers, name); node.constraint = constraint; node.default = defaultType; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateTypeParameterDeclaration(node, modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } + // @api + function updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType) { return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint @@ -23029,8 +23269,8 @@ var ts; : node; } // @api - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -23043,32 +23283,32 @@ var ts; if (questionToken) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; if (ts.modifiersToFlags(node.modifiers) & 16476 /* ModifierFlags.ParameterPropertyModifier */) - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; } return node; } // @api - function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } // @api function createDecorator(expression) { var node = createBaseNode(165 /* SyntaxKind.Decorator */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */ | - 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */ | + 33554432 /* TransformFlags.ContainsDecorators */; return node; } // @api @@ -23082,11 +23322,12 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, - /*decorators*/ undefined, modifiers, name); + var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, modifiers, name); node.type = type; node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.initializer = undefined; return node; } // @api @@ -23095,20 +23336,27 @@ var ts; || node.name !== name || node.questionToken !== questionToken || node.type !== type - ? update(createPropertySignature(modifiers, name, questionToken, type), node) + ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) : node; } + function finishUpdatePropertySignature(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.initializer = original.initializer; + } + return update(updated, original); + } // @api - function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, decorators, modifiers, name, type, initializer); + function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 8388608 /* TransformFlags.ContainsClassFields */; + 16777216 /* TransformFlags.ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; @@ -23116,21 +23364,19 @@ var ts; return node; } // @api - function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.modifiers !== modifiers || node.name !== name || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer - ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23143,12 +23389,12 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node; } // @api - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= @@ -23169,12 +23415,13 @@ var ts; else if (asteriskToken) { node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } + // The following properties are used only to report grammar errors + node.exclamationToken = undefined; return node; } // @api - function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.questionToken !== questionToken @@ -23182,80 +23429,123 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } + function finishUpdateMethodDeclaration(updated, original) { + if (updated !== original) { + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api - function createClassStaticBlockDeclaration(decorators, modifiers, body) { - var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, decorators, modifiers, + function createClassStaticBlockDeclaration(body) { + var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, + /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined); node.body = body; - node.transformFlags = propagateChildFlags(body) | 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags = propagateChildFlags(body) | 16777216 /* TransformFlags.ContainsClassFields */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api - function updateClassStaticBlockDeclaration(node, decorators, modifiers, body) { - return node.decorators !== decorators - || node.modifier !== modifiers - || node.body !== body - ? update(createClassStaticBlockDeclaration(decorators, modifiers, body), node) + function updateClassStaticBlockDeclaration(node, body) { + return node.body !== body + ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) : node; } + function finishUpdateClassStaticBlockDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, decorators, modifiers, + function createConstructorDeclaration(modifiers, parameters, body) { + var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.typeParameters = undefined; + node.type = undefined; return node; } // @api - function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateConstructorDeclaration(node, modifiers, parameters, body) { + return node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node) + ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) : node; } + function finishUpdateConstructorDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, decorators, modifiers, name, + function createGetAccessorDeclaration(modifiers, name, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + return node; } // @api - function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node) + ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) : node; } + function finishUpdateGetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, decorators, modifiers, name, + function createSetAccessorDeclaration(modifiers, name, parameters, body) { + var node = createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + node.type = undefined; + return node; } // @api - function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateSetAccessorDeclaration(node, modifiers, name, parameters, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node) + ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) : node; } + function finishUpdateSetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createCallSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(174 /* SyntaxKind.CallSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23266,13 +23556,12 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node; } // @api function createConstructSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(175 /* SyntaxKind.ConstructSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23283,24 +23572,23 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node; } // @api - function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, decorators, modifiers, + function createIndexSignature(modifiers, parameters, type) { + var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } // @api - function updateIndexSignature(node, decorators, modifiers, parameters, type) { + function updateIndexSignature(node, modifiers, parameters, type) { return node.parameters !== parameters || node.type !== type - || node.decorators !== decorators || node.modifiers !== modifiers - ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node; } // @api @@ -23360,10 +23648,11 @@ var ts; // @api function createFunctionTypeNode(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(179 /* SyntaxKind.FunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.modifiers = undefined; return node; } // @api @@ -23371,9 +23660,15 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node) + ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) : node; } + function finishUpdateFunctionTypeNode(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createConstructorTypeNode() { var args = []; @@ -23385,8 +23680,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, - /*decorators*/ undefined, modifiers, + var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23410,7 +23704,7 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node; } /** @deprecated */ @@ -23590,33 +23884,27 @@ var ts; ? update(createTemplateLiteralType(head, templateSpans), node) : node; } - function createImportTypeNode(argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : false; + // @api + function createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = false; } var node = createBaseNode(200 /* SyntaxKind.ImportType */); node.argument = argument; - node.assertions = assertion; + node.assertions = assertions; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.isTypeOf = isTypeOf; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateImportTypeNode(node, argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : node.isTypeOf; + // @api + function updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; } return node.argument !== argument - || node.assertions !== assertion + || node.assertions !== assertions || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf - ? update(createImportTypeNode(argument, assertion, qualifier, typeArguments, isTypeOf), node) + ? update(createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf), node) : node; } // @api @@ -23715,11 +24003,11 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + 524288 /* TransformFlags.ContainsBindingPattern */; + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } return node; } @@ -23736,7 +24024,7 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; + 524288 /* TransformFlags.ContainsBindingPattern */; return node; } // @api @@ -23748,7 +24036,6 @@ var ts; // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(203 /* SyntaxKind.BindingElement */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; @@ -23761,7 +24048,7 @@ var ts; propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 16384 /* TransformFlags.ContainsRestOrSpread */; + node.transformFlags |= 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -23817,13 +24104,13 @@ var ts; // @api function createPropertyAccessExpression(expression, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.name = asName(name); node.transformFlags = propagateChildFlags(node.expression) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); if (ts.isSuperKeyword(expression)) { // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators @@ -23847,7 +24134,7 @@ var ts; function createPropertyAccessChain(expression, questionDotToken, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= @@ -23856,7 +24143,7 @@ var ts; propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); return node; } // @api @@ -23873,7 +24160,7 @@ var ts; // @api function createElementAccessExpression(expression, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.argumentExpression = asExpression(index); node.transformFlags |= propagateChildFlags(node.expression) | @@ -23901,7 +24188,7 @@ var ts; function createElementAccessChain(expression, questionDotToken, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.argumentExpression = asExpression(index); node.transformFlags |= @@ -23925,7 +24212,7 @@ var ts; // @api function createCallExpression(expression, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); node.transformFlags |= @@ -23936,10 +24223,10 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 4194304 /* TransformFlags.ContainsDynamicImport */; + node.transformFlags |= 8388608 /* TransformFlags.ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -23958,7 +24245,7 @@ var ts; function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -23972,7 +24259,7 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24013,7 +24300,7 @@ var ts; // @api function createTaggedTemplateExpression(tag, typeArguments, template) { var node = createBaseExpression(210 /* SyntaxKind.TaggedTemplateExpression */); - node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); + node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.template = template; node.transformFlags |= @@ -24070,8 +24357,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); if (node.typeParameters) { @@ -24099,20 +24385,19 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, - /*decorators*/ undefined, modifiers, + var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* SyntaxKind.EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | 1024 /* TransformFlags.ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { - node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24124,7 +24409,7 @@ var ts; || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } // @api @@ -24174,7 +24459,7 @@ var ts; propagateChildFlags(node.expression) | 256 /* TransformFlags.ContainsES2017 */ | 128 /* TransformFlags.ContainsES2018 */ | - 1048576 /* TransformFlags.ContainsAwait */; + 2097152 /* TransformFlags.ContainsAwait */; return node; } // @api @@ -24195,7 +24480,7 @@ var ts; ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -24216,7 +24501,7 @@ var ts; if (ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -24262,11 +24547,14 @@ var ts; else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { node.transformFlags |= 16 /* TransformFlags.ContainsES2021 */; } + if (operatorKind === 101 /* SyntaxKind.InKeyword */ && ts.isPrivateIdentifier(node.left)) { + node.transformFlags |= 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */; + } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; if (node.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer @@ -24274,8 +24562,8 @@ var ts; var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (target.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } if (target.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); @@ -24401,7 +24689,7 @@ var ts; propagateChildFlags(node.asteriskToken) | 1024 /* TransformFlags.ContainsES2015 */ | 128 /* TransformFlags.ContainsES2018 */ | - 524288 /* TransformFlags.ContainsYield */; + 1048576 /* TransformFlags.ContainsYield */; return node; } // @api @@ -24418,7 +24706,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 16384 /* TransformFlags.ContainsRestOrSpread */; + 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -24428,20 +24716,19 @@ var ts; : node; } // @api - function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, modifiers, name, typeParameters, heritageClauses, members); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; return node; } // @api - function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api @@ -24451,7 +24738,7 @@ var ts; // @api function createExpressionWithTypeArguments(expression, typeArguments) { var node = createBaseNode(228 /* SyntaxKind.ExpressionWithTypeArguments */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24487,7 +24774,7 @@ var ts; // @api function createNonNullExpression(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -24506,7 +24793,7 @@ var ts; function createNonNullChain(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -24589,10 +24876,12 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */); + node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= - propagateChildFlags(node.declarationList); + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.declarationList); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } @@ -24751,7 +25040,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24766,7 +25055,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24783,7 +25072,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24883,7 +25172,6 @@ var ts; // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { var node = createBaseVariableLikeDeclaration(254 /* SyntaxKind.VariableDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; node.transformFlags |= propagateChildFlags(node.exclamationToken); @@ -24909,11 +25197,11 @@ var ts; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* NodeFlags.BlockScoped */) { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */ | - 131072 /* TransformFlags.ContainsBlockScopedBinding */; + 262144 /* TransformFlags.ContainsBlockScopedBinding */; } return node; } @@ -24924,8 +25212,8 @@ var ts; : node; } // @api - function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -24933,7 +25221,7 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { if (node.asteriskToken) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */; @@ -24946,104 +25234,133 @@ var ts; node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } } + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } + function finishUpdateFunctionDeclaration(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.illegalDecorators = original.illegalDecorators; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } else { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; - if (node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */) { + if (node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } } return node; } // @api - function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api - function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? finishUpdateInterfaceDeclaration(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } + function finishUpdateInterfaceDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + function createTypeAliasDeclaration(modifiers, name, typeParameters, type) { + var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type - ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + ? finishUpdateTypeAliasDeclaration(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; } + function finishUpdateTypeAliasDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, decorators, modifiers, name); + function createEnumDeclaration(modifiers, name, members) { + var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateEnumDeclaration(node, decorators, modifiers, name, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateEnumDeclaration(node, modifiers, name, members) { + return node.modifiers !== modifiers || node.name !== name || node.members !== members - ? update(createEnumDeclaration(decorators, modifiers, name, members), node) + ? finishUpdateEnumDeclaration(createEnumDeclaration(modifiers, name, members), node) : node; } + function finishUpdateEnumDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createModuleDeclaration(decorators, modifiers, name, body, flags) { + function createModuleDeclaration(modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* NodeFlags.None */; } - var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */); + node.modifiers = asNodeArray(modifiers); node.flags |= flags & (16 /* NodeFlags.Namespace */ | 4 /* NodeFlags.NestedNamespace */ | 1024 /* NodeFlags.GlobalAugmentation */); node.name = name; node.body = body; @@ -25052,22 +25369,30 @@ var ts; } else { node.transformFlags |= - propagateChildFlags(node.name) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateModuleDeclaration(node, decorators, modifiers, name, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateModuleDeclaration(node, modifiers, name, body) { + return node.modifiers !== modifiers || node.name !== name || node.body !== body - ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + ? finishUpdateModuleDeclaration(createModuleDeclaration(modifiers, name, body, node.flags), node) : node; } + function finishUpdateModuleDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createModuleBlock(statements) { var node = createBaseNode(262 /* SyntaxKind.ModuleBlock */); @@ -25097,60 +25422,84 @@ var ts; // @api function createNamespaceExportDeclaration(name) { var node = createBaseNamedDeclaration(264 /* SyntaxKind.NamespaceExportDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api function updateNamespaceExportDeclaration(node, name) { return node.name !== name - ? update(createNamespaceExportDeclaration(name), node) + ? finishUpdateNamespaceExportDeclaration(createNamespaceExportDeclaration(name), node) : node; } + function finishUpdateNamespaceExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, decorators, modifiers, name); + function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) { + var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference - ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node) + ? finishUpdateImportEqualsDeclaration(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; } + function finishUpdateImportEqualsDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */, decorators, modifiers); + function createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause), node) + ? finishUpdateImportDeclaration(createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateImportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createImportClause(isTypeOnly, name, namedBindings) { var node = createBaseNode(267 /* SyntaxKind.ImportClause */); @@ -25163,7 +25512,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25223,7 +25572,7 @@ var ts; var node = createBaseNode(268 /* SyntaxKind.NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25239,7 +25588,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.name) | 4 /* TransformFlags.ContainsESNext */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25253,7 +25602,7 @@ var ts; var node = createBaseNode(269 /* SyntaxKind.NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25271,7 +25620,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25283,54 +25632,71 @@ var ts; : node; } // @api - function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */, decorators, modifiers); + function createExportAssignment(modifiers, isExportEquals, expression) { + var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */); + node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(63 /* SyntaxKind.EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); - node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportAssignment(node, decorators, modifiers, expression) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportAssignment(node, modifiers, expression) { + return node.modifiers !== modifiers || node.expression !== expression - ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + ? finishUpdateExportAssignment(createExportAssignment(modifiers, node.isExportEquals, expression), node) : node; } + function finishUpdateExportAssignment(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */, decorators, modifiers); + function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= - propagateChildFlags(node.exportClause) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) + ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createNamedExports(elements) { var node = createBaseNode(273 /* SyntaxKind.NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25348,7 +25714,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25361,9 +25727,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */, - /*decorators*/ undefined, - /*modifiers*/ undefined); + var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */); return node; } // @@ -25374,7 +25738,7 @@ var ts; var node = createBaseNode(277 /* SyntaxKind.ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25430,7 +25794,6 @@ var ts; // @api function createJSDocFunctionType(parameters, type) { var node = createBaseSignatureDeclaration(317 /* SyntaxKind.JSDocFunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); @@ -26082,26 +26445,18 @@ var ts; // @api function createPropertyAssignment(name, initializer) { var node = createBaseNamedDeclaration(296 /* SyntaxKind.PropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer); + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdatePropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updatePropertyAssignment(node, name, initializer) { return node.name !== name @@ -26109,31 +26464,32 @@ var ts; ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) : node; } + function finishUpdatePropertyAssignment(updated, original) { + // copy children used only for error reporting + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { var node = createBaseNamedDeclaration(297 /* SyntaxKind.ShorthandPropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.equalsToken = undefined; + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdateShorthandPropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.equalsToken) - updated.equalsToken = original.equalsToken; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { return node.name !== name @@ -26141,6 +26497,17 @@ var ts; ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) : node; } + function finishUpdateShorthandPropertyAssignment(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.equalsToken = original.equalsToken; + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createSpreadAssignment(expression) { var node = createBaseNode(298 /* SyntaxKind.SpreadAssignment */); @@ -26148,7 +26515,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; return node; } // @api @@ -26468,13 +26835,11 @@ var ts; } function createExportDefault(expression) { return createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); } function createExternalModuleExport(exportName) { return createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, createNamedExports([ createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName) @@ -26632,7 +26997,7 @@ var ts; } else if (ts.getEmitFlags(callee) & 4096 /* EmitFlags.HelperName */) { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee, /*optionalChain*/ false); } else if (ts.isPropertyAccessExpression(callee)) { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { @@ -26661,7 +27026,7 @@ var ts; else { // for `a()` target is `a` and thisArg is `void 0` thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); } return { target: target, thisArg: thisArg }; } @@ -26670,9 +27035,7 @@ var ts; // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560) createParenthesizedExpression(createObjectLiteralExpression([ createSetAccessorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, "value", [createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, paramName, /*questionToken*/ undefined, @@ -26974,30 +27337,32 @@ var ts; else { modifierArray = modifiers; } - return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : - ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : - ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : - ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifierArray, node.parameters, node.body) : - ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.type, node.body) : - ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.body) : - ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifierArray, node.parameters, node.type) : - ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : - ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : - ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.type) : - ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifierArray, node.name, node.members) : - ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifierArray, node.name, node.body) : - ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : - ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : - ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifierArray, node.expression) : - ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : - ts.Debug.assertNever(node); + return ts.isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : + ts.isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : + ts.isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : + ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : + ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : + ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : + ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : + ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : + ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : + ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : + ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : + ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : + ts.isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : + ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : + ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : + ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : + ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : + ts.isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : + ts.isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : + ts.isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : + ts.Debug.assertNever(node); } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -27105,10 +27470,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 33562624 /* TransformFlags.PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 134234112 /* TransformFlags.PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -27139,29 +27504,29 @@ var ts; case 208 /* SyntaxKind.CallExpression */: case 209 /* SyntaxKind.NewExpression */: case 204 /* SyntaxKind.ArrayLiteralExpression */: - return 536887296 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; + return -2147450880 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; case 261 /* SyntaxKind.ModuleDeclaration */: - return 589443072 /* TransformFlags.ModuleExcludes */; + return -1941676032 /* TransformFlags.ModuleExcludes */; case 164 /* SyntaxKind.Parameter */: - return 536870912 /* TransformFlags.ParameterExcludes */; + return -2147483648 /* TransformFlags.ParameterExcludes */; case 214 /* SyntaxKind.ArrowFunction */: - return 557748224 /* TransformFlags.ArrowFunctionExcludes */; + return -2072174592 /* TransformFlags.ArrowFunctionExcludes */; case 213 /* SyntaxKind.FunctionExpression */: case 256 /* SyntaxKind.FunctionDeclaration */: - return 591310848 /* TransformFlags.FunctionExcludes */; + return -1937940480 /* TransformFlags.FunctionExcludes */; case 255 /* SyntaxKind.VariableDeclarationList */: - return 537165824 /* TransformFlags.VariableDeclarationListExcludes */; + return -2146893824 /* TransformFlags.VariableDeclarationListExcludes */; case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return 536940544 /* TransformFlags.ClassExcludes */; + return -2147344384 /* TransformFlags.ClassExcludes */; case 171 /* SyntaxKind.Constructor */: - return 591306752 /* TransformFlags.ConstructorExcludes */; + return -1937948672 /* TransformFlags.ConstructorExcludes */; case 167 /* SyntaxKind.PropertyDeclaration */: - return 570433536 /* TransformFlags.PropertyExcludes */; + return -2013249536 /* TransformFlags.PropertyExcludes */; case 169 /* SyntaxKind.MethodDeclaration */: case 172 /* SyntaxKind.GetAccessor */: case 173 /* SyntaxKind.SetAccessor */: - return 574529536 /* TransformFlags.MethodOrAccessorExcludes */; + return -2005057536 /* TransformFlags.MethodOrAccessorExcludes */; case 130 /* SyntaxKind.AnyKeyword */: case 147 /* SyntaxKind.NumberKeyword */: case 158 /* SyntaxKind.BigIntKeyword */: @@ -27181,23 +27546,23 @@ var ts; case 259 /* SyntaxKind.TypeAliasDeclaration */: return -2 /* TransformFlags.TypeExcludes */; case 205 /* SyntaxKind.ObjectLiteralExpression */: - return 536973312 /* TransformFlags.ObjectLiteralExcludes */; + return -2147278848 /* TransformFlags.ObjectLiteralExcludes */; case 292 /* SyntaxKind.CatchClause */: - return 536903680 /* TransformFlags.CatchClauseExcludes */; + return -2147418112 /* TransformFlags.CatchClauseExcludes */; case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: - return 536887296 /* TransformFlags.BindingPatternExcludes */; + return -2147450880 /* TransformFlags.BindingPatternExcludes */; case 211 /* SyntaxKind.TypeAssertionExpression */: case 229 /* SyntaxKind.AsExpression */: case 350 /* SyntaxKind.PartiallyEmittedExpression */: case 212 /* SyntaxKind.ParenthesizedExpression */: case 106 /* SyntaxKind.SuperKeyword */: - return 536870912 /* TransformFlags.OuterExpressionExcludes */; + return -2147483648 /* TransformFlags.OuterExpressionExcludes */; case 206 /* SyntaxKind.PropertyAccessExpression */: case 207 /* SyntaxKind.ElementAccessExpression */: - return 536870912 /* TransformFlags.PropertyAccessExcludes */; + return -2147483648 /* TransformFlags.PropertyAccessExcludes */; default: - return 536870912 /* TransformFlags.NodeExcludes */; + return -2147483648 /* TransformFlags.NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -28607,6 +28972,11 @@ var ts; return node.kind === 126 /* SyntaxKind.AbstractKeyword */; } ts.isAbstractModifier = isAbstractModifier; + /* @internal */ + function isOverrideModifier(node) { + return node.kind === 159 /* SyntaxKind.OverrideKeyword */; + } + ts.isOverrideModifier = isOverrideModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 106 /* SyntaxKind.SuperKeyword */; @@ -29062,6 +29432,10 @@ var ts; return node.kind === 267 /* SyntaxKind.ImportClause */; } ts.isImportClause = isImportClause; + function isImportTypeAssertionContainer(node) { + return node.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */; + } + ts.isImportTypeAssertionContainer = isImportTypeAssertionContainer; function isAssertClause(node) { return node.kind === 293 /* SyntaxKind.AssertClause */; } @@ -29399,7 +29773,7 @@ var ts; (function (ts) { // Compound nodes function createEmptyExports(factory) { - return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); + return factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); } ts.createEmptyExports = createEmptyExports; function createMemberAccessForPropertyName(factory, target, memberName, location) { @@ -29549,13 +29923,13 @@ var ts; return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({ enumerable: factory.createFalse(), configurable: true, - get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, + get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(getAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, /*type*/ undefined, getAccessor.body // TODO: GH#18217 ), getAccessor), getAccessor), - set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, + set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(setAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, @@ -29574,7 +29948,7 @@ var ts; /*original*/ property); } function createExpressionForMethodDeclaration(factory, method, receiver) { - return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken, + return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(ts.getModifiers(method), method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, /*type*/ undefined, method.body // TODO: GH#18217 @@ -29807,7 +30181,6 @@ var ts; } if (namedBindings) { var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText), /*assertClause*/ undefined); ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* EmitFlags.NeverApplyImportHelper */); @@ -30126,33 +30499,50 @@ var ts; } } ts.getJSDocTypeAliasName = getJSDocTypeAliasName; - function canHaveModifiers(node) { + function canHaveIllegalType(node) { var kind = node.kind; - return kind === 164 /* SyntaxKind.Parameter */ - || kind === 166 /* SyntaxKind.PropertySignature */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 168 /* SyntaxKind.MethodSignature */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ + return kind === 171 /* SyntaxKind.Constructor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalType = canHaveIllegalType; + function canHaveIllegalTypeParameters(node) { + var kind = node.kind; + return kind === 171 /* SyntaxKind.Constructor */ || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalTypeParameters = canHaveIllegalTypeParameters; + function canHaveIllegalDecorators(node) { + var kind = node.kind; + return kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 213 /* SyntaxKind.FunctionExpression */ - || kind === 214 /* SyntaxKind.ArrowFunction */ - || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ || kind === 237 /* SyntaxKind.VariableStatement */ - || kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 257 /* SyntaxKind.ClassDeclaration */ || kind === 258 /* SyntaxKind.InterfaceDeclaration */ || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ || kind === 260 /* SyntaxKind.EnumDeclaration */ || kind === 261 /* SyntaxKind.ModuleDeclaration */ || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ || kind === 266 /* SyntaxKind.ImportDeclaration */ - || kind === 271 /* SyntaxKind.ExportAssignment */ - || kind === 272 /* SyntaxKind.ExportDeclaration */; + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ + || kind === 272 /* SyntaxKind.ExportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */; } - ts.canHaveModifiers = canHaveModifiers; + ts.canHaveIllegalDecorators = canHaveIllegalDecorators; + function canHaveIllegalModifiers(node) { + var kind = node.kind; + return kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 179 /* SyntaxKind.FunctionType */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */; + } + ts.canHaveIllegalModifiers = canHaveIllegalModifiers; ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); @@ -30416,6 +30806,14 @@ var ts; } } ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; + function elideNodes(factory, nodes) { + if (nodes === undefined) + return undefined; + if (nodes.length === 0) + return nodes; + return ts.setTextRange(factory.createNodeArray([], nodes.hasTrailingComma), nodes); + } + ts.elideNodes = elideNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -30423,6 +30821,46 @@ var ts; return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range; } ts.setTextRange = setTextRange; + function canHaveModifiers(node) { + var kind = node.kind; + return kind === 163 /* SyntaxKind.TypeParameter */ + || kind === 164 /* SyntaxKind.Parameter */ + || kind === 166 /* SyntaxKind.PropertySignature */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 168 /* SyntaxKind.MethodSignature */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 176 /* SyntaxKind.IndexSignature */ + || kind === 180 /* SyntaxKind.ConstructorType */ + || kind === 213 /* SyntaxKind.FunctionExpression */ + || kind === 214 /* SyntaxKind.ArrowFunction */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 237 /* SyntaxKind.VariableStatement */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 257 /* SyntaxKind.ClassDeclaration */ + || kind === 258 /* SyntaxKind.InterfaceDeclaration */ + || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 260 /* SyntaxKind.EnumDeclaration */ + || kind === 261 /* SyntaxKind.ModuleDeclaration */ + || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 266 /* SyntaxKind.ImportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */ + || kind === 272 /* SyntaxKind.ExportDeclaration */; + } + ts.canHaveModifiers = canHaveModifiers; + function canHaveDecorators(node) { + var kind = node.kind; + return kind === 164 /* SyntaxKind.Parameter */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 257 /* SyntaxKind.ClassDeclaration */; + } + ts.canHaveDecorators = canHaveDecorators; })(ts || (ts = {})); var ts; (function (ts) { @@ -30492,7 +30930,7 @@ var ts; } ts.isFileProbablyExternalModule = isFileProbablyExternalModule; function isAnExternalModuleIndicatorNode(node) { - return hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) + return ts.canHaveModifiers(node) && hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) || ts.isImportDeclaration(node) || ts.isExportAssignment(node) @@ -30541,7 +30979,7 @@ var ts; visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || @@ -30551,79 +30989,128 @@ var ts; case 298 /* SyntaxKind.SpreadAssignment */: return visitNode(cbNode, node.expression); case 164 /* SyntaxKind.Parameter */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 167 /* SyntaxKind.PropertyDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 166 /* SyntaxKind.PropertySignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 296 /* SyntaxKind.PropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.initializer); case 254 /* SyntaxKind.VariableDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || + return visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 203 /* SyntaxKind.BindingElement */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.dotDotDotToken) || + return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: case 176 /* SyntaxKind.IndexSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); + case 180 /* SyntaxKind.ConstructorType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 179 /* SyntaxKind.FunctionType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + return visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 169 /* SyntaxKind.MethodDeclaration */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 168 /* SyntaxKind.MethodSignature */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 171 /* SyntaxKind.Constructor */: + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 172 /* SyntaxKind.GetAccessor */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 256 /* SyntaxKind.FunctionDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 214 /* SyntaxKind.ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.body); case 178 /* SyntaxKind.TypeReference */: @@ -30751,7 +31238,7 @@ var ts; return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); case 237 /* SyntaxKind.VariableStatement */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); case 255 /* SyntaxKind.VariableDeclarationList */: @@ -30816,27 +31303,26 @@ var ts; return visitNode(cbNode, node.expression); case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 258 /* SyntaxKind.InterfaceDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); case 260 /* SyntaxKind.EnumDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); @@ -30844,17 +31330,17 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 261 /* SyntaxKind.ModuleDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); case 266 /* SyntaxKind.ImportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -30868,7 +31354,8 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.value); case 264 /* SyntaxKind.NamespaceExportDeclaration */: - return visitNode(cbNode, node.name); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNode(cbNode, node.name); case 268 /* SyntaxKind.NamespaceImport */: return visitNode(cbNode, node.name); case 274 /* SyntaxKind.NamespaceExport */: @@ -30877,7 +31364,7 @@ var ts; case 273 /* SyntaxKind.NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); case 272 /* SyntaxKind.ExportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -30887,17 +31374,21 @@ var ts; return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); case 271 /* SyntaxKind.ExportAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); case 223 /* SyntaxKind.TemplateExpression */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 233 /* SyntaxKind.TemplateSpan */: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.literal); case 198 /* SyntaxKind.TemplateLiteralType */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 199 /* SyntaxKind.TemplateLiteralTypeSpan */: - return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.literal); case 162 /* SyntaxKind.ComputedPropertyName */: return visitNode(cbNode, node.expression); case 291 /* SyntaxKind.HeritageClause */: @@ -30908,7 +31399,8 @@ var ts; case 277 /* SyntaxKind.ExternalModuleReference */: return visitNode(cbNode, node.expression); case 276 /* SyntaxKind.MissingDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers); case 351 /* SyntaxKind.CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 278 /* SyntaxKind.JsxElement */: @@ -31587,7 +32079,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* NodeFlags.AwaitContext */) - && !!(node.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -31628,7 +32120,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setFields(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); setFields(sourceFile); } @@ -32556,7 +33048,7 @@ var ts; } return parseElement(); } - function currentNode(parsingContext) { + function currentNode(parsingContext, pos) { // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. // // If there is an outstanding parse error that we've encountered, but not attached to @@ -32569,7 +33061,7 @@ var ts; if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } - var node = syntaxCursor.currentNode(scanner.getStartPos()); + var node = syntaxCursor.currentNode(pos !== null && pos !== void 0 ? pos : scanner.getStartPos()); // Can't reuse a missing node. // Can't reuse a node that intersected the change range. // Can't reuse a node that contains a parse error. This is necessary so that we @@ -32844,7 +33336,9 @@ var ts; case 23 /* ParsingContext.ImportOrExportSpecifiers */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 13 /* ParsingContext.JsxAttributes */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 14 /* ParsingContext.JsxChildren */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - default: return [undefined]; // TODO: GH#18217 `default: Debug.assertNever(context);` + case 24 /* ParsingContext.AssertEntries */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_or_string_literal_expected); // AssertionKey. + case 25 /* ParsingContext.Count */: return ts.Debug.fail("ParsingContext.Count used as a context"); // Not a real context, only a marker. + default: ts.Debug.assertNever(context); } } function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { @@ -33160,7 +33654,6 @@ var ts; parseExpected(58 /* SyntaxKind.ColonToken */); } return finishNode(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier? @@ -33286,10 +33779,9 @@ var ts; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : doOutsideOfAwaitContext(parseDecorators); if (token() === 108 /* SyntaxKind.ThisKeyword */) { var node_1 = factory.createParameterDeclaration(decorators, - /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); @@ -33300,12 +33792,12 @@ var ts; } var savedTopLevel = topLevel; topLevel = false; - var modifiers = parseModifiers(); + var modifiers = combineDecoratorsAndModifiers(decorators, parseModifiers()); var dotDotDotToken = parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */); if (!allowAmbiguity && !isParameterNameStart()) { return undefined; } - var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createParameterDeclaration(modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); topLevel = savedTopLevel; return node; } @@ -33457,7 +33949,8 @@ var ts; var parameters = parseBracketedList(16 /* ParsingContext.Parameters */, function () { return parseParameter(/*inOuterAwaitContext*/ false); }, 22 /* SyntaxKind.OpenBracketToken */, 23 /* SyntaxKind.CloseBracketToken */); var type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - var node = factory.createIndexSignature(decorators, modifiers, parameters, type); + var node = factory.createIndexSignature(modifiers, parameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) { @@ -33530,10 +34023,10 @@ var ts; var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */, 4 /* SignatureFlags.Type */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */, 4 /* SignatureFlags.Type */); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); @@ -34171,10 +34664,10 @@ var ts; setDecoratorContext(/*val*/ false); } var pos = getNodePos(); - var expr = parseAssignmentExpressionOrHigher(); + var expr = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); var operatorToken; while ((operatorToken = parseOptionalToken(27 /* SyntaxKind.CommaToken */))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos); + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), pos); } if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -34182,9 +34675,9 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true) : undefined; } - function parseAssignmentExpressionOrHigher() { + function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) { // AssignmentExpression[in,yield]: // 1) ConditionalExpression[?in,?yield] // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] @@ -34210,7 +34703,7 @@ var ts; // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + var arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction); if (arrowExpression) { return arrowExpression; } @@ -34229,7 +34722,7 @@ var ts; // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. if (expr.kind === 79 /* SyntaxKind.Identifier */ && token() === 38 /* SyntaxKind.EqualsGreaterThanToken */) { - return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, /*asyncModifier*/ undefined); } // Now see if we might be in cases '2' or '3'. // If the expression was a LHS expression, and we have an assignment operator, then @@ -34238,10 +34731,10 @@ var ts; // Note: we call reScanGreaterToken so that we get an appropriately merged token // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos); + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); } // It wasn't an assignment or a lambda. This is a conditional expression: - return parseConditionalExpressionRest(expr, pos); + return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction); } function isYieldExpression() { if (token() === 125 /* SyntaxKind.YieldKeyword */) { @@ -34281,7 +34774,7 @@ var ts; nextToken(); if (!scanner.hasPrecedingLineBreak() && (token() === 41 /* SyntaxKind.AsteriskToken */ || isStartOfExpression())) { - return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher()), pos); + return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)), pos); } else { // if the next token is not on the same line as yield. or we don't have an '*' or @@ -34289,10 +34782,9 @@ var ts; return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { ts.Debug.assert(token() === 38 /* SyntaxKind.EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var parameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, identifier, /*questionToken*/ undefined, @@ -34301,11 +34793,11 @@ var ts; finishNode(parameter, identifier.pos); var parameters = createNodeArray([parameter], parameter.pos, parameter.end); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); - var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier, allowReturnTypeInArrowFunction); var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body); return addJSDocComment(finishNode(node, pos)); } - function tryParseParenthesizedArrowFunctionExpression() { + function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var triState = isParenthesizedArrowFunctionExpression(); if (triState === 0 /* Tristate.False */) { // It's definitely not a parenthesized arrow function expression. @@ -34316,8 +34808,8 @@ var ts; // it out, but don't allow any ambiguity, and return 'undefined' if this could be an // expression instead. return triState === 1 /* Tristate.True */ ? - parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) : - tryParse(parsePossibleParenthesizedArrowFunctionExpression); + parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true, /*allowReturnTypeInArrowFunction*/ true) : + tryParse(function () { return parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction); }); } // True -> We definitely expect a parenthesized arrow function here. // False -> There *cannot* be a parenthesized arrow function here. @@ -34382,7 +34874,7 @@ var ts; // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. if (ts.isModifierKind(second) && second !== 131 /* SyntaxKind.AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { - if (lookAhead(function () { return nextToken() === 127 /* SyntaxKind.AsKeyword */; })) { + if (nextToken() === 127 /* SyntaxKind.AsKeyword */) { // https://github.com/microsoft/TypeScript/issues/44466 return 0 /* Tristate.False */; } @@ -34451,25 +34943,25 @@ var ts; return 2 /* Tristate.Unknown */; } } - function parsePossibleParenthesizedArrowFunctionExpression() { + function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var tokenPos = scanner.getTokenPos(); if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) { return undefined; } - var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false); + var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false, allowReturnTypeInArrowFunction); if (!result) { (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos); } return result; } - function tryParseAsyncSimpleArrowFunctionExpression() { + function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() === 131 /* SyntaxKind.AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* Tristate.True */) { var pos = getNodePos(); var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0 /* OperatorPrecedence.Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); } } return undefined; @@ -34493,7 +34985,7 @@ var ts; } return 0 /* Tristate.False */; } - function parseParenthesizedArrowFunctionExpression(allowAmbiguity) { + function parseParenthesizedArrowFunctionExpression(allowAmbiguity, allowReturnTypeInArrowFunction) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiersForArrowFunction(); @@ -34528,6 +35020,7 @@ var ts; return undefined; } } + var hasReturnColon = token() === 58 /* SyntaxKind.ColonToken */; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) { return undefined; @@ -34556,12 +35049,37 @@ var ts; var lastToken = token(); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); var body = (lastToken === 38 /* SyntaxKind.EqualsGreaterThanToken */ || lastToken === 18 /* SyntaxKind.OpenBraceToken */) - ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier)) + ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier(); + // Given: + // x ? y => ({ y }) : z => ({ z }) + // We try to parse the body of the first arrow function by looking at: + // ({ y }) : z => ({ z }) + // This is a valid arrow function with "z" as the return type. + // + // But, if we're in the true side of a conditional expression, this colon + // terminates the expression, so we cannot allow a return type if we aren't + // certain whether or not the preceding text was parsed as a parameter list. + // + // For example, + // a() ? (b: number, c?: string): void => d() : e + // is determined by isParenthesizedArrowFunctionExpression to unambiguously + // be an arrow expression, so we allow a return type. + if (!allowReturnTypeInArrowFunction && hasReturnColon) { + // However, if the arrow function we were able to parse is followed by another colon + // as in: + // a ? (x): string => x : null + // Then allow the arrow function, and treat the second colon as terminating + // the conditional expression. It's okay to do this because this code would + // be a syntax error in JavaScript (as the second colon shouldn't be there). + if (token() !== 58 /* SyntaxKind.ColonToken */) { + return undefined; + } + } var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseArrowFunctionExpressionBody(isAsync) { + function parseArrowFunctionExpressionBody(isAsync, allowReturnTypeInArrowFunction) { if (token() === 18 /* SyntaxKind.OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* SignatureFlags.Await */ : 0 /* SignatureFlags.None */); } @@ -34589,12 +35107,12 @@ var ts; var savedTopLevel = topLevel; topLevel = false; var node = isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + ? doInAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }) + : doOutsideOfAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }); topLevel = savedTopLevel; return node; } - function parseConditionalExpressionRest(leftOperand, pos) { + function parseConditionalExpressionRest(leftOperand, pos, allowReturnTypeInArrowFunction) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. var questionToken = parseOptionalToken(57 /* SyntaxKind.QuestionToken */); if (!questionToken) { @@ -34603,8 +35121,8 @@ var ts; // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. var colonToken; - return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) - ? parseAssignmentExpressionOrHigher() + return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ false); }), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) + ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(79 /* SyntaxKind.Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* SyntaxKind.ColonToken */))), pos); } function parseBinaryExpressionOrHigher(precedence) { @@ -34989,6 +35507,9 @@ var ts; var typeArguments = tryParse(parseTypeArgumentsInExpression); if (typeArguments !== undefined) { parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments); + if (!isTemplateStartOfTaggedTemplate()) { + expression = factory.createExpressionWithTypeArguments(expression, typeArguments); + } } } if (token() === 20 /* SyntaxKind.OpenParenToken */ || token() === 24 /* SyntaxKind.DotToken */ || token() === 22 /* SyntaxKind.OpenBracketToken */) { @@ -35201,9 +35722,22 @@ var ts; } scanJsxIdentifier(); var pos = getNodePos(); - return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 63 /* SyntaxKind.EqualsToken */ ? undefined : - scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */ ? parseLiteralNode() : - parseJsxExpression(/*inExpressionContext*/ true)), pos); + return finishNode(factory.createJsxAttribute(parseIdentifierName(), parseJsxAttributeValue()), pos); + } + function parseJsxAttributeValue() { + if (token() === 63 /* SyntaxKind.EqualsToken */) { + if (scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */) { + return parseLiteralNode(); + } + if (token() === 18 /* SyntaxKind.OpenBraceToken */) { + return parseJsxExpression(/*inExpressionContext*/ true); + } + if (token() === 29 /* SyntaxKind.LessThanToken */) { + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + parseErrorAtCurrentToken(ts.Diagnostics.or_JSX_element_expected); + } + return undefined; } function parseJsxSpreadAttribute() { var pos = getNodePos(); @@ -35293,6 +35827,11 @@ var ts; if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) { parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers); } + if (ts.isExpressionWithTypeArguments(expression) && expression.typeArguments) { + var pos_2 = expression.typeArguments.pos - 1; + var end = ts.skipTrivia(sourceText, expression.typeArguments.end) + 1; + parseErrorAt(pos_2, end, ts.Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access); + } return finishNode(propertyAccess, pos); } function parseElementAccessExpressionRest(pos, expression, questionDotToken) { @@ -35418,10 +35957,11 @@ var ts; } nextToken(); var typeArguments = parseDelimitedList(20 /* ParsingContext.TypeArguments */, parseType); - if (!parseExpected(31 /* SyntaxKind.GreaterThanToken */)) { + if (reScanGreaterToken() !== 31 /* SyntaxKind.GreaterThanToken */) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } + nextToken(); // We successfully parsed a type argument list. The next token determines whether we want to // treat it as such. If the type argument list is followed by `(` or a template literal, as in // `f(42)`, we favor the type argument interpretation even though JavaScript would view @@ -35435,9 +35975,18 @@ var ts; case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: // foo `...` case 15 /* SyntaxKind.TemplateHead */: // foo `...${100}...` return true; + // A type argument list followed by `<` never makes sense, and a type argument list followed + // by `>` is ambiguous with a (re-scanned) `>>` operator, so we disqualify both. Also, in + // this context, `+` and `-` are unary operators, not binary operators. + case 29 /* SyntaxKind.LessThanToken */: + case 31 /* SyntaxKind.GreaterThanToken */: + case 39 /* SyntaxKind.PlusToken */: + case 40 /* SyntaxKind.MinusToken */: + return false; } - // Consider something a type argument list only if the following token can't start an expression. - return !isStartOfExpression(); + // We favor the type argument list interpretation when it is immediately followed by + // a line break, a binary operator, or something that can't start an expression. + return scanner.hasPrecedingLineBreak() || isBinaryOperator() || !isStartOfExpression(); } function parsePrimaryExpression() { switch (token()) { @@ -35496,13 +36045,13 @@ var ts; function parseSpreadElement() { var pos = getNodePos(); parseExpected(25 /* SyntaxKind.DotDotDotToken */); - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createSpreadElement(expression), pos); } function parseArgumentOrArrayLiteralElement() { return token() === 25 /* SyntaxKind.DotDotDotToken */ ? parseSpreadElement() : token() === 27 /* SyntaxKind.CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) : - parseAssignmentExpressionOrHigher(); + parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); @@ -35520,16 +36069,16 @@ var ts; var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); if (parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */)) { - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc); } var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } var asteriskToken = parseOptionalToken(41 /* SyntaxKind.AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -35549,7 +36098,7 @@ var ts; var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* SyntaxKind.ColonToken */); if (isShorthandPropertyAssignment) { var equalsToken = parseOptionalToken(63 /* SyntaxKind.EqualsToken */); - var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined; + var objectAssignmentInitializer = equalsToken ? allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }) : undefined; node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer); // Save equals token for error reporting. // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful. @@ -35557,11 +36106,11 @@ var ts; } else { parseExpected(58 /* SyntaxKind.ColonToken */); - var initializer = allowInAnd(parseAssignmentExpressionOrHigher); + var initializer = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); node = factory.createPropertyAssignment(name, initializer); } // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; node.questionToken = questionToken; node.exclamationToken = exclamationToken; @@ -35621,6 +36170,9 @@ var ts; typeArguments = expression.typeArguments; expression = expression.expression; } + if (token() === 28 /* SyntaxKind.QuestionDotToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, ts.getTextOfNodeFromSourceText(sourceText, expression)); + } var argumentList = token() === 20 /* SyntaxKind.OpenParenToken */ ? parseArgumentList() : undefined; return finishNode(factory.createNewExpression(expression, typeArguments, argumentList), pos); } @@ -35731,7 +36283,7 @@ var ts; } var node; if (awaitToken ? parseExpected(160 /* SyntaxKind.OfKeyword */) : parseOptional(160 /* SyntaxKind.OfKeyword */)) { - var expression = allowInAnd(parseAssignmentExpressionOrHigher); + var expression = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); parseExpected(21 /* SyntaxKind.CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); } @@ -36136,24 +36688,19 @@ var ts; return modifier.kind === 135 /* SyntaxKind.DeclareKeyword */; } function parseDeclaration() { - // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner - // if we can't reuse the declaration, so that we don't do this work twice? - // // `parseListElement` attempted to get the reused node at this position, // but the ambient context flag was not yet set, so the node appeared // not reusable in that context. - var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier); - if (isAmbient) { - var node = tryReuseAmbientDeclaration(); - if (node) { - return node; - } - } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var decorators = parseDecorators(); var modifiers = parseModifiers(); + var isAmbient = ts.some(modifiers, isDeclareModifier); if (isAmbient) { + var node = tryReuseAmbientDeclaration(pos); + if (node) { + return node; + } for (var _i = 0, _a = modifiers; _i < _a.length; _i++) { var m = _a[_i]; m.flags |= 16777216 /* NodeFlags.Ambient */; @@ -36164,9 +36711,9 @@ var ts; return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); } } - function tryReuseAmbientDeclaration() { + function tryReuseAmbientDeclaration(pos) { return doInsideOfContext(16777216 /* NodeFlags.Ambient */, function () { - var node = currentNode(parsingContext); + var node = currentNode(parsingContext, pos); if (node) { return consumeNode(node); } @@ -36211,7 +36758,7 @@ var ts; // would follow. For recovery and error reporting purposes, return an incomplete declaration. var missing = createMissingNode(276 /* SyntaxKind.MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); - missing.decorators = decorators; + missing.illegalDecorators = decorators; missing.modifiers = modifiers; return missing; } @@ -36223,9 +36770,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* SyntaxKind.StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 18 /* SyntaxKind.OpenBraceToken */ && canParseSemicolon()) { - parseSemicolon(); - return; + if (token() !== 18 /* SyntaxKind.OpenBraceToken */) { + if (flags & 4 /* SignatureFlags.Type */) { + parseTypeMemberSemicolon(); + return; + } + if (canParseSemicolon()) { + parseSemicolon(); + return; + } } return parseFunctionBlock(flags, diagnosticMessage); } @@ -36348,7 +36901,7 @@ var ts; parseSemicolon(); var node = factory.createVariableStatement(modifiers, declarationList); // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker. - node.decorators = decorators; + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36367,7 +36920,8 @@ var ts; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); setAwaitContext(savedAwaitContext); - var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + var node = factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseConstructorName() { @@ -36388,8 +36942,9 @@ var ts; var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */, ts.Diagnostics.or_expected); - var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body); - // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker. + var node = factory.createConstructorDeclaration(modifiers, parameters, body); + // Attach invalid nodes if they exist so that we can report them in the grammar checker. + node.illegalDecorators = decorators; node.typeParameters = typeParameters; node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36403,7 +36958,7 @@ var ts; var parameters = parseParameters(isGenerator | isAsync); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + var node = factory.createMethodDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); // An exclamation token on a method is invalid syntax and will be handled by the grammar checker node.exclamationToken = exclamationToken; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36413,7 +36968,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = doOutsideOfContext(8192 /* NodeFlags.YieldContext */ | 32768 /* NodeFlags.AwaitContext */ | 4096 /* NodeFlags.DisallowInContext */, parseInitializer); parseSemicolonAfterPropertyName(name, type, initializer); - var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer); + var node = factory.createPropertyDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, questionToken || exclamationToken, type, initializer); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36427,18 +36982,18 @@ var ts; } return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken); } - function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) { + function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind, flags) { var name = parsePropertyName(); var typeParameters = parseTypeParameters(); var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); - var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */); + var body = parseFunctionBlockOrSemicolon(flags); var node = kind === 172 /* SyntaxKind.GetAccessor */ - ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) - : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); + ? factory.createGetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, type, body) + : factory.createSetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 173 /* SyntaxKind.SetAccessor */) + if (ts.isSetAccessorDeclaration(node)) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -36504,7 +37059,10 @@ var ts; function parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers) { parseExpectedToken(124 /* SyntaxKind.StaticKeyword */); var body = parseClassStaticBlockBody(); - return withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(decorators, modifiers, body), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(body), pos), hasJSDoc); + node.illegalDecorators = decorators; + node.modifiers = modifiers; + return node; } function parseClassStaticBlockBody() { var savedYieldContext = inYieldContext(); @@ -36567,6 +37125,15 @@ var ts; } return finishNode(factory.createToken(kind), pos); } + function combineDecoratorsAndModifiers(decorators, modifiers) { + if (!decorators) + return modifiers; + if (!modifiers) + return decorators; + var decoratorsAndModifiers = factory.createNodeArray(ts.concatenate(decorators, modifiers)); + ts.setTextRangePosEnd(decoratorsAndModifiers, decorators.pos, modifiers.end); + return decoratorsAndModifiers; + } /* * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect @@ -36607,10 +37174,10 @@ var ts; return parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers); } if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } if (token() === 134 /* SyntaxKind.ConstructorKeyword */ || token() === 10 /* SyntaxKind.StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -36675,8 +37242,8 @@ var ts; } setAwaitContext(savedAwaitContext); var node = kind === 257 /* SyntaxKind.ClassDeclaration */ - ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) - : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); + ? factory.createClassDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members) + : factory.createClassExpression(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseNameOfClassDeclarationOrExpression() { @@ -36733,7 +37300,8 @@ var ts; var typeParameters = parseTypeParameters(); var heritageClauses = parseHeritageClauses(); var members = parseObjectTypeMembers(); - var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = factory.createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36743,7 +37311,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var type = token() === 138 /* SyntaxKind.IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); parseSemicolon(); - var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type); + var node = factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } // In an ambient declaration, the grammar only allows integer literals as initializers. @@ -36768,7 +37337,8 @@ var ts; else { members = createMissingList(); } - var node = factory.createEnumDeclaration(decorators, modifiers, name, members); + var node = factory.createEnumDeclaration(modifiers, name, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleBlock() { @@ -36791,7 +37361,8 @@ var ts; var body = parseOptional(24 /* SyntaxKind.DotToken */) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NodeFlags.NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36813,7 +37384,8 @@ var ts; else { parseSemicolon(); } - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36853,7 +37425,7 @@ var ts; parseSemicolon(); var node = factory.createNamespaceExportDeclaration(name); // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -36892,14 +37464,15 @@ var ts; assertClause = parseAssertClause(); } parseSemicolon(); - var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause); + var node = factory.createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAssertEntry() { var pos = getNodePos(); var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* SyntaxKind.StringLiteral */); parseExpected(58 /* SyntaxKind.ColonToken */); - var value = parseAssignmentExpressionOrHigher(); + var value = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createAssertEntry(name, value), pos); } function parseAssertClause(skipAssertKeyword) { @@ -36936,7 +37509,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var moduleReference = parseModuleReference(); parseSemicolon(); - var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference); + var node = factory.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference); + node.illegalDecorators = decorators; var finished = withJSDoc(finishNode(node, pos), hasJSDoc); return finished; } @@ -37125,7 +37699,8 @@ var ts; } parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + var node = factory.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) { @@ -37138,10 +37713,11 @@ var ts; else { parseExpected(88 /* SyntaxKind.DefaultKeyword */); } - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression); + var node = factory.createExportAssignment(modifiers, isExportEquals, expression); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } var ParsingContext; @@ -37932,7 +38508,6 @@ var ts; if (parseOptional(24 /* SyntaxKind.DotToken */)) { var body = parseJSDocTypeNameWithNamespace(/*nested*/ true); var jsDocNamespaceNode = factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NodeFlags.NestedNamespace */ : undefined); return finishNode(jsDocNamespaceNode, pos); } @@ -38369,10 +38944,10 @@ var ts; } function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { - var pos_2 = node.pos; + var pos_3 = node.pos; var visitNode_1 = function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; + ts.Debug.assert(child.pos >= pos_3); + pos_3 = child.end; }; if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -38381,7 +38956,7 @@ var ts; } } forEachChild(node, visitNode_1); - ts.Debug.assert(pos_2 <= node.end); + ts.Debug.assert(pos_3 <= node.end); } } function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { @@ -38979,6 +39554,7 @@ var ts; ["es2022.error", "lib.es2022.error.d.ts"], ["es2022.intl", "lib.es2022.intl.d.ts"], ["es2022.object", "lib.es2022.object.d.ts"], + ["es2022.sharedmemory", "lib.es2022.sharedmemory.d.ts"], ["es2022.string", "lib.es2022.string.d.ts"], ["esnext.array", "lib.es2022.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], @@ -39192,6 +39768,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, defaultValueDescription: false, @@ -39226,12 +39803,40 @@ var ts; affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, defaultValueDescription: 0 /* ScriptTarget.ES3 */, }; + /*@internal*/ + ts.moduleOptionDeclaration = { + name: "module", + shortName: "m", + type: new ts.Map(ts.getEntries({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + es2020: ts.ModuleKind.ES2020, + es2022: ts.ModuleKind.ES2022, + esnext: ts.ModuleKind.ESNext, + node16: ts.ModuleKind.Node16, + nodenext: ts.ModuleKind.NodeNext, + })), + affectsModuleResolution: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Modules, + description: ts.Diagnostics.Specify_what_module_code_is_generated, + defaultValueDescription: undefined, + }; var commandOptionsWithoutBuild = [ // CommandLine only options { @@ -39293,37 +39898,14 @@ var ts; category: ts.Diagnostics.Command_line_Options, affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, isCommandLineOnly: true, description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, defaultValueDescription: false, }, // Basic ts.targetOptionDeclaration, - { - name: "module", - shortName: "m", - type: new ts.Map(ts.getEntries({ - none: ts.ModuleKind.None, - commonjs: ts.ModuleKind.CommonJS, - amd: ts.ModuleKind.AMD, - system: ts.ModuleKind.System, - umd: ts.ModuleKind.UMD, - es6: ts.ModuleKind.ES2015, - es2015: ts.ModuleKind.ES2015, - es2020: ts.ModuleKind.ES2020, - es2022: ts.ModuleKind.ES2022, - esnext: ts.ModuleKind.ESNext, - node16: ts.ModuleKind.Node16, - nodenext: ts.ModuleKind.NodeNext, - })), - affectsModuleResolution: true, - affectsEmit: true, - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Modules, - description: ts.Diagnostics.Specify_what_module_code_is_generated, - defaultValueDescription: undefined, - }, + ts.moduleOptionDeclaration, { name: "lib", type: "list", @@ -39360,6 +39942,7 @@ var ts; type: jsxOptionMap, affectsSourceFile: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -39372,6 +39955,7 @@ var ts; shortName: "d", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -39382,6 +39966,7 @@ var ts; name: "declarationMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -39392,6 +39977,7 @@ var ts; name: "emitDeclarationOnly", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, @@ -39402,6 +39988,7 @@ var ts; name: "sourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -39411,6 +39998,9 @@ var ts; name: "outFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, showInSimplifiedHelpView: true, @@ -39422,6 +40012,8 @@ var ts; name: "outDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, showInSimplifiedHelpView: true, @@ -39432,6 +40024,8 @@ var ts; name: "rootDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Modules, @@ -39442,6 +40036,8 @@ var ts; name: "composite", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isTSConfigOnly: true, category: ts.Diagnostics.Projects, transpileOptionValue: undefined, @@ -39452,6 +40048,8 @@ var ts; name: "tsBuildInfoFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, category: ts.Diagnostics.Projects, @@ -39463,6 +40061,7 @@ var ts; name: "removeComments", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -39481,6 +40080,7 @@ var ts; name: "importHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, defaultValueDescription: false, @@ -39494,6 +40094,7 @@ var ts; })), affectsEmit: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, defaultValueDescription: 0 /* ImportsNotUsedAsValues.Remove */, @@ -39502,6 +40103,7 @@ var ts; name: "downlevelIteration", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, defaultValueDescription: false, @@ -39520,6 +40122,9 @@ var ts; type: "boolean", // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here // The value of each strictFlag depends on own strictFlag value or this and never accessed directly. + // But we need to store `strict` in builf info, even though it won't be examined directly, so that the + // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_all_strict_type_checking_options, @@ -39529,6 +40134,7 @@ var ts; name: "noImplicitAny", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, @@ -39538,6 +40144,7 @@ var ts; name: "strictNullChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_type_checking_take_into_account_null_and_undefined, @@ -39546,6 +40153,8 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, @@ -39554,6 +40163,8 @@ var ts; { name: "strictBindCallApply", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, @@ -39563,6 +40174,7 @@ var ts; name: "strictPropertyInitialization", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, @@ -39572,6 +40184,7 @@ var ts; name: "noImplicitThis", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, @@ -39581,6 +40194,7 @@ var ts; name: "useUnknownInCatchVariables", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, @@ -39590,6 +40204,8 @@ var ts; name: "alwaysStrict", type: "boolean", affectsSourceFile: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_use_strict_is_always_emitted, @@ -39600,6 +40216,7 @@ var ts; name: "noUnusedLocals", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, defaultValueDescription: false, @@ -39608,6 +40225,7 @@ var ts; name: "noUnusedParameters", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, defaultValueDescription: false, @@ -39616,6 +40234,7 @@ var ts; name: "exactOptionalPropertyTypes", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, defaultValueDescription: false, @@ -39624,6 +40243,7 @@ var ts; name: "noImplicitReturns", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, defaultValueDescription: false, @@ -39633,6 +40253,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, defaultValueDescription: false, @@ -39641,6 +40262,7 @@ var ts; name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, defaultValueDescription: false, @@ -39649,6 +40271,7 @@ var ts; name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, defaultValueDescription: false, @@ -39656,6 +40279,8 @@ var ts; { name: "noPropertyAccessFromIndexSignature", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: false, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, @@ -39741,6 +40366,7 @@ var ts; name: "allowSyntheticDefaultImports", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, defaultValueDescription: ts.Diagnostics.module_system_or_esModuleInterop @@ -39750,6 +40376,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, @@ -39766,6 +40393,7 @@ var ts; name: "allowUmdGlobalAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules, defaultValueDescription: false, @@ -39787,6 +40415,7 @@ var ts; name: "sourceRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code, @@ -39795,6 +40424,7 @@ var ts; name: "mapRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, @@ -39803,6 +40433,7 @@ var ts; name: "inlineSourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -39811,6 +40442,7 @@ var ts; name: "inlineSources", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -39820,6 +40452,7 @@ var ts; name: "experimentalDecorators", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, defaultValueDescription: false, @@ -39829,6 +40462,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, defaultValueDescription: false, @@ -39853,6 +40487,7 @@ var ts; type: "string", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, @@ -39870,6 +40505,9 @@ var ts; name: "out", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: false, // for correct behaviour, please use outFile category: ts.Diagnostics.Backwards_Compatibility, @@ -39881,6 +40519,7 @@ var ts; name: "reactNamespace", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, defaultValueDescription: "`React`", @@ -39888,6 +40527,8 @@ var ts; { name: "skipDefaultLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, defaultValueDescription: false, @@ -39903,6 +40544,7 @@ var ts; name: "emitBOM", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, defaultValueDescription: false, @@ -39914,6 +40556,7 @@ var ts; lf: 1 /* NewLineKind.LineFeed */ })), affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Set_the_newline_character_for_emitting_files, @@ -39923,6 +40566,7 @@ var ts; name: "noErrorTruncation", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_truncating_types_in_error_messages, defaultValueDescription: false, @@ -39953,6 +40597,7 @@ var ts; name: "stripInternal", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, defaultValueDescription: false, @@ -39993,6 +40638,7 @@ var ts; name: "noImplicitUseStrict", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, defaultValueDescription: false, @@ -40001,6 +40647,7 @@ var ts; name: "noEmitHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, defaultValueDescription: false, @@ -40009,6 +40656,7 @@ var ts; name: "noEmitOnError", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, @@ -40018,6 +40666,7 @@ var ts; name: "preserveConstEnums", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, defaultValueDescription: false, @@ -40026,6 +40675,8 @@ var ts; name: "declarationDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, category: ts.Diagnostics.Emit, @@ -40035,6 +40686,8 @@ var ts; { name: "skipLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_all_d_ts_files, defaultValueDescription: false, @@ -40044,6 +40697,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unused_labels, defaultValueDescription: undefined, @@ -40053,6 +40707,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code, defaultValueDescription: undefined, @@ -40061,6 +40716,7 @@ var ts; name: "suppressExcessPropertyErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, defaultValueDescription: false, @@ -40069,6 +40725,7 @@ var ts; name: "suppressImplicitAnyIndexErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, defaultValueDescription: false, @@ -40093,6 +40750,7 @@ var ts; name: "noStrictGenericChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, defaultValueDescription: false, @@ -40102,6 +40760,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, defaultValueDescription: ts.Diagnostics.true_for_ES2022_and_above_including_ESNext @@ -40110,6 +40769,7 @@ var ts; name: "preserveValueImports", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, defaultValueDescription: false, @@ -40153,6 +40813,8 @@ var ts; /* @internal */ ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; }); /* @internal */ + ts.affectsDeclarationPathOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsDeclarationPath; }); + /* @internal */ ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); /* @internal */ ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { @@ -40975,7 +41637,7 @@ var ts; return undefined; if (ts.length(specs) !== 1) return specs; - if (specs[0] === "**/*") + if (specs[0] === ts.defaultIncludeSpec) return undefined; return specs; } @@ -41008,6 +41670,7 @@ var ts; return optionDefinition.type; } } + /* @internal */ function getNameOfCompilerOptionValue(value, customTypeMap) { // There is a typeMap associated with this command-line option so use it to map value back to its name return ts.forEachEntry(customTypeMap, function (mapValue, key) { @@ -41016,6 +41679,7 @@ var ts; } }); } + ts.getNameOfCompilerOptionValue = getNameOfCompilerOptionValue; function serializeCompilerOptions(options, pathOptions) { return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); } @@ -41253,6 +41917,8 @@ var ts; // until consistent casing errors are reported return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } + /*@internal*/ + ts.defaultIncludeSpec = "**/*"; /** * Parse the contents of a config file from json or json source file (tsconfig.json). * @param json The contents of the config file to parse @@ -41318,6 +41984,7 @@ var ts; } var includeSpecs = toPropValue(getSpecsFromRaw("include")); var excludeOfRaw = getSpecsFromRaw("exclude"); + var isDefaultIncludeSpec = false; var excludeSpecs = toPropValue(excludeOfRaw); if (excludeOfRaw === "no-prop" && raw.compilerOptions) { var outDir = raw.compilerOptions.outDir; @@ -41327,7 +41994,8 @@ var ts; } } if (filesSpecs === undefined && includeSpecs === undefined) { - includeSpecs = ["**/*"]; + includeSpecs = [ts.defaultIncludeSpec]; + isDefaultIncludeSpec = true; } var validatedIncludeSpecs, validatedExcludeSpecs; // The exclude spec list is converted into a regular expression, which allows us to quickly @@ -41346,7 +42014,8 @@ var ts; validatedFilesSpec: ts.filter(filesSpecs, ts.isString), validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, - pathPatterns: undefined, // Initialized on first use + pathPatterns: undefined, + isDefaultIncludeSpec: isDefaultIncludeSpec, }; } function getFileNames(basePath) { @@ -42006,7 +42675,7 @@ var ts; } if (ts.isImplicitGlob(spec.substring(spec.lastIndexOf(ts.directorySeparator) + 1))) { return { - key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec), + key: ts.removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec)), flags: 1 /* WatchDirectoryFlags.Recursive */ }; } @@ -42176,16 +42845,18 @@ var ts; ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, diagnostics, resultFromCache) { - var _a; + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache) { + var _a, _b; if (resultFromCache) { (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = resultFromCache.affectingLocations).push.apply(_b, affectingLocations); return resultFromCache; } return { resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations, - resolutionDiagnostics: diagnostics + affectingLocations: affectingLocations, + resolutionDiagnostics: diagnostics, }; } function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { @@ -42374,6 +43045,7 @@ var ts; } } var failedLookupLocations = []; + var affectingLocations = []; var features = getDefaultNodeResolutionFeatures(options); // Unlike `import` statements, whose mode-calculating APIs are all guaranteed to return `undefined` if we're in an un-mode-ed module resolution // setting, type references will return their target mode regardless of options because of how the parser works, so we guard against the mode being @@ -42392,6 +43064,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -42408,15 +43081,17 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + var pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host); resolvedTypeReferenceDirective = { primary: primary, - resolvedFileName: resolvedFileName, - originalPath: arePathsEqual(fileName, resolvedFileName, host) ? undefined : fileName, + // If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedFileName: pathsAreEqual ? fileName : resolvedFileName, + originalPath: pathsAreEqual ? undefined : fileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName), }; } - result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, resolutionDiagnostics: diagnostics }; + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, affectingLocations: affectingLocations, resolutionDiagnostics: diagnostics }; perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, /*mode*/ resolutionMode, result); if (traceEnabled) traceResult(result); @@ -42491,17 +43166,7 @@ var ts; * Does not try `@types/${packageName}` - use a second pass if needed. */ function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ts.emptyArray, - features: NodeResolutionFeatures.None, - requestContainingDirectory: containingDirectory, - reportDiagnostic: ts.noop - }; + var moduleResolutionState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); return ts.forEachAncestorDirectory(containingDirectory, function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var nodeModulesFolder = ts.combinePaths(ancestorDirectory, "node_modules"); @@ -42598,7 +43263,7 @@ var ts; ts.createCacheWithRedirects = createCacheWithRedirects; function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { var cache; - return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries }; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries, getInternalMap: getInternalMap }; function getPackageJsonInfo(packageJsonPath) { return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); } @@ -42612,6 +43277,9 @@ var ts; var iter = cache === null || cache === void 0 ? void 0 : cache.entries(); return iter ? ts.arrayFrom(iter) : []; } + function getInternalMap() { + return cache; + } } function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); @@ -42715,15 +43383,18 @@ var ts; } ts.zipToModeAwareCache = zipToModeAwareCache; function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; }, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); - moduleNameToDirectoryMap.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + } function update(options) { updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); } @@ -42799,13 +43470,16 @@ var ts; } ts.createModuleResolutionCache = createModuleResolutionCache; function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { clear: clear, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + } } ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { @@ -43111,16 +43785,20 @@ var ts; function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.NodeNextDefault, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); + var tsconfigExtensions = [Extensions.TSConfig]; function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { var containingDirectory = ts.getDirectoryPath(containingFile); // es module file or cjs-like input file, use a variant of the legacy cjs resolver that supports the selected modern features var esmMode = resolutionMode === ts.ModuleKind.ESNext ? NodeResolutionFeatures.EsmMode : 0; - return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions, redirectedReference); + var extensions = compilerOptions.noDtsResolution ? [Extensions.TsOnly, Extensions.JavaScript] : tsExtensions; + if (compilerOptions.resolveJsonModule) { + extensions = __spreadArray(__spreadArray([], extensions, true), [Extensions.Json], false); + } + return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference); } - var jsOnlyExtensions = [Extensions.JavaScript]; - var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; - var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); - var tsconfigExtensions = [Extensions.TSConfig]; function tryResolveJSModuleWorker(moduleName, initialDir, host) { return nodeModuleNameResolverWorker(NodeResolutionFeatures.None, moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); } @@ -43146,6 +43824,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; // conditions are only used by the node16/nodenext resolver - there's no priority order in the list, //it's essentially a set (priority is determined by object insertion order in the object we look at). var conditions = features & NodeResolutionFeatures.EsmMode ? ["node", "import", "types"] : ["node", "require", "types"]; @@ -43158,6 +43837,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -43165,7 +43845,7 @@ var ts; reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; 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, diagnostics, state.resultFromCache); + 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) { var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); @@ -43191,8 +43871,10 @@ var ts; var resolvedValue = resolved_1.value; if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - var originalPath = arePathsEqual(path, resolvedValue.path, host) ? undefined : resolvedValue.path; - resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath }); + var pathsAreEqual = arePathsEqual(path, resolvedValue.path, host); + var originalPath = pathsAreEqual ? undefined : resolvedValue.path; + // If the path and realpath are differing only in casing prefer path so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedValue = __assign(__assign({}, resolvedValue), { path: pathsAreEqual ? resolvedValue.path : path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; @@ -43455,17 +44137,9 @@ var ts; var entrypoints; var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript; var features = getDefaultNodeResolutionFeatures(options); - var requireState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ["node", "require", "types"], - features: features, - requestContainingDirectory: packageJsonInfo.packageDirectory, - reportDiagnostic: ts.noop - }; + var requireState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); + requireState.conditions = ["node", "require", "types"]; + requireState.requestContainingDirectory = packageJsonInfo.packageDirectory; var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, /*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths); entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path); @@ -43538,22 +44212,27 @@ var ts; } } } - /** - * A function for locating the package.json scope for a given path - */ /*@internal*/ - function getPackageScopeForPath(fileName, packageJsonInfoCache, host, options) { - var state = { + function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) { + return { host: host, compilerOptions: options, traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], + failedLookupLocations: ts.noopPush, + affectingLocations: ts.noopPush, packageJsonInfoCache: packageJsonInfoCache, - features: 0, - conditions: [], + features: NodeResolutionFeatures.None, + conditions: ts.emptyArray, requestContainingDirectory: undefined, reportDiagnostic: ts.noop }; + } + ts.getTemporaryModuleResolutionState = getTemporaryModuleResolutionState; + /** + * A function for locating the package.json scope for a given path + */ + /*@internal*/ + function getPackageScopeForPath(fileName, state) { var parts = ts.getPathComponents(fileName); parts.pop(); while (parts.length > 0) { @@ -43580,6 +44259,7 @@ var ts; if (typeof existing !== "boolean") { if (traceEnabled) trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + state.affectingLocations.push(packageJsonPath); return existing; } else { @@ -43598,6 +44278,7 @@ var ts; var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined }; (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + state.affectingLocations.push(packageJsonPath); return result; } else { @@ -43722,7 +44403,7 @@ var ts; var _a, _b; var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope || !scope.packageJsonContent.exports) { return undefined; } @@ -43781,7 +44462,7 @@ var ts; } var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath); @@ -43803,13 +44484,38 @@ var ts; } return toSearchResult(/*value*/ undefined); } + /** + * @internal + * From https://github.com/nodejs/node/blob/8f39f51cbbd3b2de14b9ee896e26421cc5b20121/lib/internal/modules/esm/resolve.js#L722 - + * "longest" has some nuance as to what "longest" means in the presence of pattern trailers + */ + function comparePatternKeys(a, b) { + var aPatternIndex = a.indexOf("*"); + var bPatternIndex = b.indexOf("*"); + var baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + var baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + if (baseLenA > baseLenB) + return -1; + if (baseLenB > baseLenA) + return 1; + if (aPatternIndex === -1) + return 1; + if (bPatternIndex === -1) + return -1; + if (a.length > b.length) + return -1; + if (b.length > a.length) + return 1; + return 0; + } + ts.comparePatternKeys = comparePatternKeys; function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { 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); } - var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), function (a, b) { return a.length - b.length; }); + 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++) { var potentialTarget = expandingKeys_1[_i]; if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) { @@ -44128,8 +44834,8 @@ var ts; var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths); if (!pathAndExtension && packageInfo - && packageInfo.packageJsonContent.exports === undefined - && packageInfo.packageJsonContent.main === undefined + // eslint-disable-next-line no-null/no-null + && (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null) && state.features & NodeResolutionFeatures.EsmMode) { // EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume // a default `index.js` entrypoint if no `main` or `exports` are present @@ -44238,12 +44944,25 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: cache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: containingDirectory, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, + /*isExternalLibraryImport*/ false, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { @@ -44286,10 +45005,23 @@ var ts; trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; + var affectingLocations = []; var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: undefined, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: packageJsonInfoCache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: undefined, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false, /*cache*/ undefined, /*redirectedReference*/ undefined); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved, + /*isExternalLibraryImport*/ true, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -44655,7 +45387,7 @@ var ts; case 164 /* SyntaxKind.Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind, ", expected JSDocFunctionType"); }); + ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind), ", expected JSDocFunctionType"); }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -45839,8 +46571,6 @@ var ts; // - `BindingElement: BindingPattern Initializer?` // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization // - `BindingElement: BindingPattern Initializer?` - bindEach(node.decorators); - bindEach(node.modifiers); bind(node.dotDotDotToken); bind(node.propertyName); bind(node.initializer); @@ -46181,37 +46911,6 @@ var ts; typeLiteralSymbol.members.set(symbol.escapedName, symbol); } function bindObjectLiteralExpression(node) { - var ElementKind; - (function (ElementKind) { - ElementKind[ElementKind["Property"] = 1] = "Property"; - ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; - })(ElementKind || (ElementKind = {})); - if (inStrictMode && !ts.isAssignmentTarget(node)) { - var seen = new ts.Map(); - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 298 /* SyntaxKind.SpreadAssignment */ || prop.name.kind !== 79 /* SyntaxKind.Identifier */) { - continue; - } - var identifier = prop.name; - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 296 /* SyntaxKind.PropertyAssignment */ || prop.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || prop.kind === 169 /* SyntaxKind.MethodDeclaration */ - ? 1 /* ElementKind.Property */ - : 2 /* ElementKind.Accessor */; - var existingKind = seen.get(identifier.escapedText); - if (!existingKind) { - seen.set(identifier.escapedText, currentKind); - continue; - } - } - } return bindAnonymousDeclaration(node, 4096 /* SymbolFlags.ObjectLiteral */, "__object" /* InternalSymbolName.Object */); } function bindJsxAttributes(node) { @@ -46868,7 +47567,7 @@ var ts; } } function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { + if (ts.some(node.modifiers)) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level @@ -46905,12 +47604,14 @@ var ts; } } function setCommonJsModuleIndicator(node) { - if (file.externalModuleIndicator) { + if (file.externalModuleIndicator && file.externalModuleIndicator !== true) { return false; } if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } return true; } @@ -47324,7 +48025,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) && !ts.getJSDocTypeTag(node) && !(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */)) { + var possibleVariableDecl = node.kind === 254 /* SyntaxKind.VariableDeclaration */ ? node : node.parent.parent; + if (ts.isInJSFile(node) && + ts.isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && + !ts.getJSDocTypeTag(node) && + !(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* SymbolFlags.Alias */, 2097152 /* SymbolFlags.AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -47514,10 +48219,11 @@ var ts; } function isExportsOrModuleExportsOrAlias(sourceFile, node) { var i = 0; - var q = [node]; - while (q.length && i < 100) { + var q = ts.createQueue(); + q.enqueue(node); + while (!q.isEmpty() && i < 100) { i++; - node = q.shift(); + node = q.dequeue(); if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) { return true; } @@ -47525,10 +48231,10 @@ var ts; var symbol = lookupSymbolForName(sourceFile, node.escapedText); if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) { var init = symbol.valueDeclaration.initializer; - q.push(init); + q.enqueue(init); if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) { - q.push(init.left); - q.push(init.right); + q.enqueue(init.left); + q.enqueue(init.right); } } } @@ -47788,7 +48494,10 @@ var ts; TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; - TypeFacts[TypeFacts["All"] = 16777215] = "All"; + TypeFacts[TypeFacts["IsUndefined"] = 16777216] = "IsUndefined"; + TypeFacts[TypeFacts["IsNull"] = 33554432] = "IsNull"; + TypeFacts[TypeFacts["IsUndefinedOrNull"] = 50331648] = "IsUndefinedOrNull"; + TypeFacts[TypeFacts["All"] = 134217727] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. @@ -47830,25 +48539,17 @@ var ts; TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; - TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["VoidFacts"] = 9830144] = "VoidFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 26607360] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 42917664] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 83427327] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 83886079] = "EmptyObjectFacts"; + TypeFacts[TypeFacts["UnknownFacts"] = 83886079] = "UnknownFacts"; TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE"; - TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; // Masks TypeFacts[TypeFacts["OrFactsMask"] = 8256] = "OrFactsMask"; - TypeFacts[TypeFacts["AndFactsMask"] = 16768959] = "AndFactsMask"; - })(TypeFacts || (TypeFacts = {})); - var typeofEQFacts = new ts.Map(ts.getEntries({ - string: 1 /* TypeFacts.TypeofEQString */, - number: 2 /* TypeFacts.TypeofEQNumber */, - bigint: 4 /* TypeFacts.TypeofEQBigInt */, - boolean: 8 /* TypeFacts.TypeofEQBoolean */, - symbol: 16 /* TypeFacts.TypeofEQSymbol */, - undefined: 65536 /* TypeFacts.EQUndefined */, - object: 32 /* TypeFacts.TypeofEQObject */, - function: 64 /* TypeFacts.TypeofEQFunction */ - })); + TypeFacts[TypeFacts["AndFactsMask"] = 134209471] = "AndFactsMask"; + })(TypeFacts = ts.TypeFacts || (ts.TypeFacts = {})); var typeofNEFacts = new ts.Map(ts.getEntries({ string: 256 /* TypeFacts.TypeofNEString */, number: 512 /* TypeFacts.TypeofNENumber */, @@ -47883,7 +48584,7 @@ var ts; CheckMode[CheckMode["RestBindingElement"] = 64] = "RestBindingElement"; // e.g. in `const { a, ...rest } = foo`, when checking the type of `foo` to determine the type of `rest`, // we need to preserve generic types instead of substituting them for constraints - })(CheckMode || (CheckMode = {})); + })(CheckMode = ts.CheckMode || (ts.CheckMode = {})); var SignatureCheckMode; (function (SignatureCheckMode) { SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback"; @@ -47891,7 +48592,7 @@ var ts; SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes"; SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity"; SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback"; - })(SignatureCheckMode || (SignatureCheckMode = {})); + })(SignatureCheckMode = ts.SignatureCheckMode || (ts.SignatureCheckMode = {})); var IntersectionState; (function (IntersectionState) { IntersectionState[IntersectionState["None"] = 0] = "None"; @@ -48225,7 +48926,7 @@ var ts; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); - return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + return node ? getContextualTypeForObjectLiteralElement(node, /*contextFlags*/ undefined) : undefined; }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -48233,7 +48934,7 @@ var ts; }, getContextualTypeForJsxAttribute: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); - return node && getContextualTypeForJsxAttribute(node); + return node && getContextualTypeForJsxAttribute(node, /*contextFlags*/ undefined); }, isContextSensitive: isContextSensitive, getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, @@ -48347,9 +49048,9 @@ var ts; return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, - tryGetThisTypeAt: function (nodeIn, includeGlobalThis) { + tryGetThisTypeAt: function (nodeIn, includeGlobalThis, container) { var node = ts.getParseTreeNode(nodeIn); - return node && tryGetThisTypeAt(node, includeGlobalThis); + return node && tryGetThisTypeAt(node, includeGlobalThis, container); }, getTypeArgumentConstraint: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); @@ -48439,6 +49140,7 @@ var ts; var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); var subtypeReductionCache = new ts.Map(); + var cachedTypes = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var markerTypes = new ts.Set(); @@ -48447,11 +49149,10 @@ var ts; var unresolvedSymbols = new ts.Map(); var errorTypes = new ts.Map(); var anyType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); - var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); + var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 262144 /* ObjectFlags.NonInferrableType */); var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error"); var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved"); - var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); @@ -48480,8 +49181,7 @@ var ts; var esSymbolType = createIntrinsicType(4096 /* TypeFlags.ESSymbol */, "symbol"); var voidType = createIntrinsicType(16384 /* TypeFlags.Void */, "void"); var neverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); + var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* TypeFlags.NonPrimitive */, "object"); @@ -48491,16 +49191,30 @@ var ts; var numberOrBigIntType = getUnionType([numberType, bigintType]); var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]); var numericStringType = getTemplateLiteralType(["", ""], [numberType]); // The `${number}` type - var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }); - var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }); + var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }, function () { return "(restrictive mapper)"; }); + var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }, function () { return "(permissive mapper)"; }); var uniqueLiteralType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); // `uniqueLiteralType` is a special `never` flagged by union reduction to behave as a literal - var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }); // replace all type parameters with the unique literal type (disregarding constraints) + var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }, function () { return "(unique literal mapper)"; }); // replace all type parameters with the unique literal type (disregarding constraints) + var outofbandVarianceMarkerHandler; + var reportUnreliableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); + } + return t; + }, function () { return "(unmeasurable reporter)"; }); + var reportUnmeasurableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); + } + return t; + }, function () { return "(unreliable reporter)"; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyJsxObjectType.objectFlags |= 2048 /* ObjectFlags.JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* SymbolFlags.TypeLiteral */, "__type" /* InternalSymbolName.Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray)]) : unknownType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyGenericType.instantiations = new ts.Map(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); @@ -48514,6 +49228,9 @@ var ts; var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); + var markerSuperTypeForCheck = createTypeParameter(); + var markerSubTypeForCheck = createTypeParameter(); + markerSubTypeForCheck.constraint = markerSuperTypeForCheck; var noTypePredicate = createTypePredicate(1 /* TypePredicateKind.Identifier */, "<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); @@ -48643,21 +49360,13 @@ var ts; var potentialNewTargetCollisions = []; var potentialWeakMapSetCollisions = []; var potentialReflectCollisions = []; + var potentialUnusedRenamedBindingElementsInTypes = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); - var typeofTypesByName = new ts.Map(ts.getEntries({ - string: stringType, - number: numberType, - bigint: bigintType, - boolean: booleanType, - symbol: esSymbolType, - undefined: undefinedType - })); var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var outofbandVarianceMarkerHandler; var subtypeRelation = new ts.Map(); var strictSubtypeRelation = new ts.Map(); var assignableRelation = new ts.Map(); @@ -48683,6 +49392,14 @@ var ts; ]; initializeTypeChecker(); return checker; + function getCachedType(key) { + return key ? cachedTypes.get(key) : undefined; + } + function setCachedType(key, type) { + if (key) + cachedTypes.set(key, type); + return type; + } function getJsxNamespace(location) { if (location) { var file = ts.getSourceFileOfNode(location); @@ -49547,6 +50264,7 @@ var ts; if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 111551 /* SymbolFlags.Value */)) { // Remember the property node, it will be used later to report appropriate error + ts.Debug.assertNode(location, ts.isPropertyDeclaration); propertyWithInvalidInitializer = location; } } @@ -49736,11 +50454,27 @@ var ts; } } } + // The invalid initializer error is needed in two situation: + // 1. When result is undefined, after checking for a missing "this." + // 2. When result is defined + function checkAndReportErrorForInvalidInitializer() { + if (propertyWithInvalidInitializer && !(useDefineForClassFields && ts.getEmitScriptTarget(compilerOptions) >= 9 /* ScriptTarget.ES2022 */)) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed + // with ESNext+useDefineForClassFields because the scope semantics are different. + error(errorLocation, errorLocation && propertyWithInvalidInitializer.type && ts.textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) + ? ts.Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor + : ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg)); + return true; + } + return false; + } if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(function () { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForInvalidInitializer() && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && @@ -49748,7 +50482,16 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { + var suggestedLib = void 0; + // Report missing lib first + if (nameArg) { + suggestedLib = getSuggestedLibForNonExistentName(nameArg); + if (suggestedLib) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib); + } + } + // then spelling suggestions + if (!suggestedLib && getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -49767,16 +50510,9 @@ var ts; } } } - if (!suggestion) { - if (nameArg) { - var lib = getSuggestedLibForNonExistentName(nameArg); - if (lib) { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib); - } - else { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); - } - } + // And then fall back to unspecified "not found" + if (!suggestion && !suggestedLib && nameArg) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); } suggestionCount++; } @@ -49784,12 +50520,7 @@ var ts; } return undefined; } - if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ScriptTarget.ESNext */ && useDefineForClassFields)) { - // We have a match, but the reference occurred within a property initializer and the identifier also binds - // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed - // with ESNext+useDefineForClassFields because the scope semantics are different. - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + else if (checkAndReportErrorForInvalidInitializer()) { return undefined; } // Perform extra checks only if error reporting was requested @@ -49891,7 +50622,7 @@ var ts; if (decl.kind === 163 /* SyntaxKind.TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); } } } @@ -50000,7 +50731,12 @@ var ts; function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { if (isPrimitiveTypeName(name)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(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)); + } + else { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + } return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); @@ -50020,6 +50756,16 @@ var ts; } return false; } + function isExtendedByInterface(node) { + var grandparent = node.parent.parent; + var parentOfGrandparent = grandparent.parent; + if (grandparent && parentOfGrandparent) { + var isExtending = ts.isHeritageClause(grandparent) && grandparent.token === 94 /* SyntaxKind.ExtendsKeyword */; + var isInterface = ts.isInterfaceDeclaration(parentOfGrandparent); + return isExtending && isInterface; + } + return false; + } function maybeMappedType(node, symbol) { var container = ts.findAncestor(node.parent, function (n) { return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit"; @@ -50151,7 +50897,8 @@ var ts; && isAliasableOrJsExpression(node.parent.right) || node.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || node.kind === 296 /* SyntaxKind.PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node); + || node.kind === 254 /* SyntaxKind.VariableDeclaration */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) + || node.kind === 203 /* SyntaxKind.BindingElement */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -50244,7 +50991,7 @@ var ts; return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker - return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); + return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { var _a; @@ -50522,10 +51269,6 @@ var ts; checkExpressionCached(expression); return getNodeLinks(expression).resolvedSymbol; } - function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) { - var expression = node.initializer; - return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve); - } function getTargetOfAccessExpression(node, dontRecursivelyResolve) { if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */)) { return undefined; @@ -50557,7 +51300,7 @@ var ts; case 297 /* SyntaxKind.ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); case 296 /* SyntaxKind.PropertyAssignment */: - return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); + return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); case 207 /* SyntaxKind.ElementAccessExpression */: case 206 /* SyntaxKind.PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); @@ -50962,7 +51705,40 @@ var ts; // An override clause will take effect for type-only imports and import types, and allows importing the types across formats, regardless of // normal mode restrictions if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext && !ts.getResolutionModeOverrideForClause(overrideClause)) { - error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); + if (ts.findAncestor(location, ts.isImportEqualsDeclaration)) { + // ImportEquals in a ESM file resolving to another ESM file + error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); + } + else { + // CJS file resolving to an ESM file + var diagnosticDetails = void 0; + var ext = ts.tryGetExtensionFromPath(currentSourceFile.fileName); + if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) { + var scope = currentSourceFile.packageJsonScope; + var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined; + if (scope && !scope.packageJsonContent.type) { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json")); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, ts.combinePaths(scope.packageDirectory, "package.json")); + } + } + else { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, targetExt); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module); + } + } + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(diagnosticDetails, ts.Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, moduleReference))); + } } } // merged symbol is module declaration symbol combined with all augmentations @@ -51471,8 +52247,9 @@ var ts; function getExportSymbolOfValueSymbolIfExported(symbol) { return getMergedSymbol(symbol && (symbol.flags & 1048576 /* SymbolFlags.ExportValue */) !== 0 && symbol.exportSymbol || symbol); } - function symbolIsValue(symbol) { - return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && !getTypeOnlyAliasDeclaration(symbol)); + function symbolIsValue(symbol, includeTypeOnlyMembers) { + return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || + symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -51512,7 +52289,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getStringLiteralType)); + return getUnionType(ts.arrayFrom(typeofNEFacts.keys(), getStringLiteralType)); } function createTypeParameter(symbol) { var type = createType(262144 /* TypeFlags.TypeParameter */); @@ -51921,13 +52698,25 @@ var ts; && isDeclarationVisible(declaration.parent)) { return addVisibleAlias(declaration, declaration); } - else if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isBindingElement(declaration) && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement - && ts.isVariableDeclaration(declaration.parent.parent) - && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) - && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) - && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) - && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { - return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + else if (ts.isBindingElement(declaration)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement + && ts.isVariableDeclaration(declaration.parent.parent) + && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) + && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) + && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) + && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + } + else if (symbol.flags & 2 /* SymbolFlags.BlockScopedVariable */) { + var variableStatement = ts.findAncestor(declaration, ts.isVariableStatement); + if (ts.hasSyntacticModifier(variableStatement, 1 /* ModifierFlags.Export */)) { + return true; + } + if (!isDeclarationVisible(variableStatement.parent)) { + return false; + } + return addVisibleAlias(declaration, variableStatement); + } } // Declaration is not visible return false; @@ -51969,6 +52758,9 @@ var ts; if (symbol && symbol.flags & 262144 /* SymbolFlags.TypeParameter */ && meaning & 788968 /* SymbolFlags.Type */) { return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; } + if (!symbol && ts.isThisIdentifier(firstIdentifier) && isSymbolAccessible(getSymbolOfNode(ts.getThisContainer(firstIdentifier, /*includeArrowFunctions*/ false)), firstIdentifier, meaning, /*computeAliases*/ false).accessibility === 0 /* SymbolAccessibility.Accessible */) { + return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; + } // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* SymbolAccessibility.NotAccessible */, @@ -52057,7 +52849,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* TypeFormatFlags.None */; } - return flags & 814775659 /* TypeFormatFlags.NodeBuilderFlagsMask */; + return flags & 848330091 /* TypeFormatFlags.NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { return !!type.symbol && !!(type.symbol.flags & 32 /* SymbolFlags.Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* TypeFlags.Object */) && !!(ts.getObjectFlags(type) & 16777216 /* ObjectFlags.IsClassInstanceClone */))); @@ -52159,6 +52951,12 @@ var ts; return context.truncating = context.approximateLength > ((context.flags & 1 /* NodeBuilderFlags.NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { + var savedFlags = context.flags; + var typeNode = typeToTypeNodeWorker(type, context); + context.flags = savedFlags; + return typeNode; + } + function typeToTypeNodeWorker(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); } @@ -52298,6 +53096,9 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* SymbolFlags.Class */)) return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes); + if (ts.length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) { + return ts.factory.createArrayTypeNode(typeArgumentNodes[0]); + } return symbolToTypeNode(type.aliasSymbol, context, 788968 /* SymbolFlags.Type */, typeArgumentNodes); } var objectFlags = ts.getObjectFlags(type); @@ -52334,8 +53135,8 @@ var ts; if (type.symbol) { return symbolToTypeNode(type.symbol, context, 788968 /* SymbolFlags.Type */); } - var name = (type === markerSuperType || type === markerSubType) && varianceTypeParameter && varianceTypeParameter.symbol ? - (type === markerSubType ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; + var name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? + (type === markerSubTypeForCheck ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name), /*typeArguments*/ undefined); } if (type.flags & 1048576 /* TypeFlags.Union */ && type.origin) { @@ -52401,7 +53202,7 @@ var ts; var name = typeParameterToName(newParam, context); var newTypeVariable = ts.factory.createTypeReferenceNode(name); context.approximateLength += 37; // 15 each for two added conditionals, 7 for an added infer type - var newMapper = prependTypeMapping(type.root.checkType, newParam, type.combinedMapper || type.mapper); + var newMapper = prependTypeMapping(type.root.checkType, newParam, type.mapper); var saveInferTypeParameters_1 = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode_1 = typeToTypeNodeHelper(instantiateType(type.root.extendsType, newMapper), context); @@ -52442,6 +53243,10 @@ var ts; } return typeToTypeNodeHelper(type, context); } + function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) { + return isMappedTypeWithKeyofConstraintDeclaration(type) + && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */); + } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 524288 /* TypeFlags.Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -52451,7 +53256,7 @@ var ts; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` - if (!(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { var newParam = createTypeParameter(createSymbol(262144 /* SymbolFlags.TypeParameter */, "T")); var name = typeParameterToName(newParam, context); newTypeVariable = ts.factory.createTypeReferenceNode(name); @@ -52467,11 +53272,12 @@ var ts; var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; var result = ts.setEmitFlags(mappedTypeNode, 1 /* EmitFlags.SingleLine */); - if (isMappedTypeWithKeyofConstraintDeclaration(type) && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { // homomorphic mapped type with a non-homomorphic naive inlining // wrap it with a conditional like `SomeModifiersType extends infer U ? {..the mapped type...} : never` to ensure the resulting // type stays homomorphic - return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); + var originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type.declaration.typeParameter.constraint.type)) || unknownType, type.mapper); + return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* TypeFlags.Unknown */ ? undefined : typeToTypeNodeHelper(originalConstraint, context))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); } return result; } @@ -52488,7 +53294,7 @@ var ts; // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* SymbolFlags.Class */ && !getBaseTypeVariableOfClass(symbol) - && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 226 /* SyntaxKind.ClassExpression */ && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */) || + && !(symbol.valueDeclaration && ts.isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */ && (!ts.isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*computeAliases*/ false).accessibility !== 0 /* SymbolAccessibility.Accessible */)) || symbol.flags & (384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -52754,7 +53560,7 @@ var ts; var id = ids_1[_i]; qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id; } - return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf); + return ts.factory.updateImportTypeNode(root, root.argument, root.assertions, qualifier, typeArguments, root.isTypeOf); } else { // first shift type arguments @@ -52858,7 +53664,7 @@ var ts; anyType : getNonMissingTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* CheckFlags.Late */ && isLateBoundName(propertySymbol.escapedName)) { + if (context.tracker.trackSymbol && isLateBoundName(propertySymbol.escapedName)) { if (propertySymbol.declarations) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { @@ -53003,7 +53809,6 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, @@ -53015,8 +53820,7 @@ var ts; context.encounteredError = true; } context.approximateLength += (name.length + 4); - return ts.factory.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + return ts.factory.createIndexSignature(indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { var _a, _b, _c, _d; @@ -53035,7 +53839,7 @@ var ts; var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* CheckFlags.RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 171 /* SyntaxKind.Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); - var thisParameter = tryGetThisParameterDeclaration(signature, context); + var thisParameter = context.flags & 33554432 /* NodeBuilderFlags.OmitThisParameter */ ? undefined : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { parameters.unshift(thisParameter); } @@ -53068,15 +53872,15 @@ var ts; var node = kind === 174 /* SyntaxKind.CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 175 /* SyntaxKind.ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 168 /* SyntaxKind.MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(modifiers, parameters, /*body*/ undefined) : + kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 317 /* SyntaxKind.JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 179 /* SyntaxKind.FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : kind === 180 /* SyntaxKind.ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : kind === 213 /* SyntaxKind.FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : kind === 214 /* SyntaxKind.ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); @@ -53093,7 +53897,6 @@ var ts; var thisTag = ts.getJSDocThisTag(signature.declaration); if (thisTag && thisTag.typeExpression) { return ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); @@ -53125,7 +53928,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); - var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined; + var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && ts.canHaveModifiers(parameterDeclaration) ? ts.map(ts.getModifiers(parameterDeclaration), ts.factory.cloneNode) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* CheckFlags.RestParameter */; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -53136,21 +53939,27 @@ var ts; ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* CheckFlags.OptionalParameter */; var questionToken = isOptional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined; - var parameterNode = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + var parameterNode = ts.factory.createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { - return elideInitializerAndSetEmitFlags(node); - function elideInitializerAndSetEmitFlags(node) { + return elideInitializerAndPropertyRenamingAndSetEmitFlags(node); + function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) { if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { trackComputedName(node.expression, context.enclosingDeclaration, context); } - var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags); if (ts.isBindingElement(visited)) { - visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, - /*initializer*/ undefined); + if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, + /* propertyName*/ undefined, visited.propertyName, + /*initializer*/ undefined); + } + else { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, + /*initializer*/ undefined); + } } if (!ts.nodeIsSynthesized(visited)) { visited = ts.factory.cloneNode(visited); @@ -53359,6 +54168,7 @@ var ts; return symbol.parent ? ts.factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var _a, _b, _c, _d; var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module var isTypeOf = meaning === 111551 /* SymbolFlags.Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { @@ -53376,6 +54186,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral("import")) ]))); + (_b = (_a = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _b === void 0 ? void 0 : _b.call(_a); } } if (!specifier) { @@ -53395,6 +54206,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral(swappedMode === ts.ModuleKind.ESNext ? "import" : "require")) ]))); + (_d = (_c = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _d === void 0 ? void 0 : _d.call(_c); } } if (!assertion) { @@ -53796,9 +54608,7 @@ var ts; } if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdotToken*/ undefined, "x", /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); @@ -53806,14 +54616,13 @@ var ts; if (ts.isJSDocFunctionType(node)) { if (ts.isJSDocConstructSignature(node)) { var newTypeNode_1; - return ts.factory.createConstructorTypeNode(node.modifiers, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createConstructorTypeNode( + /*modifiers*/ undefined, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } else { return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } @@ -53832,7 +54641,7 @@ var ts; !(ts.length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) { return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); } - return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.assertions, node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { var _a = trackExistingEntityName(node, context, includePrivateSymbol), introducesError = _a.introducesError, result = _a.node; @@ -53884,7 +54693,7 @@ var ts; } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 169 /* SyntaxKind.MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -53945,8 +54754,7 @@ var ts; var name_3 = ns.name; var body = ns.body; if (ts.length(excessExports)) { - ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, + ns = ts.factory.updateModuleDeclaration(ns, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, /*alias*/ undefined, id); })), /*moduleSpecifier*/ undefined)], false)))); @@ -53972,7 +54780,6 @@ var ts; if (ts.length(exports) > 1) { var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; }); statements = __spreadArray(__spreadArray([], nonExports, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), /*moduleSpecifier*/ undefined)], false); @@ -53987,7 +54794,6 @@ var ts; // remove group members from statements and then merge group members and add back to statements statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), true), [ ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier) ], false); @@ -54027,7 +54833,7 @@ var ts; } else { // some items filtered, others not - update the export declaration - statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); + statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); } } return statements; @@ -54092,12 +54898,11 @@ var ts; if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) { var oldContext = context; context = cloneNodeBuilderContext(context); - var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); + serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); if (context.reportedDiagnostic) { oldcontext.reportedDiagnostic = context.reportedDiagnostic; // hoist diagnostic result into outer context } context = oldContext; - return result; } } // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias @@ -54178,7 +54983,6 @@ var ts; && ((_d = type.symbol) === null || _d === void 0 ? void 0 : _d.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, alias, localName)])), 0 /* ModifierFlags.None */); context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* SymbolFlags.Value */); @@ -54211,7 +55015,6 @@ var ts; // ``` // To create an export named `g` that does _not_ shadow the local `g` addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name, localName)])), 0 /* ModifierFlags.None */); needsExportDeclaration = false; @@ -54260,16 +55063,15 @@ var ts; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); if (!resolvedModule) continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); } } } if (needsPostExportDefault) { - addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportAssignment(/*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); } else if (needsExportDeclaration) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* ModifierFlags.None */); } @@ -54337,7 +55139,7 @@ var ts; && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); - addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); + addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; context.enclosingDeclaration = oldEnclosingDecl; } @@ -54353,7 +55155,6 @@ var ts; var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* SymbolFlags.Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), constructSignatures, true), callSignatures, true), members, true)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { @@ -54379,7 +55180,6 @@ var ts; var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* InternalSymbolName.ExportEquals */; }), function (s) { var _a, _b; @@ -54396,13 +55196,11 @@ var ts; return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name === targetName ? undefined : targetName, name); })))]); addResult(ts.factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* NodeFlags.Namespace */), 0 /* ModifierFlags.None */); } } function serializeEnum(symbol, symbolName, modifierFlags) { - addResult(ts.factory.createEnumDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { + addResult(ts.factory.createEnumDeclaration(ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { // TODO: Handle computed names // I hate that to get the initialized value we need to walk back to the declarations here; but there's no // other way to get the possible const value of an enum member that I'm aware of, as the value is cached @@ -54463,7 +55261,7 @@ var ts; // emit akin to the above would be needed. // Add a namespace // Create namespace as non-synthetic so it is usable as an enclosing declaration - var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace, enclosingDeclaration); fakespace.locals = ts.createSymbolTable(props); fakespace.symbol = props[0].parent; @@ -54482,11 +55280,10 @@ var ts; results = oldResults; // replace namespace with synthetic version var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, d.expression, ts.factory.createIdentifier("default" /* InternalSymbolName.Default */))])) : d; }); var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* ModifierFlags.Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced; - fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); + fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); addResult(fakespace, modifierFlags); // namespaces can never be default exported } } @@ -54542,7 +55339,7 @@ var ts; ? getBaseConstructorTypeOfClass(staticType) : anyType; var heritageClauses = __spreadArray(__spreadArray([], !ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], true), !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(117 /* SyntaxKind.ImplementsKeyword */, implementsExpressions)], true); - var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); + var symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties @@ -54560,7 +55357,6 @@ var ts; // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? [ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -54577,12 +55373,11 @@ var ts; ts.isInJSFile(symbol.valueDeclaration) && !ts.some(getSignaturesOfType(staticType, 1 /* SignatureKind.Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? - [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : + [ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : serializeSignatures(1 /* SignatureKind.Construct */, staticType, staticBaseType, 171 /* SyntaxKind.Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), staticMembers, true), constructors, true), publicProperties, true), privateProperties, true)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags); } function getSomeTargetNameFromDeclarations(declarations) { @@ -54634,7 +55429,6 @@ var ts; var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier( /*isTypeOnly*/ false, propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1), /*importClause*/ undefined), 0 /* ModifierFlags.None */); @@ -54658,12 +55452,10 @@ var ts; var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); // 'y' // import _x = require('y'); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* ModifierFlags.None */); // import x = _x.z addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); break; @@ -54680,7 +55472,6 @@ var ts; // an external `import localName = require("whatever")` var isLocalImport = !(target.flags & 512 /* SymbolFlags.ValueModule */) && !ts.isVariableDeclaration(node); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), isLocalImport ? symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false) @@ -54694,7 +55485,6 @@ var ts; break; case 267 /* SyntaxKind.ImportClause */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag @@ -54704,19 +55494,16 @@ var ts; break; case 268 /* SyntaxKind.NamespaceImport */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), /*assertClause*/ undefined), 0 /* ModifierFlags.None */); break; case 274 /* SyntaxKind.NamespaceExport */: addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* ModifierFlags.None */); break; case 270 /* SyntaxKind.ImportSpecifier */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamedImports([ @@ -54755,7 +55542,6 @@ var ts; } function serializeExportSpecifier(localName, targetName, specifier) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* ModifierFlags.None */); } @@ -54796,7 +55582,6 @@ var ts; context.tracker.trackSymbol = function () { return false; }; if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* SymbolFlags.All */))); } else { @@ -54811,7 +55596,6 @@ var ts; // serialize as `import _Ref = t.arg.et; export { _Ref as name }` var varName = getUnusedName(name, symbol); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false)), 0 /* ModifierFlags.None */); serializeExportSpecifier(name, varName); @@ -54842,7 +55626,6 @@ var ts; } if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName))); return true; } @@ -54892,9 +55675,7 @@ var ts; if (p.flags & 98304 /* SymbolFlags.Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SymbolFlags.SetAccessor */) { - result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], @@ -54902,8 +55683,7 @@ var ts; } if (p.flags & 32768 /* SymbolFlags.GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* ModifierFlags.Private */; - result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; @@ -54911,8 +55691,7 @@ var ts; // This is an else/if as accessors and properties can't merge in TS, but might in JS // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* SymbolFlags.Property */ | 3 /* SymbolFlags.Variable */ | 98304 /* SymbolFlags.Accessor */)) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); @@ -54921,8 +55700,7 @@ var ts; var type = getTypeOfSymbol(p); var signatures = getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (flag & 8 /* ModifierFlags.Private */) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, /*type*/ undefined, /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } @@ -54980,8 +55758,7 @@ var ts; } } if (privateProtected) { - return [ts.setTextRange(ts.factory.createConstructorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), + return [ts.setTextRange(ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(privateProtected), /*parameters*/ [], /*body*/ undefined), signatures[0].declaration)]; } @@ -55680,7 +56457,7 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 32768 /* TypeFlags.Undefined */) ? getNonUndefinedType(type) : type; + return strictNullChecks && !(getTypeFacts(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 16777216 /* TypeFacts.IsUndefined */) ? getNonUndefinedType(type) : type; } return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)], 2 /* UnionReduction.Subtype */)); } @@ -56081,7 +56858,7 @@ var ts; (resolvedSymbol || symbol).exports.forEach(function (s, name) { var _a; var exportedMember = members_4.get(name); - if (exportedMember && exportedMember !== s) { + if (exportedMember && exportedMember !== s && !(s.flags & 2097152 /* SymbolFlags.Alias */)) { if (s.flags & 111551 /* SymbolFlags.Value */ && exportedMember.flags & 111551 /* SymbolFlags.Value */) { // If the member has an additional value-like declaration, union the types from the two declarations, // but issue an error if they occurred in two different files. The purpose is to support a JS file with @@ -56115,6 +56892,17 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.indexInfos); + if (initialSize === members_4.size) { + if (type.aliasSymbol) { + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = type.aliasTypeArguments; + } + if (ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */) { + result.aliasSymbol = type.symbol; + var args = getTypeArguments(type); + result.aliasTypeArguments = ts.length(args) ? args : undefined; + } + } result.objectFlags |= (ts.getObjectFlags(type) & 4096 /* ObjectFlags.JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* SymbolFlags.Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { result.objectFlags |= 16777216 /* ObjectFlags.IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type @@ -56166,11 +56954,7 @@ var ts; if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAny(element, anyType); } - // When we're including the pattern in the type (an indication we're obtaining a contextual type), we - // use the non-inferrable any type. Inference will never directly infer this type, but it is possible - // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases, - // widening of the binding pattern type substitutes a regular any for the non-inferrable any. - return includePatternInType ? nonInferrableAnyType : anyType; + return anyType; } // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { @@ -57171,7 +57955,7 @@ var ts; error(declaration.typeExpression.type, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } else { - error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + error(ts.isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } } links.declaredType = type; @@ -58475,6 +59259,9 @@ var ts; else if (type.objectFlags & 32 /* ObjectFlags.Mapped */) { resolveMappedTypeMembers(type); } + else { + ts.Debug.fail("Unhandled object type " + ts.Debug.formatObjectFlags(type.objectFlags)); + } } else if (type.flags & 1048576 /* TypeFlags.Union */) { resolveUnionTypeMembers(type); @@ -58482,6 +59269,9 @@ var ts; else if (type.flags & 2097152 /* TypeFlags.Intersection */) { resolveIntersectionTypeMembers(type); } + else { + ts.Debug.fail("Unhandled type " + ts.Debug.formatTypeFlags(type.flags)); + } } return type; } @@ -58669,7 +59459,7 @@ var ts; } } } - else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { hasDisjointDomainType = true; } } @@ -58681,12 +59471,13 @@ var ts; // intersection operation to reduce the union constraints. for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { var t = types_6[_a]; - if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { constraints = ts.append(constraints, t); } } } - return getIntersectionType(constraints); + // The source types were normalized; ensure the result is normalized too. + return getNormalizedType(getIntersectionType(constraints), /*writing*/ false); } return undefined; } @@ -58797,7 +59588,7 @@ var ts; } if (t.flags & 268435456 /* TypeFlags.StringMapping */) { var constraint = getBaseConstraint(t.type); - return constraint ? getStringMappingType(t.symbol, constraint) : stringType; + return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType; } if (t.flags & 8388608 /* TypeFlags.IndexedAccess */) { if (isMappedTypeGenericIndexedAccess(t)) { @@ -58883,7 +59674,7 @@ var ts; var objectType; return !!(type.flags & 8388608 /* TypeFlags.IndexedAccess */ && ts.getObjectFlags(objectType = type.objectType) & 32 /* ObjectFlags.Mapped */ && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && - !objectType.declaration.questionToken && !objectType.declaration.nameType); + !(getMappedTypeModifiers(objectType) & 8 /* MappedTypeModifiers.ExcludeOptional */) && !objectType.declaration.nameType); } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, @@ -59162,12 +59953,12 @@ var ts; * @param type a type to look up property from * @param name a name of property to look up in a given type */ - function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment) { + function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) { type = getReducedApparentType(type); if (type.flags & 524288 /* TypeFlags.Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { + if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) { return symbol; } if (skipObjectFunctionPropertyAugment) @@ -59273,12 +60064,15 @@ var ts; // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(declaration) { + var _a; var result; - for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { - var node = _a[_i]; + for (var _i = 0, _b = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _b.length; _i++) { + var node = _b[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); } - return result; + return (result === null || result === void 0 ? void 0 : result.length) ? result + : ts.isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) === null || _a === void 0 ? void 0 : _a.typeParameters + : undefined; } function symbolsToArray(symbols) { var result = []; @@ -59829,8 +60623,7 @@ var ts; var _a; var inferences; if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { - for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; + var _loop_15 = function (declaration) { if (declaration.parent.kind === 190 /* SyntaxKind.InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the @@ -59838,12 +60631,12 @@ var ts; // present, we form an intersection of the inferred constraint types. var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; if (grandParent.kind === 178 /* SyntaxKind.TypeReference */ && !omitTypeReferences) { - var typeReference = grandParent; - var typeParameters = getTypeParametersForTypeReference(typeReference); - if (typeParameters) { - var index = typeReference.typeArguments.indexOf(childTypeParameter); - if (index < typeParameters.length) { - var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + var typeReference_1 = grandParent; + var typeParameters_1 = getTypeParametersForTypeReference(typeReference_1); + if (typeParameters_1) { + var index = typeReference_1.typeArguments.indexOf(childTypeParameter); + if (index < typeParameters_1.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters_1[index]); if (declaredConstraint) { // Type parameter constraints can reference other type parameters so // constraints need to be instantiated. If instantiation produces the @@ -59851,7 +60644,9 @@ var ts; // type Foo = [T, U]; // type Bar = T extends Foo ? Foo : T; // the instantiated constraint for U is X, so we discard that inference. - var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var mapper = makeDeferredTypeMapper(typeParameters_1, typeParameters_1.map(function (_, index) { return function () { + return getEffectiveTypeArgumentAtIndex(typeReference_1, typeParameters_1, index); + }; })); var constraint = instantiateType(declaredConstraint, mapper); if (constraint !== typeParameter) { inferences = ts.append(inferences, constraint); @@ -59889,6 +60684,10 @@ var ts; inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); } } + }; + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + _loop_15(declaration); } } return inferences && getIntersectionType(inferences); @@ -59951,13 +60750,13 @@ var ts; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type - // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // of an object literal or a non-inferrable type. This is because there are operations in the type checker // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type = types_8[_i]; - if (!(type.flags & excludeKinds)) { + if (excludeKinds === undefined || !(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } } @@ -59969,7 +60768,7 @@ var ts; if (!type) { type = createObjectType(4 /* ObjectFlags.Reference */, target.symbol); target.instantiations.set(id, type); - type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0; type.target = target; type.resolvedTypeArguments = typeArguments; } @@ -60777,7 +61576,7 @@ var ts; var lastRequiredIndex = -1; var firstRestIndex = -1; var lastOptionalOrRestIndex = -1; - var _loop_15 = function (i) { + var _loop_16 = function (i) { var type = elementTypes[i]; var flags = target.elementFlags[i]; if (flags & 8 /* ElementFlags.Variadic */) { @@ -60807,7 +61606,7 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - var state_4 = _loop_15(i); + var state_4 = _loop_16(i); if (typeof state_4 === "object") return state_4.value; } @@ -61003,7 +61802,7 @@ var ts; var templates = ts.filter(types, isPatternLiteralType); if (templates.length) { var i = types.length; - var _loop_16 = function () { + var _loop_17 = function () { i--; var t = types[i]; if (t.flags & 128 /* TypeFlags.StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { @@ -61011,7 +61810,7 @@ var ts; } }; while (i > 0) { - _loop_16(); + _loop_17(); } } } @@ -61088,14 +61887,14 @@ var ts; var namedUnions = []; addNamedUnions(namedUnions, types); var reducedTypes = []; - var _loop_17 = function (t) { + var _loop_18 = function (t) { if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) { reducedTypes.push(t); } }; for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) { var t = typeSet_1[_i]; - _loop_17(t); + _loop_18(t); } if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) { return namedUnions[0]; @@ -61230,7 +62029,7 @@ var ts; } return includes; } - function removeRedundantPrimitiveTypes(types, includes) { + function removeRedundantSupertypes(types, includes) { var i = types.length; while (i > 0) { i--; @@ -61238,7 +62037,9 @@ var ts; var remove = t.flags & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || t.flags & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || t.flags & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */; + t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + t.flags & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + isEmptyAnonymousObjectType(t) && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -61360,7 +62161,7 @@ var ts; // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types, aliasSymbol, aliasTypeArguments, noSupertypeReduction) { var typeMembershipMap = new ts.Map(); var includes = addTypesToIntersection(typeMembershipMap, 0, types); var typeSet = ts.arrayFrom(typeMembershipMap.values()); @@ -61397,11 +62198,11 @@ var ts; if (includes & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || includes & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || includes & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */) { - removeRedundantPrimitiveTypes(typeSet, includes); - } - if (includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 524288 /* TypeFlags.Object */) { - ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + includes & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */) { + if (!noSupertypeReduction) + removeRedundantSupertypes(typeSet, includes); } if (includes & 262144 /* TypeFlags.IncludesMissingType */) { typeSet[typeSet.indexOf(undefinedType)] = missingType; @@ -61440,8 +62241,9 @@ var ts; } var constituents = getCrossProductIntersections(typeSet); // We attach a denormalized origin type when at least one constituent of the cross-product union is an - // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions). - var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; + // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions) and + // the denormalized origin has fewer constituents than the union itself. + var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; result = getUnionType(constituents, 1 /* UnionReduction.Literal */, aliasSymbol, aliasTypeArguments, origin); } } @@ -61484,11 +62286,21 @@ var ts; } return intersections; } + function getConstituentCount(type) { + return !(type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) || type.aliasSymbol ? 1 : + type.flags & 1048576 /* TypeFlags.Union */ && type.origin ? getConstituentCount(type.origin) : + getConstituentCountOfTypes(type.types); + } + function getConstituentCountOfTypes(types) { + return ts.reduceLeft(types, function (n, t) { return n + getConstituentCount(t); }, 0); + } function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var aliasSymbol = getAliasSymbolForTypeNode(node); - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var types = ts.map(node.types, getTypeFromTypeNode); + var noSupertypeReduction = types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType; + links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); } return links.resolvedType; } @@ -61616,19 +62428,22 @@ var ts; * to reduce the resulting type if possible (since only intersections with conflicting literal-typed properties are reducible). */ function isPossiblyReducibleByInstantiation(type) { - return ts.some(type.types, function (t) { - var uniqueFilled = getUniqueLiteralFilledInstantiation(t); - return getReducedType(uniqueFilled) !== uniqueFilled; - }); + var uniqueFilled = getUniqueLiteralFilledInstantiation(type); + return getReducedType(uniqueFilled) !== uniqueFilled; + } + function shouldDeferIndexType(type) { + return !!(type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || + isGenericTupleType(type) || + isGenericMappedType(type) && !hasDistributiveNameType(type) || + type.flags & 1048576 /* TypeFlags.Union */ && ts.some(type.types, isPossiblyReducibleByInstantiation) || + type.flags & 2097152 /* TypeFlags.Intersection */ && maybeTypeOfKind(type, 465829888 /* TypeFlags.Instantiable */) && ts.some(type.types, isEmptyAnonymousObjectType)); } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } type = getReducedType(type); - return type.flags & 1048576 /* TypeFlags.Union */ ? isPossiblyReducibleByInstantiation(type) - ? getIndexTypeForGenericType(type, stringsOnly) - : getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + return shouldDeferIndexType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + type.flags & 1048576 /* TypeFlags.Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : + type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ ? getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) : type === wildcardType ? wildcardType : type.flags & 2 /* TypeFlags.Unknown */ ? neverType : @@ -61754,9 +62569,12 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type; + // 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; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -61767,6 +62585,15 @@ var ts; } return str; } + function applyTemplateStringMapping(symbol, texts, types) { + switch (intrinsicTypeKinds.get(symbol.escapedName)) { + case 0 /* IntrinsicTypeKind.Uppercase */: return [texts.map(function (t) { return t.toUpperCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 1 /* IntrinsicTypeKind.Lowercase */: return [texts.map(function (t) { return t.toLowerCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 2 /* IntrinsicTypeKind.Capitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toUpperCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + case 3 /* IntrinsicTypeKind.Uncapitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toLowerCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + } + return [texts, types]; + } function getStringMappingTypeForGenericType(symbol, type) { var id = "".concat(getSymbolId(symbol), ",").concat(getTypeId(type)); var result = stringMappingTypes.get(id); @@ -61868,21 +62695,28 @@ var ts; getFlowTypeOfReference(accessExpression, propType) : propType; } - if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName) && +propName >= 0) { + if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName)) { + var index = +propName; if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 16 /* AccessFlags.NoTupleBoundsCheck */)) { var indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { + if (index < 0) { + error(indexNode, ts.Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); + return undefinedType; + } error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); } else { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } } - errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, function (t) { - var restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; - }); + if (index >= 0) { + errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); + return mapType(objectType, function (t) { + var restType = getRestTypeOfTupleType(t) || undefinedType; + return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; + }); + } } } if (!(indexType.flags & 98304 /* TypeFlags.Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* TypeFlags.StringLike */ | 296 /* TypeFlags.NumberLike */ | 12288 /* TypeFlags.ESSymbolLike */)) { @@ -62008,7 +62842,7 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -62146,7 +62980,7 @@ var ts; function substituteIndexedMappedType(objectType, index) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]); var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return instantiateType(getTemplateTypeFromMappedType(objectType.target || objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) { if (accessFlags === void 0) { accessFlags = 0 /* AccessFlags.None */; } @@ -62294,7 +63128,7 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_18 = function () { + var _loop_19 = function () { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; @@ -62415,7 +63249,7 @@ var ts; // 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_5 = _loop_18(); + var state_5 = _loop_19(); if (typeof state_5 === "object") return state_5.value; if (state_5 === "break") @@ -62516,6 +63350,7 @@ var ts; } } function getTypeFromImportTypeNode(node) { + var _a; var links = getNodeLinks(node); if (!links.resolvedType) { if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments @@ -62535,6 +63370,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } + var isExportEquals = !!((_a = innerModuleSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* InternalSymbolName.ExportEquals */)); var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); @@ -62546,9 +63382,11 @@ var ts; // That, in turn, ultimately uses `getPropertyOfType` on the type of the symbol, which differs slightly from // the `exports` lookup process that only looks up namespace members which is used for most type references var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace)); - var next = node.isTypeOf - ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText) - : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var symbolFromVariable = node.isTypeOf || ts.isInJSFile(node) && isExportEquals + ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ true) + : undefined; + var symbolFromModule = node.isTypeOf ? undefined : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var next = symbolFromModule !== null && symbolFromModule !== void 0 ? symbolFromModule : symbolFromVariable; if (!next) { error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); return links.resolvedType = errorType; @@ -63045,7 +63883,7 @@ var ts; switch (mapper.kind) { case 0 /* TypeMapKind.Simple */: return type === mapper.source ? mapper.target : type; - case 1 /* TypeMapKind.Array */: + case 1 /* TypeMapKind.Array */: { var sources = mapper.sources; var targets = mapper.targets; for (var i = 0; i < sources.length; i++) { @@ -63054,25 +63892,39 @@ var ts; } } return type; - case 2 /* TypeMapKind.Function */: + } + case 2 /* TypeMapKind.Deferred */: { + var sources = mapper.sources; + var targets = mapper.targets; + for (var i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets[i](); + } + } + return type; + } + case 3 /* TypeMapKind.Function */: return mapper.func(type); - case 3 /* TypeMapKind.Composite */: - case 4 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: + case 5 /* TypeMapKind.Merged */: var t1 = getMappedType(type, mapper.mapper1); - return t1 !== type && mapper.kind === 3 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); + return t1 !== type && mapper.kind === 4 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); } } function makeUnaryTypeMapper(source, target) { - return { kind: 0 /* TypeMapKind.Simple */, source: source, target: target }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 0 /* TypeMapKind.Simple */, source: source, target: target }); } function makeArrayTypeMapper(sources, targets) { - return { kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }); } - function makeFunctionTypeMapper(func) { - return { kind: 2 /* TypeMapKind.Function */, func: func }; + function makeFunctionTypeMapper(func, debugInfo) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 3 /* TypeMapKind.Function */, func: func, debugInfo: ts.Debug.isDebugging ? debugInfo : undefined }); + } + function makeDeferredTypeMapper(sources, targets) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 2 /* TypeMapKind.Deferred */, sources: sources, targets: targets }); } function makeCompositeTypeMapper(kind, mapper1, mapper2) { - return { kind: kind, mapper1: mapper1, mapper2: mapper2 }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: kind, mapper1: mapper1, mapper2: mapper2 }); } function createTypeEraser(sources) { return createTypeMapper(sources, /*targets*/ undefined); @@ -63082,19 +63934,20 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(context, index) { - return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; }); + var forwardInferences = context.inferences.slice(index); + return createTypeMapper(ts.map(forwardInferences, function (i) { return i.typeParameter; }), ts.map(forwardInferences, function () { return unknownType; })); } function combineTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(3 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; } function mergeTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; } function prependTypeMapping(source, target, mapper) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); } function appendTypeMapping(mapper, source, target) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); } function getRestrictiveTypeParameter(tp) { return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), @@ -63360,6 +64213,7 @@ var ts; result.mapper = mapper; result.aliasSymbol = aliasSymbol || type.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + result.objectFlags |= result.aliasTypeArguments ? getPropagatingFlagsOfTypes(result.aliasTypeArguments) : 0; return result; } function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { @@ -64008,7 +64862,7 @@ var ts; }); } function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; if (isTupleLikeType(source)) { return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); @@ -64075,7 +64929,7 @@ var ts; }); } function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); } @@ -64162,7 +65016,7 @@ var ts; var sourceSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && - (getFalsyFlags(sourceType) & 98304 /* TypeFlags.Nullable */) === (getFalsyFlags(targetType) & 98304 /* TypeFlags.Nullable */); + (getTypeFacts(sourceType) & 50331648 /* TypeFacts.IsUndefinedOrNull */) === (getTypeFacts(targetType) & 50331648 /* TypeFacts.IsUndefinedOrNull */); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* SignatureCheckMode.StrictArity */) | (strictVariance ? 2 /* SignatureCheckMode.StrictCallback */ : 1 /* SignatureCheckMode.BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* SignatureCheckMode.Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); @@ -64274,6 +65128,20 @@ var ts; return !!(ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && (type.members && isEmptyResolvedType(type) || type.symbol && type.symbol.flags & 2048 /* SymbolFlags.TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0)); } + function isUnknownLikeUnionType(type) { + if (strictNullChecks && type.flags & 1048576 /* TypeFlags.Union */) { + if (!(type.objectFlags & 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */)) { + var types = type.types; + type.objectFlags |= 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */ | (types.length >= 3 && types[0].flags & 32768 /* TypeFlags.Undefined */ && + types[1].flags & 65536 /* TypeFlags.Null */ && ts.some(types, isEmptyAnonymousObjectType) ? 67108864 /* ObjectFlags.IsUnknownLikeUnion */ : 0); + } + return !!(type.objectFlags & 67108864 /* ObjectFlags.IsUnknownLikeUnion */); + } + return false; + } + function containsUndefinedType(type) { + return !!((type.flags & 1048576 /* TypeFlags.Union */ ? type.types[0] : type).flags & 32768 /* TypeFlags.Undefined */); + } function isStringIndexSignatureOnlyType(type) { return type.flags & 524288 /* TypeFlags.Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) || @@ -64353,7 +65221,7 @@ var ts; return true; if (s & 65536 /* TypeFlags.Null */ && (!strictNullChecks && !(t & 3145728 /* TypeFlags.UnionOrIntersection */) || t & 65536 /* TypeFlags.Null */)) return true; - if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */) + if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(ts.getObjectFlags(source) & 8192 /* ObjectFlags.FreshLiteral */))) return true; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* TypeFlags.Any */) @@ -64363,6 +65231,9 @@ var ts; // bit-flag enum types sometimes look like literal enum types with numeric literal values. if (s & (8 /* TypeFlags.Number */ | 256 /* TypeFlags.NumberLiteral */) && !(s & 1024 /* TypeFlags.EnumLiteral */) && (t & 32 /* TypeFlags.Enum */ || relation === assignableRelation && t & 256 /* TypeFlags.NumberLiteral */ && t & 1024 /* TypeFlags.EnumLiteral */)) return true; + // Anything is assignable to a union containing undefined, null, and {} + if (isUnknownLikeUnionType(target)) + return true; } return false; } @@ -64405,16 +65276,27 @@ var ts; function getNormalizedType(type, writing) { while (true) { var t = isFreshLiteralType(type) ? type.regularType : - ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getReducedType(type) : + ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : + type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* TypeFlags.Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* TypeFlags.Simplifiable */ ? getSimplifiedType(type, writing) : type; - t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) - break; + return t; type = t; } + } + function getNormalizedUnionOrIntersectionType(type, writing) { + var reduced = getReducedType(type); + if (reduced !== type) { + return reduced; + } + if (type.flags & 2097152 /* TypeFlags.Intersection */) { + var normalizedTypes = ts.sameMap(type.types, function (t) { return getNormalizedType(t, writing); }); + if (normalizedTypes !== type.types) { + return getIntersectionType(normalizedTypes); + } + } return type; } /** @@ -64646,7 +65528,7 @@ var ts; ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable"); generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); } - if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperType && target !== markerSubType) { + if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperTypeForCheck && target !== markerSubTypeForCheck) { var constraint = getBaseConstraintOfType(target); var needsOriginalSource = void 0; if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) { @@ -64861,6 +65743,7 @@ var ts; return 0 /* Ternary.False */; } function reportErrorResults(originalSource, originalTarget, source, target, headMessage) { + var _a, _b; var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; @@ -64901,6 +65784,14 @@ var ts; return; } reportRelationError(headMessage, source, target); + if (source.flags & 262144 /* TypeFlags.TypeParameter */ && ((_b = (_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) === null || _b === void 0 ? void 0 : _b[0]) && !getConstraintOfType(source)) { + var syntheticParam = cloneTypeParameter(source); + syntheticParam.constraint = instantiateType(target, makeUnaryTypeMapper(source, syntheticParam)); + if (hasNonCircularBaseConstraint(syntheticParam)) { + var targetConstraintString = typeToString(target, source.symbol.declarations[0]); + associateRelatedInfo(ts.createDiagnosticForNode(source.symbol.declarations[0], ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint, targetConstraintString)); + } + } } function traceUnionsOrIntersectionsTooLarge(source, target) { if (!ts.tracing) { @@ -64953,7 +65844,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_19 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -65016,7 +65907,7 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_6 = _loop_19(prop); + var state_6 = _loop_20(prop); if (typeof state_6 === "object") return state_6.value; } @@ -65038,7 +65929,7 @@ var ts; return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* TypeFlags.Primitive */) && !(target.flags & 131068 /* TypeFlags.Primitive */)); } if (target.flags & 2097152 /* TypeFlags.Intersection */) { - return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* IntersectionState.Target */); + return typeRelatedToEachType(source, target, reportErrors, 2 /* IntersectionState.Target */); } // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the // constraints of all non-primitive types in the source into a new intersection. We do this because the @@ -65248,10 +66139,10 @@ var ts; // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component var saved = entry & 24 /* RelationComparisonResult.ReportsMask */; if (saved & 8 /* RelationComparisonResult.ReportsUnmeasurable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers)); + instantiateType(source, reportUnmeasurableMapper); } if (saved & 16 /* RelationComparisonResult.ReportsUnreliable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } } return entry & 1 /* RelationComparisonResult.Succeeded */ ? -1 /* Ternary.True */ : 0 /* Ternary.False */; @@ -65351,13 +66242,40 @@ var ts; return result; } 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 */)) { + // 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 + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + // This also handles type parameters, as a type parameter with a union constraint compared against a union + // 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 && 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) { + resetErrorInfo(saveErrorInfo); + } + 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; - var saveErrorInfo = captureErrorCalculationState(); var sourceFlags = source.flags; var targetFlags = target.flags; if (relation === identityRelation) { @@ -65403,29 +66321,6 @@ var ts; if (result = unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState)) { return result; } - if (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */) { - // 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 - // when the target is a union type. Another is when the intersection contains types belonging - // to one of the disjoint domains. For example, given type variables T and U, each with the - // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and - // we need to check this constraint against a union on the target side. Also, given a type - // variable V constrained to 'string | number', 'V & number' has a combined constraint of - // 'string & number | number & number' which reduces to just 'number'. - // This also handles type parameters, as a type parameter with a union constraint compared against a union - // 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 && 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 - if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - } // The ordered decomposition above doesn't handle all cases. Specifically, we also need to handle: // Source is instantiable (e.g. source has union or intersection constraint). // Source is an object, target is a union (e.g. { a, b: boolean } <=> { a, b: true } | { a, b: false }). @@ -65469,6 +66364,20 @@ var ts; } } } + if (relation === comparableRelation && sourceFlags & 262144 /* TypeFlags.TypeParameter */) { + // This is a carve-out in comparability to essentially forbid comparing a type parameter + // 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 */) { + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { + return result; + } + constraint = getConstraintOfTypeParameter(constraint); + } + } + return 0 /* Ternary.False */; + } } else if (targetFlags & 4194304 /* TypeFlags.Index */) { var targetType_1 = target.type; @@ -65532,7 +66441,6 @@ var ts; result &= isRelatedTo(source.indexType, target.indexType, 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } if (reportErrors) { @@ -65635,7 +66543,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } var c = target; @@ -65650,7 +66557,6 @@ var ts; if (result = skipTrue ? -1 /* Ternary.True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false)) { result &= skipFalse ? -1 /* Ternary.True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false); if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65663,31 +66569,29 @@ var ts; } // Report unreliable variance for type variables referenced in template literal type placeholders. // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* Ternary.True */; } } + else if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + if (!(source.flags & 268435456 /* TypeFlags.StringMapping */)) { + if (isMemberOfStringMapping(source, target)) { + return -1 /* Ternary.True */; + } + } + } if (sourceFlags & 8650752 /* TypeFlags.TypeVariable */) { // IndexedAccess comparisons are handled above in the `targetFlags & TypeFlage.IndexedAccess` branch if (!(sourceFlags & 8388608 /* TypeFlags.IndexedAccess */ && targetFlags & 8388608 /* TypeFlags.IndexedAccess */)) { - var constraint = getConstraintOfType(source); - if (!constraint || (sourceFlags & 262144 /* TypeFlags.TypeParameter */ && constraint.flags & 1 /* TypeFlags.Any */)) { - // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* TypeFlags.NonPrimitive */), 3 /* RecursionFlags.Both */)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } + var constraint = getConstraintOfType(source) || unknownType; // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed - else if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && constraint !== unknownType && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { return result; } if (isMappedTypeGenericIndexedAccess(source)) { @@ -65696,7 +66600,6 @@ var ts; var indexConstraint = getConstraintOfType(source.indexType); if (indexConstraint) { if (result = isRelatedTo(getIndexedAccessType(source.objectType, indexConstraint), target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65705,7 +66608,6 @@ var ts; } else if (sourceFlags & 4194304 /* TypeFlags.Index */) { if (result = isRelatedTo(keyofConstraintType, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65713,22 +66615,22 @@ var ts; if (!(targetFlags & 134217728 /* TypeFlags.TemplateLiteral */)) { var constraint = getBaseConstraintOfType(source); if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } } else if (sourceFlags & 268435456 /* TypeFlags.StringMapping */) { - if (targetFlags & 268435456 /* TypeFlags.StringMapping */ && source.symbol === target.symbol) { + if (targetFlags & 268435456 /* TypeFlags.StringMapping */) { + if (source.symbol !== target.symbol) { + return 0 /* Ternary.False */; + } if (result = isRelatedTo(source.type, target.type, 3 /* RecursionFlags.Both */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } else { var constraint = getBaseConstraintOfType(source); if (constraint && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65737,7 +66639,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } if (targetFlags & 16777216 /* TypeFlags.Conditional */) { @@ -65760,7 +66661,6 @@ var ts; result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65771,7 +66671,6 @@ var ts; var distributiveConstraint = hasNonCircularBaseConstraint(source) ? getConstraintOfDistributiveConditionalType(source) : undefined; if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65781,7 +66680,6 @@ var ts; var defaultConstraint = getDefaultConstraintOfConditionalType(source); if (defaultConstraint) { if (result = isRelatedTo(defaultConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65794,7 +66692,6 @@ var ts; if (isGenericMappedType(target)) { if (isGenericMappedType(source)) { if (result = mappedTypeRelatedTo(source, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65932,18 +66829,6 @@ var ts; } } } - function reportUnmeasurableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); - } - return p; - } - function reportUnreliableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); - } - return p; - } // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice // that S and T are contra-variant whereas X and Y are co-variant. @@ -65953,7 +66838,7 @@ var ts; if (modifiersRelated) { var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); - var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); + var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMapper : reportUnreliableMapper); if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* RecursionFlags.Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { @@ -66007,11 +66892,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_20 = 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_21 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -66027,7 +66912,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_8 = _loop_21(i); + var state_8 = _loop_22(i); switch (state_8) { case "continue-outer": continue outer; } @@ -66041,7 +66926,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_7 = _loop_20(combination); + var state_7 = _loop_21(combination); if (typeof state_7 === "object") return state_7.value; } @@ -66489,7 +67374,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, makeFunctionTypeMapper(reportUnreliableMarkers)); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, reportUnreliableMapper); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -66644,7 +67529,7 @@ var ts; return typeCouldHaveTopLevelSingletonTypes(constraint); } } - return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */); + return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */); } function getExactOptionalUnassignableProperties(source, target) { if (isTupleType(source) && isTupleType(target)) @@ -66748,7 +67633,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_22 = 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 */ : @@ -66784,12 +67669,12 @@ var ts; } variances.push(variance); }; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - _loop_22(tp); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var tp = typeParameters_2[_i]; + _loop_23(tp); } links.variances = variances; - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); } return links.variances; } @@ -67127,35 +68012,33 @@ var ts; var commonBaseType; for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { var t = types_13[_i]; - var baseType = getBaseTypeOfLiteralType(t); - if (!commonBaseType) { - commonBaseType = baseType; - } - if (baseType === t || baseType !== commonBaseType) { - return false; + if (!(t.flags & 131072 /* TypeFlags.Never */)) { + var baseType = getBaseTypeOfLiteralType(t); + commonBaseType !== null && commonBaseType !== void 0 ? commonBaseType : (commonBaseType = baseType); + if (baseType === t || baseType !== commonBaseType) { + return false; + } } } return true; } - // When the candidate types are all literal types with the same base type, return a union - // of those literal types. Otherwise, return the leftmost type for which no type to the - // right is a supertype. - function getSupertypeOrUnion(types) { - if (types.length === 1) { - return types[0]; - } - return literalTypesWithSameBaseType(types) ? - getUnionType(types) : - ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + function getCombinedTypeFlags(types) { + return ts.reduceLeft(types, function (flags, t) { return flags | (t.flags & 1048576 /* TypeFlags.Union */ ? getCombinedTypeFlags(t.types) : t.flags); }, 0); } function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); + if (types.length === 1) { + return types[0]; } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* TypeFlags.Nullable */); }); - return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* TypeFlags.Nullable */) : - getUnionType(types, 2 /* UnionReduction.Subtype */); + // Remove nullable types from each of the candidates. + var primaryTypes = strictNullChecks ? ts.sameMap(types, function (t) { return filterType(t, function (u) { return !(u.flags & 98304 /* TypeFlags.Nullable */); }); }) : types; + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + var superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? + getUnionType(primaryTypes) : + ts.reduceLeft(primaryTypes, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + // Add any nullable types that occurred in the candidates back to the result. + return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & 98304 /* TypeFlags.Nullable */); } // Return the leftmost type for which no type to the right is a subtype. function getCommonSubtype(types) { @@ -67259,9 +68142,14 @@ var ts; type.flags & 256 /* TypeFlags.NumberLiteral */ ? numberType : type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? bigintType : type.flags & 512 /* TypeFlags.BooleanLiteral */ ? booleanType : - type.flags & 1048576 /* TypeFlags.Union */ ? mapType(type, getBaseTypeOfLiteralType) : + type.flags & 1048576 /* TypeFlags.Union */ ? getBaseTypeOfLiteralTypeUnion(type) : type; } + function getBaseTypeOfLiteralTypeUnion(type) { + var _a; + var key = "B".concat(getTypeId(type)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); + } function getWidenedLiteralType(type) { return type.flags & 1024 /* TypeFlags.EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : type.flags & 128 /* TypeFlags.StringLiteral */ && isFreshLiteralType(type) ? stringType : @@ -67342,29 +68230,8 @@ var ts; var value = _a.value; return value.base10Value === "0"; } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - result |= getFalsyFlags(t); - } - return result; - } - // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null - // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns - // no flags for all other types (including non-falsy literal types). - function getFalsyFlags(type) { - return type.flags & 1048576 /* TypeFlags.Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? type.value === "" ? 128 /* TypeFlags.StringLiteral */ : 0 : - type.flags & 256 /* TypeFlags.NumberLiteral */ ? type.value === 0 ? 256 /* TypeFlags.NumberLiteral */ : 0 : - type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* TypeFlags.BigIntLiteral */ : 0 : - type.flags & 512 /* TypeFlags.BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* TypeFlags.BooleanLiteral */ : 0 : - type.flags & 117724 /* TypeFlags.PossiblyFalsy */; - } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 117632 /* TypeFlags.DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* TypeFlags.DefinitelyFalsy */); }) : - type; + return filterType(type, function (t) { return !!(getTypeFacts(t) & 4194304 /* TypeFacts.Truthy */); }); } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); @@ -67399,20 +68266,15 @@ var ts; return type.flags & 32768 /* TypeFlags.Undefined */ ? type : getUnionType([type, isProperty ? missingType : undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { - // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates - // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' - // that isn't eliminated by a NonNullable instantiation. - var reducedType = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* SymbolFlags.TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? - getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : - reducedType; + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : + getIntersectionType([type, emptyObjectType]); } function getNonNullableType(type) { - return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + return strictNullChecks ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; @@ -67466,12 +68328,13 @@ var ts; * with no call or construct signatures. */ function isObjectTypeWithInferableIndex(type) { + var objectFlags = ts.getObjectFlags(type); return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* SymbolFlags.ObjectLiteral */ | 2048 /* SymbolFlags.TypeLiteral */ | 384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */)) !== 0 && !(type.symbol.flags & 32 /* SymbolFlags.Class */) - && !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & 4194304 /* ObjectFlags.ObjectRestType */) || !!(objectFlags & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* CheckFlags.Readonly */); @@ -67804,27 +68667,29 @@ var ts; signature: signature, flags: flags, compareTypes: compareTypes, - mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }), - nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }), + mapper: reportUnmeasurableMapper, + nonFixingMapper: reportUnmeasurableMapper, }; + context.mapper = makeFixingMapperForContext(context); + context.nonFixingMapper = makeNonFixingMapperForContext(context); return context; } - function mapToInferredType(context, t, fix) { - var inferences = context.inferences; - for (var i = 0; i < inferences.length; i++) { - var inference = inferences[i]; - if (t === inference.typeParameter) { - if (fix && !inference.isFixed) { - // Before we commit to a particular inference (and thus lock out any further inferences), - // we infer from any intra-expression inference sites we have collected. - inferFromIntraExpressionSites(context); - clearCachedInferences(inferences); - inference.isFixed = true; - } - return getInferredType(context, i); + function makeFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (inference, i) { return function () { + if (!inference.isFixed) { + // Before we commit to a particular inference (and thus lock out any further inferences), + // we infer from any intra-expression inference sites we have collected. + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; } - } - return t; + return getInferredType(context, i); + }; })); + } + function makeNonFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (_, i) { return function () { + return getInferredType(context, i); + }; })); } function clearCachedInferences(inferences) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { @@ -68093,13 +68958,40 @@ var ts; return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen); } - function isValidBigIntString(s) { + /** + * Tests whether the provided string can be parsed as a number. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting number matches the input when converted back to a string. + */ + function isValidNumberString(s, roundTripOnly) { + if (s === "") + return false; + var n = +s; + return isFinite(n) && (!roundTripOnly || "" + n === s); + } + /** + * @param text a valid bigint string excluding a trailing `n`, but including a possible prefix `-`. Use `isValidBigIntString(text, roundTripOnly)` before calling this function. + */ + function parseBigIntLiteralType(text) { + var negative = text.startsWith("-"); + var base10Value = ts.parsePseudoBigInt("".concat(negative ? text.slice(1) : text, "n")); + return getBigIntLiteralType({ negative: negative, base10Value: base10Value }); + } + /** + * Tests whether the provided string can be parsed as a bigint. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting bigint matches the input when converted back to a string. + */ + function isValidBigIntString(s, roundTripOnly) { + if (s === "") + return false; var scanner = ts.createScanner(99 /* ScriptTarget.ESNext */, /*skipTrivia*/ false); var success = true; scanner.setOnError(function () { return success = false; }); scanner.setText(s + "n"); var result = scanner.scan(); - if (result === 40 /* SyntaxKind.MinusToken */) { + var negative = result === 40 /* SyntaxKind.MinusToken */; + if (negative) { result = scanner.scan(); } var flags = scanner.getTokenFlags(); @@ -68108,7 +69000,33 @@ var ts; // * a bigint can be scanned, and that when it is scanned, it is // * the full length of the input string (so the scanner is one character beyond the augmented input length) // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) - return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */); + return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */) + && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); + } + function isMemberOfStringMapping(source, target) { + if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + return true; + } + if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { + return isTypeAssignableTo(source, target); + } + if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + // We need to see whether applying the same mappings of the target + // onto the source would produce an identical type *and* that + // it's compatible with the inner-most non-string-mapped type. + // + // The intuition here is that if same mappings don't affect the source at all, + // and the source is compatible with the unmapped target, then they must + // still reside in the same domain. + var mappingStack = []; + while (target.flags & 268435456 /* TypeFlags.StringMapping */) { + mappingStack.unshift(target.symbol); + target = target.type; + } + var mappedSource = ts.reduceLeft(mappingStack, function (memo, value) { return getStringMappingType(value, memo); }, source); + return mappedSource === source && isMemberOfStringMapping(source, target); + } + return false; } function isValidTypeForTemplateLiteralPlaceholder(source, target) { if (source === target || target.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */)) { @@ -68116,9 +69034,10 @@ var ts; } if (source.flags & 128 /* TypeFlags.StringLiteral */) { var value = source.value; - return !!(target.flags & 8 /* TypeFlags.Number */ && value !== "" && isFinite(+value) || - target.flags & 64 /* TypeFlags.BigInt */ && value !== "" && isValidBigIntString(value) || - target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName); + return !!(target.flags & 8 /* TypeFlags.Number */ && isValidNumberString(value, /*roundTripOnly*/ false) || + target.flags & 64 /* TypeFlags.BigInt */ && isValidBigIntString(value, /*roundTripOnly*/ false) || + target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName || + target.flags & 268435456 /* TypeFlags.StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target)); } if (source.flags & 134217728 /* TypeFlags.TemplateLiteral */) { var texts = source.texts; @@ -68241,10 +69160,13 @@ var ts; propagationType = savePropagationType; return; } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - // Source and target are types originating in the same generic type alias declaration. - // Simply infer from source type arguments to target type arguments. - inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + if (source.aliasSymbol && source.aliasSymbol === target.aliasSymbol) { + if (source.aliasTypeArguments) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + } + // And if there weren't any type arguments, there's no reason to run inference as the types must be the same. return; } if (source === target && source.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { @@ -68300,18 +69222,26 @@ var ts; target = getActualTypeVariable(target); } if (target.flags & 8650752 /* TypeFlags.TypeVariable */) { - // If target is a type parameter, make an inference, unless the source type contains - // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). - // Because the anyFunctionType is internal, it should not be exposed to the user by adding - // it as an inference candidate. Hopefully, a better candidate will come along that does - // not contain anyFunctionType when we come back to this argument for its second round - // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard - // when constructing types from type parameters that had no inference candidates). - if (source === nonInferrableAnyType || source === silentNeverType || (priority & 128 /* InferencePriority.ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + // Skip inference if the source is "blocked", which is used by the language service to + // prevent inference on nodes currently being edited. + if (isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); if (inference) { + // If target is a type parameter, make an inference, unless the source type contains + // a "non-inferrable" type. Types with this flag set are markers used to prevent inference. + // + // For example: + // - anyFunctionType is a wildcard type that's used to avoid contextually typing functions; + // it's internal, so should not be exposed to the user by adding it as a candidate. + // - autoType (and autoArrayType) is a special "any" used in control flow; like anyFunctionType, + // it's internal and should not be observable. + // - silentNeverType is returned by getInferredType when instantiating a generic function for + // inference (and a type variable has no mapping). + // + // This flag is infectious; if we produce Box (where never is silentNeverType), Box is + // also non-inferrable. if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) { return; } @@ -68368,15 +69298,11 @@ var ts; inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target)); } else if (source.flags & 4194304 /* TypeFlags.Index */ && target.flags & 4194304 /* TypeFlags.Index */) { - contravariant = !contravariant; - inferFromTypes(source.type, target.type); - contravariant = !contravariant; + inferFromContravariantTypes(source.type, target.type); } else if ((isLiteralType(source) || source.flags & 4 /* TypeFlags.String */) && target.flags & 4194304 /* TypeFlags.Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - contravariant = !contravariant; - inferWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); - contravariant = !contravariant; + inferFromContravariantTypesWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); } else if (source.flags & 8388608 /* TypeFlags.IndexedAccess */ && target.flags & 8388608 /* TypeFlags.IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -68389,10 +69315,7 @@ var ts; } else if (source.flags & 33554432 /* TypeFlags.Substitution */) { inferFromTypes(source.baseType, target); - var oldPriority = priority; - priority |= 4 /* InferencePriority.SubstituteSource */; - inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority - priority = oldPriority; + inferWithPriority(source.substitute, target, 4 /* InferencePriority.SubstituteSource */); // Make substitute inference at a lower priority } else if (target.flags & 16777216 /* TypeFlags.Conditional */) { invokeOnce(source, target, inferToConditionalType); @@ -68442,6 +69365,18 @@ var ts; inferFromTypes(source, target); priority = savePriority; } + function inferFromContravariantTypesWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromContravariantTypes(source, target); + priority = savePriority; + } + function inferToMultipleTypesWithPriority(source, targets, targetFlags, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferToMultipleTypes(source, targets, targetFlags); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -68506,10 +69441,13 @@ var ts; } } function inferFromContravariantTypes(source, target) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + function inferFromContravariantTypesIfStrictFunctionTypes(source, target) { if (strictFunctionTypes || priority & 1024 /* InferencePriority.AlwaysStrict */) { - contravariant = !contravariant; - inferFromTypes(source, target); - contravariant = !contravariant; + inferFromContravariantTypes(source, target); } else { inferFromTypes(source, target); @@ -68528,8 +69466,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var type = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* TypeFlags.Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -68673,11 +69611,8 @@ var ts; inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else { - var savePriority = priority; - priority |= contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; - inferToMultipleTypes(source, targetTypes, target.flags); - priority = savePriority; + inferToMultipleTypesWithPriority(source, targetTypes, target.flags, contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0); } } function inferToTemplateLiteralType(source, target) { @@ -68690,8 +69625,57 @@ 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_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 + // allowed template literal placeholder types, infer from a literal type corresponding to the constraint. + if (source_1.flags & 128 /* TypeFlags.StringLiteral */ && target_3.flags & 8650752 /* TypeFlags.TypeVariable */) { + var inferenceContext = getInferenceInfoForType(target_3); + var constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : undefined; + if (constraint && !isTypeAny(constraint)) { + var constraintTypes = constraint.flags & 1048576 /* TypeFlags.Union */ ? constraint.types : [constraint]; + var allTypeFlags_1 = ts.reduceLeft(constraintTypes, function (flags, t) { return flags | t.flags; }, 0); + // If the constraint contains `string`, we don't need to look for a more preferred type + if (!(allTypeFlags_1 & 4 /* TypeFlags.String */)) { + var str_1 = source_1.value; + // If the type contains `number` or a number literal and the string isn't a valid number, exclude numbers + if (allTypeFlags_1 & 296 /* TypeFlags.NumberLike */ && !isValidNumberString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~296 /* TypeFlags.NumberLike */; + } + // If the type contains `bigint` or a bigint literal and the string isn't a valid bigint, exclude bigints + if (allTypeFlags_1 & 2112 /* TypeFlags.BigIntLike */ && !isValidBigIntString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~2112 /* TypeFlags.BigIntLike */; + } + // for each type in the constraint, find the highest priority matching type + var matchingType = ts.reduceLeft(constraintTypes, function (left, right) { + return !(right.flags & allTypeFlags_1) ? left : + left.flags & 4 /* TypeFlags.String */ ? left : right.flags & 4 /* TypeFlags.String */ ? source_1 : + left.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? left : right.flags & 134217728 /* TypeFlags.TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source_1, right) ? source_1 : + left.flags & 268435456 /* TypeFlags.StringMapping */ ? left : right.flags & 268435456 /* TypeFlags.StringMapping */ && str_1 === applyStringMapping(right.symbol, str_1) ? source_1 : + left.flags & 128 /* TypeFlags.StringLiteral */ ? left : right.flags & 128 /* TypeFlags.StringLiteral */ && right.value === str_1 ? right : + left.flags & 8 /* TypeFlags.Number */ ? left : right.flags & 8 /* TypeFlags.Number */ ? getNumberLiteralType(+str_1) : + left.flags & 32 /* TypeFlags.Enum */ ? left : right.flags & 32 /* TypeFlags.Enum */ ? getNumberLiteralType(+str_1) : + left.flags & 256 /* TypeFlags.NumberLiteral */ ? left : right.flags & 256 /* TypeFlags.NumberLiteral */ && right.value === +str_1 ? right : + left.flags & 64 /* TypeFlags.BigInt */ ? left : right.flags & 64 /* TypeFlags.BigInt */ ? parseBigIntLiteralType(str_1) : + left.flags & 2048 /* TypeFlags.BigIntLiteral */ ? left : right.flags & 2048 /* TypeFlags.BigIntLiteral */ && ts.pseudoBigIntToString(right.value) === str_1 ? right : + left.flags & 16 /* TypeFlags.Boolean */ ? left : right.flags & 16 /* TypeFlags.Boolean */ ? str_1 === "true" ? trueType : str_1 === "false" ? falseType : booleanType : + left.flags & 512 /* TypeFlags.BooleanLiteral */ ? left : right.flags & 512 /* TypeFlags.BooleanLiteral */ && right.intrinsicName === str_1 ? right : + left.flags & 32768 /* TypeFlags.Undefined */ ? left : right.flags & 32768 /* TypeFlags.Undefined */ && right.intrinsicName === str_1 ? right : + left.flags & 65536 /* TypeFlags.Null */ ? left : right.flags & 65536 /* TypeFlags.Null */ && right.intrinsicName === str_1 ? right : + left; + }, neverType); + if (!(matchingType.flags & 131072 /* TypeFlags.Never */)) { + inferFromTypes(matchingType, target_3); + return "continue"; + } + } + } + } + inferFromTypes(source_1, target_3); + }; for (var i = 0; i < types.length; i++) { - inferFromTypes(matches ? matches[i] : neverType, types[i]); + _loop_24(i); } } } @@ -68805,20 +69789,17 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } - function inferFromSignature(source, target, skipParameters) { - if (!skipParameters) { - var saveBivariant = bivariant; - var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; - // Once we descend into a bivariant signature we remain bivariant for all nested inferences - bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; - applyToParameterTypes(source, target, inferFromContravariantTypes); - bivariant = saveBivariant; - } + function inferFromSignature(source, target) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; + applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); + bivariant = saveBivariant; applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { @@ -69065,6 +70046,15 @@ var ts; var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); return key && key + "." + propName; } + break; + case 201 /* SyntaxKind.ObjectBindingPattern */: + case 202 /* SyntaxKind.ArrayBindingPattern */: + case 256 /* SyntaxKind.FunctionDeclaration */: + case 213 /* SyntaxKind.FunctionExpression */: + case 214 /* SyntaxKind.ArrowFunction */: + case 169 /* SyntaxKind.MethodDeclaration */: + // Handle pseudo-references originating in getNarrowedTypeOfSymbol. + return "".concat(getNodeId(node), "#").concat(getTypeId(declaredType)); } return undefined; } @@ -69209,7 +70199,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_23 = 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) { @@ -69233,9 +70223,9 @@ var ts; } } }; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - var state_9 = _loop_23(type); + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var type = types_15[_i]; + var state_9 = _loop_25(type); if (typeof state_9 === "object") return state_9.value; } @@ -69324,23 +70314,25 @@ var ts; // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 131072 /* TypeFlags.Never */) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType)) { - reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types - } - // Our crude heuristic produces an invalid result in some cases: see GH#26130. - // For now, when that happens, we give up and don't narrow at all. (This also - // means we'll never narrow for erroneous assignments where the assigned type - // is not assignable to the declared type.) - if (isTypeAssignableTo(assignedType, reducedType)) { - return reducedType; - } + var _a; + if (declaredType === assignedType) { + return declaredType; } - return declaredType; + if (assignedType.flags & 131072 /* TypeFlags.Never */) { + return assignedType; + } + var key = "A".concat(getTypeId(declaredType), ",").concat(getTypeId(assignedType)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); + } + function getAssignmentReducedTypeWorker(declaredType, assignedType) { + var filteredType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + // Ensure that we narrow to fresh types if the assignment is a fresh boolean literal type. + var reducedType = assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType; + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType; } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype @@ -69349,14 +70341,16 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type, ignoreObjects) { - if (ignoreObjects === void 0) { ignoreObjects = false; } + function getTypeFacts(type) { + if (type.flags & (2097152 /* TypeFlags.Intersection */ | 465829888 /* TypeFlags.Instantiable */)) { + type = getBaseConstraintOfType(type) || unknownType; + } var flags = type.flags; - if (flags & 4 /* TypeFlags.String */) { + if (flags & (4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */)) { return strictNullChecks ? 16317953 /* TypeFacts.StringStrictFacts */ : 16776705 /* TypeFacts.StringFacts */; } - if (flags & 128 /* TypeFlags.StringLiteral */) { - var isEmpty = type.value === ""; + if (flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */)) { + var isEmpty = flags & 128 /* TypeFlags.StringLiteral */ && type.value === ""; return strictNullChecks ? isEmpty ? 12123649 /* TypeFacts.EmptyStringStrictFacts */ : 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* TypeFacts.EmptyStringFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; @@ -69388,20 +70382,20 @@ var ts; (type === falseType || type === regularFalseType) ? 12580616 /* TypeFacts.FalseFacts */ : 16774920 /* TypeFacts.TrueFacts */; } if (flags & 524288 /* TypeFlags.Object */) { - if (ignoreObjects) { - return 16768959 /* TypeFacts.AndFactsMask */; // This is the identity element for computing type facts of intersection. - } return ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && isEmptyObjectType(type) ? - strictNullChecks ? 16318463 /* TypeFacts.EmptyObjectStrictFacts */ : 16777215 /* TypeFacts.EmptyObjectFacts */ : + strictNullChecks ? 83427327 /* TypeFacts.EmptyObjectStrictFacts */ : 83886079 /* TypeFacts.EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* TypeFacts.FunctionStrictFacts */ : 16728000 /* TypeFacts.FunctionFacts */ : strictNullChecks ? 7888800 /* TypeFacts.ObjectStrictFacts */ : 16736160 /* TypeFacts.ObjectFacts */; } - if (flags & (16384 /* TypeFlags.Void */ | 32768 /* TypeFlags.Undefined */)) { - return 9830144 /* TypeFacts.UndefinedFacts */; + if (flags & 16384 /* TypeFlags.Void */) { + return 9830144 /* TypeFacts.VoidFacts */; + } + if (flags & 32768 /* TypeFlags.Undefined */) { + return 26607360 /* TypeFacts.UndefinedFacts */; } if (flags & 65536 /* TypeFlags.Null */) { - return 9363232 /* TypeFacts.NullFacts */; + return 42917664 /* TypeFacts.NullFacts */; } if (flags & 12288 /* TypeFlags.ESSymbolLike */) { return strictNullChecks ? 7925520 /* TypeFacts.SymbolStrictFacts */ : 16772880 /* TypeFacts.SymbolFacts */; @@ -69412,37 +70406,56 @@ var ts; if (flags & 131072 /* TypeFlags.Never */) { return 0 /* TypeFacts.None */; } - if (flags & 465829888 /* TypeFlags.Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : - strictNullChecks ? 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; - } if (flags & 1048576 /* TypeFlags.Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* TypeFacts.None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* TypeFacts.None */); } if (flags & 2097152 /* TypeFlags.Intersection */) { - // When an intersection contains a primitive type we ignore object type constituents as they are - // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. - ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */)); - return getIntersectionTypeFacts(type, ignoreObjects); + return getIntersectionTypeFacts(type); } - return 16777215 /* TypeFacts.All */; + return 83886079 /* TypeFacts.UnknownFacts */; } - function getIntersectionTypeFacts(type, ignoreObjects) { + function getIntersectionTypeFacts(type) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + var ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */); // When computing the type facts of an intersection type, certain type facts are computed as `and` // and others are computed as `or`. var oredFacts = 0 /* TypeFacts.None */; - var andedFacts = 16777215 /* TypeFacts.All */; + var andedFacts = 134217727 /* TypeFacts.All */; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - var f = getTypeFacts(t, ignoreObjects); - oredFacts |= f; - andedFacts &= f; + if (!(ignoreObjects && t.flags & 524288 /* TypeFlags.Object */)) { + var f = getTypeFacts(t); + oredFacts |= f; + andedFacts &= f; + } } - return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 16768959 /* TypeFacts.AndFactsMask */; + return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 134209471 /* TypeFacts.AndFactsMask */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } + // This function is similar to getTypeWithFacts, except that in strictNullChecks mode it replaces type + // unknown with the union {} | null | undefined (and reduces that accordingly), and it intersects remaining + // instantiable types with {}, {} | null, or {} | undefined in order to remove null and/or undefined. + function getAdjustedTypeWithFacts(type, facts) { + var reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 /* TypeFlags.Unknown */ ? unknownUnionType : type, facts)); + if (strictNullChecks) { + switch (facts) { + case 524288 /* TypeFacts.NEUndefined */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ ? getIntersectionType([t, getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ && !maybeTypeOfKind(reduced, 65536 /* TypeFlags.Null */) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t; }); + case 1048576 /* TypeFacts.NENull */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ ? getIntersectionType([t, getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ && !maybeTypeOfKind(reduced, 32768 /* TypeFlags.Undefined */) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t; }); + case 2097152 /* TypeFacts.NEUndefinedOrNull */: + case 4194304 /* TypeFacts.Truthy */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 262144 /* TypeFacts.EQUndefinedOrNull */ ? getGlobalNonNullableTypeInstantiation(t) : t; }); + } + } + return reduced; + } + function recombineUnknownType(type) { + return type === unknownUnionType ? unknownType : type; + } function getTypeWithDefault(type, defaultExpression) { return defaultExpression ? getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : @@ -69597,19 +70610,17 @@ var ts; } return links.switchTypes; } - function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) { + // Get the type names from all cases in a switch on `typeof`. The default clause and/or duplicate type names are + // represented as undefined. Return undefined if one or more case clause expressions are not string literals. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + if (ts.some(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 289 /* SyntaxKind.CaseClause */ && !ts.isStringLiteralLike(clause.expression); })) { + return undefined; + } var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 289 /* SyntaxKind.CaseClause */) { - if (ts.isStringLiteralLike(clause.expression)) { - witnesses.push(clause.expression.text); - continue; - } - return ts.emptyArray; - } - if (retainDefault) - witnesses.push(/*explicitDefaultStatement*/ undefined); + var text = clause.kind === 289 /* SyntaxKind.CaseClause */ ? clause.expression.text : undefined; + witnesses.push(text && !ts.contains(witnesses, text) ? text : undefined); } return witnesses; } @@ -69691,8 +70702,8 @@ var ts; var types = origin && origin.flags & 1048576 /* TypeFlags.Union */ ? origin.types : type.types; var mappedTypes; var changed = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; var mapped = t.flags & 1048576 /* TypeFlags.Union */ ? mapType(t, mapper, noReductions) : mapper(t); changed || (changed = t !== mapped); if (mapped) { @@ -69778,8 +70789,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (!(t.flags & 131072 /* TypeFlags.Never */)) { if (!(ts.getObjectFlags(t) & 256 /* ObjectFlags.EvolvingArray */)) { return false; @@ -70240,7 +71251,7 @@ var ts; } // for (const _ in ref) acts as a nonnull on ref if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 243 /* SyntaxKind.ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { - return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); } // Assignment doesn't affect reference return undefined; @@ -70500,7 +71511,7 @@ var ts; if (isEvolvingArrayTypeList(types)) { return getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))); } - var result = getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + var result = recombineUnknownType(getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction)); if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* TypeFlags.Union */ && ts.arraysEqual(result.types, declaredType.types)) { return declaredType; } @@ -70602,11 +71613,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return type.flags & 2 /* TypeFlags.Unknown */ && assumeTrue ? nonNullUnknownType : - getTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); + return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -70728,7 +71738,7 @@ var ts; var targetType = ts.hasStaticModifier(ts.Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows: @@ -70746,7 +71756,7 @@ var ts; // Note that we include any and unknown in the exclusion test because their domain includes null and undefined. var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) || equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* TypeFlags.AnyOrUnknown */ | nullableFlags)); }); - return removeNullable ? getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; + return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* TypeFlags.Any */) { @@ -70756,9 +71766,6 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (assumeTrue && (type.flags & 2 /* TypeFlags.Unknown */) && (operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 35 /* SyntaxKind.ExclamationEqualsToken */) && (valueType.flags & 65536 /* TypeFlags.Null */)) { - return getUnionType([nullType, undefinedType]); - } if ((type.flags & 2 /* TypeFlags.Unknown */) && assumeTrue && (operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */ || operator === 37 /* SyntaxKind.ExclamationEqualsEqualsToken */)) { if (valueType.flags & (131068 /* TypeFlags.Primitive */ | 67108864 /* TypeFlags.NonPrimitive */)) { return valueType; @@ -70778,7 +71785,7 @@ var ts; valueType.flags & 65536 /* TypeFlags.Null */ ? assumeTrue ? 131072 /* TypeFacts.EQNull */ : 1048576 /* TypeFacts.NENull */ : assumeTrue ? 65536 /* TypeFacts.EQUndefined */ : 524288 /* TypeFacts.NEUndefined */; - return type.flags & 2 /* TypeFlags.Unknown */ && facts & (1048576 /* TypeFacts.NENull */ | 2097152 /* TypeFacts.NEUndefinedOrNull */) ? nonNullUnknownType : getTypeWithFacts(type, facts); + return getAdjustedTypeWithFacts(type, facts); } if (assumeTrue) { var filterFn = operator === 34 /* SyntaxKind.EqualsEqualsToken */ ? @@ -70799,24 +71806,13 @@ var ts; var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } - if (type.flags & 1 /* TypeFlags.Any */ && literal.text === "function") { - return type; - } - if (assumeTrue && type.flags & 2 /* TypeFlags.Unknown */ && literal.text === "object") { - // The non-null unknown type is used to track whether a previous narrowing operation has removed the null type - // from the unknown type. For example, the expression `x && typeof x === 'object'` first narrows x to the non-null - // unknown type, and then narrows that to the non-primitive type. - return type === nonNullUnknownType ? nonPrimitiveType : getUnionType([nonPrimitiveType, nullType]); - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 128 /* TypeFacts.TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */; - var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text); - return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts); + return assumeTrue ? + narrowTypeByTypeName(type, literal.text) : + getTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */); } function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); @@ -70863,97 +71859,52 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* TypeFlags.Never */ ? defaultType : getUnionType([caseType, defaultType]); } - function getImpliedTypeFromTypeofGuard(type, text) { - switch (text) { - case "function": - return type.flags & 1 /* TypeFlags.Any */ ? type : globalFunctionType; - case "object": - return type.flags & 2 /* TypeFlags.Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; - default: - return typeofTypesByName.get(text); - } - } - // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are - // super-types of the implied guard will be retained in the final type: this is because type-facts only - // filter. Instead, we would like to replace those union constituents with the more precise type implied by - // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not - // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to - // filtering by type-facts. - function narrowUnionMemberByTypeof(candidate) { - return function (type) { - if (isTypeSubtypeOf(type, candidate)) { - return type; - } - if (isTypeSubtypeOf(candidate, type)) { - return candidate; - } - if (type.flags & 465829888 /* TypeFlags.Instantiable */) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(candidate, constraint)) { - return getIntersectionType([type, candidate]); - } - } - return type; - }; + function narrowTypeByTypeName(type, typeName) { + switch (typeName) { + case "string": return narrowTypeByTypeFacts(type, stringType, 1 /* TypeFacts.TypeofEQString */); + case "number": return narrowTypeByTypeFacts(type, numberType, 2 /* TypeFacts.TypeofEQNumber */); + case "bigint": return narrowTypeByTypeFacts(type, bigintType, 4 /* TypeFacts.TypeofEQBigInt */); + case "boolean": return narrowTypeByTypeFacts(type, booleanType, 8 /* TypeFacts.TypeofEQBoolean */); + case "symbol": return narrowTypeByTypeFacts(type, esSymbolType, 16 /* TypeFacts.TypeofEQSymbol */); + case "object": return type.flags & 1 /* TypeFlags.Any */ ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32 /* TypeFacts.TypeofEQObject */), narrowTypeByTypeFacts(type, nullType, 131072 /* TypeFacts.EQNull */)]); + case "function": return type.flags & 1 /* TypeFlags.Any */ ? type : narrowTypeByTypeFacts(type, globalFunctionType, 64 /* TypeFacts.TypeofEQFunction */); + case "undefined": return narrowTypeByTypeFacts(type, undefinedType, 65536 /* TypeFacts.EQUndefined */); + } + return narrowTypeByTypeFacts(type, nonPrimitiveType, 128 /* TypeFacts.TypeofEQHostObject */); + } + function narrowTypeByTypeFacts(type, impliedType, facts) { + return mapType(type, function (t) { + // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate + // the constituent based on its type facts. We use the strict subtype relation because it treats `object` + // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, + // but are classified as "function" according to `typeof`. + return isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? getTypeFacts(t) & facts ? t : neverType : + // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied + // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. + isTypeSubtypeOf(impliedType, t) ? impliedType : + // Neither the constituent nor the implied type is a subtype of the other, however their domains may still + // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate + // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. + getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : + neverType; + }); } function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { - var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true); - if (!switchWitnesses.length) { + var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!witnesses) { return type; } - // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause - var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); - var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); - var clauseWitnesses; - var switchFacts; - if (defaultCaseLocation > -1) { - // We no longer need the undefined denoting an explicit default case. Remove the undefined and - // fix-up clauseStart and clauseEnd. This means that we don't have to worry about undefined in the - // witness array. - var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); - // The adjusted clause start and end after removing the `default` statement. - var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; - var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; - clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); - switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); - } - else { - clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); - switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); - } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause. + var defaultIndex = ts.findIndex(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 290 /* SyntaxKind.DefaultClause */; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultIndex >= clauseStart && defaultIndex < clauseEnd); if (hasDefaultClause) { - return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + // In the default clause we filter constituents down to those that are not-equal to all handled cases. + var notEqualFacts_1 = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); + return filterType(type, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }); } - /* - The implied type is the raw type suggested by a - value being caught in this clause. - - When the clause contains a default case we ignore - the implied type and try to narrow using any facts - we can learn: see `switchFacts`. - - Example: - switch (typeof x) { - case 'number': - case 'string': break; - default: break; - case 'number': - case 'boolean': break - } - - In the first clause (case `number` and `string`) the - implied type is number | string. - - In the default clause we de not compute an implied type. - - In the third clause (case `number` and `boolean`) - the naive implied type is number | boolean, however - we use the type facts to narrow the implied type to - boolean. We know that number cannot be selected - because it is caught in the first clause. - */ - var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts); - return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts); + // In the non-default cause we create a union of the type narrowed by each of the listed cases. + var clauseWitnesses = witnesses.slice(clauseStart, clauseEnd); + return getUnionType(ts.map(clauseWitnesses, function (text) { return text ? narrowTypeByTypeName(type, text) : neverType; })); } function isMatchingConstructorReference(expr) { return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || @@ -71004,7 +71955,7 @@ var ts; var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } @@ -71038,29 +71989,48 @@ var ts; if (!nonConstructorTypeInUnion) return type; } - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { + function getNarrowedType(type, candidate, assumeTrue, checkDerived) { + var _a; + var key = type.flags & 1048576 /* TypeFlags.Union */ ? "N".concat(getTypeId(type), ",").concat(getTypeId(candidate), ",").concat((assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)) : undefined; + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); + } + function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) { + var isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf; if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - // If the current type is a union type, remove all constituents that couldn't be instances of - // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 1048576 /* TypeFlags.Union */) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 131072 /* TypeFlags.Never */)) { - return assignableType; - } + if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { + return candidate; } - // If the candidate type is a subtype of the target type, narrow to the candidate type. - // Otherwise, if the target type is assignable to the candidate type, keep the target type. - // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate - // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the - // two types. - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); + // We first attempt to filter the current type, narrowing constituents as appropriate and removing + // constituents that are unrelated to the candidate. + var keyPropertyName = type.flags & 1048576 /* TypeFlags.Union */ ? getKeyPropertyName(type) : undefined; + var narrowedType = mapType(candidate, function (c) { + // If a discriminant property is available, use that to reduce the type. + var discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName); + var matching = discriminant && getConstituentTypeForKeyType(type, discriminant); + // For each constituent t in the current type, if t and and c are directly related, pick the most + // specific of the two. When t and c are related in both directions, we prefer c for type predicates + // because that is the asserted type, but t for `instanceof` because generics aren't reflected in + // prototype object types. + var directlyRelated = mapType(matching || type, checkDerived ? + function (t) { return isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType; } : + function (t) { return isTypeSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : neverType; }); + // If no constituents are directly related, create intersections for any generic constituents that + // are related by constraint. + return directlyRelated.flags & 131072 /* TypeFlags.Never */ ? + mapType(type, function (t) { return maybeTypeOfKind(t, 465829888 /* TypeFlags.Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType; }) : + directlyRelated; + }); + // If filtering produced a non-empty type, return that. Otherwise, pick the most specific of the two + // based on assignability, or as a last resort produce an intersection. + return !(narrowedType.flags & 131072 /* TypeFlags.Never */) ? narrowedType : + isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -71088,15 +72058,15 @@ var ts; var predicateArgument = getTypePredicateArgument(predicate, callExpression); if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + return getNarrowedType(type, predicate.type, assumeTrue, /*checkDerived*/ false); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && !(getTypeFacts(predicate.type) & 65536 /* TypeFacts.EQUndefined */)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(predicateArgument, type); if (access) { - return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); + return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, /*checkDerived*/ false); }); } } } @@ -71149,7 +72119,7 @@ var ts; } function narrowTypeByOptionality(type, expr, assumePresent) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -71235,8 +72205,8 @@ var ts; var annotationIncludesUndefined = strictNullChecks && declaration.kind === 164 /* SyntaxKind.Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 32768 /* TypeFlags.Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* TypeFlags.Undefined */); + getTypeFacts(declaredType) & 16777216 /* TypeFacts.IsUndefined */ && + !(getTypeFacts(checkExpression(declaration.initializer)) & 16777216 /* TypeFacts.IsUndefined */); popTypeResolution(); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* TypeFacts.NEUndefined */) : declaredType; } @@ -71257,7 +72227,9 @@ var ts; !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { - return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); + return type.flags & 2097152 /* TypeFlags.Intersection */ ? + ts.some(type.types, isGenericTypeWithUnionConstraint) : + !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); } function isGenericTypeWithoutNullableConstraint(type) { return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* TypeFlags.Nullable */)); @@ -71271,7 +72243,7 @@ var ts; !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 64 /* CheckMode.RestBindingElement */ ? getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) - : getContextualType(node)); + : getContextualType(node, /*contextFlags*/ undefined)); return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { @@ -71285,7 +72257,7 @@ var ts; var substituteConstraints = !(checkMode && checkMode & 2 /* CheckMode.Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); - return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* TypeFlags.Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (n) { @@ -71433,9 +72405,7 @@ var ts; getNodeLinks(container).flags |= 8192 /* NodeCheckFlags.CaptureArguments */; return getTypeOfSymbol(symbol); } - // We should only mark aliases as referenced if there isn't a local value declaration - // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that - if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + if (shouldMarkIdentifierAliasReferenced(node)) { markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); @@ -71562,13 +72532,32 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function shouldMarkIdentifierAliasReferenced(node) { + var _a; + var parent = node.parent; + if (parent) { + // A property access expression LHS? checkPropertyAccessExpression will handle that. + if (ts.isPropertyAccessExpression(parent) && parent.expression === node) { + return false; + } + // Next two check for an identifier inside a type only export. + if (ts.isExportSpecifier(parent) && parent.isTypeOnly) { + return false; + } + var greatGrandparent = (_a = parent.parent) === null || _a === void 0 ? void 0 : _a.parent; + if (greatGrandparent && ts.isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) { + return false; + } + } + return true; + } function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } @@ -71696,7 +72685,7 @@ var ts; } function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) { if (ts.isPropertyDeclaration(container) && ts.hasStaticModifier(container) && - container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.length(container.parent.decorators)) { + container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.hasDecorators(container.parent)) { error(thisExpression, ts.Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); } } @@ -72118,7 +73107,7 @@ var ts; // We have an object literal method. Check if the containing object literal has a contextual type // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in // any directly enclosing object literals. - var contextualType = getApparentTypeOfContextualType(containingLiteral); + var contextualType = getApparentTypeOfContextualType(containingLiteral, /*contextFlags*/ undefined); var literal = containingLiteral; var type = contextualType; while (type) { @@ -72130,7 +73119,7 @@ var ts; break; } literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); + type = getApparentTypeOfContextualType(literal, /*contextFlags*/ undefined); } // There was no contextual ThisType for the containing object literal, so the contextual type // for 'this' is the non-null form of the contextual type for the containing object literal or @@ -72187,7 +73176,7 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } - function getContextualTypeForVariableLikeDeclaration(declaration) { + function getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -72196,18 +73185,18 @@ var ts; case 164 /* SyntaxKind.Parameter */: return getContextuallyTypedParameterType(declaration); case 203 /* SyntaxKind.BindingElement */: - return getContextualTypeForBindingElement(declaration); + return getContextualTypeForBindingElement(declaration, contextFlags); case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isStatic(declaration)) { - return getContextualTypeForStaticPropertyDeclaration(declaration); + return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); } // By default, do nothing and return undefined - only the above cases have context implied by a parent } } - function getContextualTypeForBindingElement(declaration) { + function getContextualTypeForBindingElement(declaration, contextFlags) { var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - var parentType = getContextualTypeForVariableLikeDeclaration(parent) || + var parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== 203 /* SyntaxKind.BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 64 /* CheckMode.RestBindingElement */ : 0 /* CheckMode.Normal */); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; @@ -72223,8 +73212,8 @@ var ts; return getTypeOfPropertyOfType(parentType, text); } } - function getContextualTypeForStaticPropertyDeclaration(declaration) { - var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent); + function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) { + var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags); if (!parentType) return undefined; return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName); @@ -72240,29 +73229,32 @@ var ts; function getContextualTypeForInitializerExpression(node, contextFlags) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var result = getContextualTypeForVariableLikeDeclaration(declaration); + var result = getContextualTypeForVariableLikeDeclaration(declaration, contextFlags); if (result) { return result; } - if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable + if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name) && declaration.name.elements.length > 0) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } } return undefined; } - function getContextualTypeForReturnExpression(node) { + function getContextualTypeForReturnExpression(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { var functionFlags = ts.getFunctionFlags(func); if (functionFlags & 1 /* FunctionFlags.Generator */) { // Generator or AsyncGenerator function - var use = functionFlags & 2 /* FunctionFlags.Async */ ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; - var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined); - if (!iterationTypes) { + var isAsyncGenerator_1 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_1); }); + } + var iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + if (!iterationReturnType) { return undefined; } - contextualReturnType = iterationTypes.returnType; + contextualReturnType = iterationReturnType; // falls through to unwrap Promise for AsyncGenerators } if (functionFlags & 2 /* FunctionFlags.Async */) { // Async function or AsyncGenerator function @@ -72283,15 +73275,19 @@ var ts; } return undefined; } - function getContextualTypeForYieldOperand(node) { + function getContextualTypeForYieldOperand(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { + var isAsyncGenerator_2 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_2); }); + } return node.asteriskToken ? contextualReturnType - : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, isAsyncGenerator_2); } } return undefined; @@ -72311,14 +73307,14 @@ var ts; } function getContextualIterationType(kind, functionDecl) { var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* FunctionFlags.Async */); - var contextualReturnType = getContextualReturnType(functionDecl); + var contextualReturnType = getContextualReturnType(functionDecl, /*contextFlags*/ undefined); if (contextualReturnType) { return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || undefined; } return undefined; } - function getContextualReturnType(functionDecl) { + function getContextualReturnType(functionDecl, contextFlags) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed var returnType = getReturnTypeFromAnnotation(functionDecl); @@ -72333,7 +73329,7 @@ var ts; } var iife = ts.getImmediatelyInvokedFunctionExpression(functionDecl); if (iife) { - return getContextualType(iife); + return getContextualType(iife, contextFlags); } return undefined; } @@ -72407,6 +73403,14 @@ var ts; var lhsType = getTypeOfExpression(e.expression); return ts.isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText); } + if (ts.isElementAccessExpression(e)) { + var propType = checkExpressionCached(e.argumentExpression); + if (!isTypeUsableAsPropertyName(propType)) { + return undefined; + } + var lhsType = getTypeOfExpression(e.expression); + return getPropertyOfType(lhsType, getPropertyNameFromType(propType)); + } return undefined; function tryGetPrivateIdentifierPropertyOfType(type, id) { var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id); @@ -72428,7 +73432,7 @@ var ts; if (decl && (ts.isPropertyDeclaration(decl) || ts.isPropertySignature(decl))) { var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); return (overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper)) || - (decl.initializer && getTypeOfExpression(binaryExpression.left)); + (ts.isPropertyDeclaration(decl) ? decl.initializer && getTypeOfExpression(binaryExpression.left) : undefined); } if (kind === 0 /* AssignmentDeclarationKind.None */) { return getTypeOfExpression(binaryExpression.left); @@ -72561,7 +73565,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; - var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element, contextFlags); if (propertyAssignmentType) { return propertyAssignmentType; } @@ -72596,8 +73600,8 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined; } - function getContextualTypeForChildJsxExpression(node, child) { - var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + function getContextualTypeForChildJsxExpression(node, child, contextFlags) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); // JSX expression is in children of JSX Element, we will look for an "children" attribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { @@ -72615,27 +73619,27 @@ var ts; } }, /*noReductions*/ true)); } - function getContextualTypeForJsxExpression(node) { + function getContextualTypeForJsxExpression(node, contextFlags) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) - ? getContextualType(node) + ? getContextualType(node, contextFlags) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent, node) + ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) : undefined; } - function getContextualTypeForJsxAttribute(attribute) { + function getContextualTypeForJsxAttribute(attribute, contextFlags) { // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName if (ts.isJsxAttribute(attribute)) { - var attributesType = getApparentTypeOfContextualType(attribute.parent); + var attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return getContextualType(attribute.parent); + return getContextualType(attribute.parent, contextFlags); } } // Return true if the given expression is possibly a discriminant value. We limit the kinds of @@ -72688,22 +73692,20 @@ var ts; 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 && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { // 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. - if (contextFlags && contextFlags & 1 /* ContextFlags.Signature */) { - return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); - } + return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); + } + if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.returnMapper) { // For other purposes (e.g. determining whether to produce literal types) we only // incorporate inferences made from the return type in a function call. We remove // the 'boolean' type from the contextual type such that contextually typed boolean // literals actually end up widening to 'boolean' (see #48363). - if (inferenceContext.returnMapper) { - var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); - return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? - filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : - type; - } + var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); + return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? + filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : + type; } } return contextualType; @@ -72758,9 +73760,9 @@ var ts; return getContextualTypeForInitializerExpression(node, contextFlags); case 214 /* SyntaxKind.ArrowFunction */: case 247 /* SyntaxKind.ReturnStatement */: - return getContextualTypeForReturnExpression(node); + return getContextualTypeForReturnExpression(node, contextFlags); case 224 /* SyntaxKind.YieldExpression */: - return getContextualTypeForYieldOperand(parent); + return getContextualTypeForYieldOperand(parent, contextFlags); case 218 /* SyntaxKind.AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); case 208 /* SyntaxKind.CallExpression */: @@ -72798,17 +73800,17 @@ var ts; case 271 /* SyntaxKind.ExportAssignment */: return tryGetTypeFromEffectiveTypeNode(parent); case 288 /* SyntaxKind.JsxExpression */: - return getContextualTypeForJsxExpression(parent); + return getContextualTypeForJsxExpression(parent, contextFlags); case 285 /* SyntaxKind.JsxAttribute */: case 287 /* SyntaxKind.JsxSpreadAttribute */: - return getContextualTypeForJsxAttribute(parent); + return getContextualTypeForJsxAttribute(parent, contextFlags); case 280 /* SyntaxKind.JsxOpeningElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; function tryFindWhenConstTypeReference(node) { - return getContextualType(node); + return getContextualType(node, contextFlags); } } function getInferenceContext(node) { @@ -73068,8 +74070,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var current = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var current = types_18[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -73110,7 +74112,7 @@ var ts; var elementCount = elements.length; var elementTypes = []; var elementFlags = []; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var inDestructuringPattern = ts.isAssignmentTarget(node); var inConstContext = isConstContext(node); var hasOmittedExpression = false; @@ -73281,7 +74283,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 201 /* SyntaxKind.ObjectBindingPattern */ || contextualType.pattern.kind === 205 /* SyntaxKind.ObjectLiteralExpression */); var inConstContext = isConstContext(node); @@ -73620,7 +74622,7 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes, /*contextFlags*/ undefined); var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* SymbolFlags.Property */, jsxChildrenPropertyName); @@ -74231,19 +75233,19 @@ var ts; return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { - return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */); + return !!(getTypeFacts(type) & 50331648 /* TypeFacts.IsUndefinedOrNull */); } function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function reportObjectPossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportObjectPossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); } - function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); @@ -74253,9 +75255,9 @@ var ts; error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */; - if (kind) { - reportError(node, kind); + var facts = getTypeFacts(type); + if (facts & 50331648 /* TypeFacts.IsUndefinedOrNull */) { + reportError(node, facts); var t = getNonNullableType(type); return t.flags & (98304 /* TypeFlags.Nullable */ | 131072 /* TypeFlags.Never */) ? errorType : t; } @@ -74424,9 +75426,8 @@ var ts; markAliasReferenced(parentSymbol, node); } return isErrorType(apparentType) ? errorType : apparentType; - ; } - prop = getPropertyOfType(apparentType, right.escapedText); + prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ node.kind === 161 /* SyntaxKind.QualifiedName */); } // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. // `Foo` is also not referenced in `enum FooCopy { Bar = Foo.Bar }`, because the enum member value gets inlined @@ -74551,7 +75552,7 @@ var ts; assumeUninitialized = true; } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) { error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -74734,9 +75735,9 @@ var ts; function getSuggestedSymbolForNonexistentProperty(name, containingType) { var props = getPropertiesOfType(containingType); if (typeof name !== "string") { - var parent_2 = name.parent; - if (ts.isPropertyAccessExpression(parent_2)) { - props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + var parent_3 = name.parent; + if (ts.isPropertyAccessExpression(parent_3)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_3, containingType, prop); }); } name = ts.idText(name); } @@ -75238,29 +76239,43 @@ var ts; // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. if (node.kind !== 165 /* SyntaxKind.Decorator */) { - var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); + var skipBindingPatterns = ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }); + var contextualType = getContextualType(node, skipBindingPatterns ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); if (contextualType) { var inferenceTargetType = getReturnTypeOfSignature(signature); if (couldContainTypeVariables(inferenceTargetType)) { - // We clone the inference context to avoid disturbing a resolution in progress for an - // outer call expression. Effectively we just want a snapshot of whatever has been - // inferred for any outer call expression so far. var outerContext = getInferenceContext(node); - var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); - var instantiatedType = instantiateType(contextualType, outerMapper); - // If the contextual type is a generic function type with a single call signature, we - // instantiate the type with its own type parameters and type arguments. This ensures that - // the type parameters are not erased to type any during type inference such that they can - // be inferred as actual types from the contextual type. For example: - // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; - // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); - // Above, the type of the 'value' parameter is inferred to be 'A'. - var contextualSignature = getSingleCallSignature(instantiatedType); - var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : - instantiatedType; - // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + var isFromBindingPattern = !skipBindingPatterns && getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) !== contextualType; + // A return type inference from a binding pattern can be used in instantiating the contextual + // type of an argument later in inference, but cannot stand on its own as the final return type. + // It is incorporated into `context.returnMapper` which is used in `instantiateContextualType`, + // but doesn't need to go into `context.inferences`. This allows a an array binding pattern to + // produce a tuple for `T` in + // declare function f(cb: () => T): T; + // const [e1, e2, e3] = f(() => [1, "hi", true]); + // but does not produce any inference for `T` in + // declare function f(): T; + // const [e1, e2, e3] = f(); + if (!isFromBindingPattern) { + // We clone the inference context to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); + var instantiatedType = instantiateType(contextualType, outerMapper); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + } // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -75587,7 +76602,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_24 = 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 === 225 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -75604,7 +76619,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_24(i); + _loop_26(i); } return effectiveArgs_1; } @@ -75811,7 +76826,7 @@ var ts; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray; var typeArguments; - if (!isDecorator) { + if (!isDecorator && !ts.isSuperCall(node)) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 106 /* SyntaxKind.SuperKeyword */) { @@ -75890,6 +76905,15 @@ var ts; if (result) { return result; } + result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + // Preemptively cache the result; getResolvedSignature will do this after we return, but + // we need to ensure that the result is present for the error checks below so that if + // this signature is encountered again, we handle the circularity (rather than producing a + // different result which may produce no errors and assert). Callers of getResolvedSignature + // don't hit this issue because they only observe this result after it's had a chance to + // be cached, but the error reporting code below executes before getResolvedSignature sets + // resolvedSignature. + getNodeLinks(node).resolvedSignature = result; // No signatures were applicable. Now report errors based on the last applicable signature with // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, @@ -75924,7 +76948,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_25 = 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) { @@ -75942,7 +76966,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_25(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"); @@ -75981,7 +77005,7 @@ var ts; } } } - return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + return result; function addImplementationSuccessElaboration(failed, diagnostic) { var _a, _b; var oldCandidatesForArgumentError = candidatesForArgumentError; @@ -76061,7 +77085,7 @@ var ts; argCheckMode = checkMode & 32 /* CheckMode.IsForStringLiteralArgumentCompletions */; if (inferenceContext) { var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -76100,7 +77124,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_26 = 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; }); @@ -76108,7 +77132,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_26(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -76276,7 +77300,7 @@ var ts; // returns a function type, we choose to defer processing. This narrowly permits function composition // operators to flow inferences through return types, but otherwise processes calls right away. We // use the resolvingSignature singleton to indicate that we deferred processing. This result will be - // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and + // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and // from which we never make inferences). if (checkMode & 8 /* CheckMode.SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) { skippedGenericFunction(node, checkMode); @@ -76453,8 +77477,8 @@ var ts; if (apparentType.flags & 1048576 /* TypeFlags.Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var constituent = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var constituent = types_19[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -76620,7 +77644,7 @@ var ts; // file would probably be preferable. var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* SymbolFlags.Type */); var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* SymbolFlags.Type */, node); - var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); var parameterSymbol = createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, "props"); parameterSymbol.type = result; return createSignature(declaration, @@ -76829,8 +77853,8 @@ var ts; var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode); if (signature === resolvingSignature) { // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that - // returns a function type. We defer checking and return nonInferrableType. - return nonInferrableType; + // returns a function type. We defer checking and return silentNeverType. + return silentNeverType; } checkDeprecatedSignature(signature, node); if (node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { @@ -77438,17 +78462,6 @@ var ts; } } } - var restType = getEffectiveRestType(context); - if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { - // The contextual signature has a generic rest parameter. We first instantiate the contextual - // signature (without fixing type parameters) and assign types to contextually typed parameters. - var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper); - assignContextualParameterTypes(signature, instantiatedContext); - // We then infer from a tuple type representing the parameters that correspond to the contextual - // rest parameter. - var restPos = getParameterCount(context) - 1; - inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType); - } } function assignContextualParameterTypes(signature, context) { if (context.typeParameters) { @@ -77641,7 +78654,7 @@ var ts; var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : - instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); + instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func, /*contextFlags*/ undefined); if (isGenerator) { yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* IterationTypeKind.Yield */, isAsync); returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* IterationTypeKind.Return */, isAsync); @@ -77712,7 +78725,7 @@ var ts; nextType = iterationTypes && iterationTypes.nextType; } else { - nextType = getContextualType(yieldExpression); + nextType = getContextualType(yieldExpression, /*contextFlags*/ undefined); } if (nextType) ts.pushIfUnique(nextTypes, nextType); @@ -77727,45 +78740,12 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - /** - * Collect the TypeFacts learned from a typeof switch with - * total clauses `witnesses`, and the active clause ranging - * from `start` to `end`. Parameter `hasDefault` denotes - * whether the active clause contains a default clause. - */ - function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + // Return the combined not-equal type facts for all cases except those between the start and end indices. + function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) { var facts = 0 /* TypeFacts.None */; - // When in the default we only collect inequality facts - // because default is 'in theory' a set of infinite - // equalities. - if (hasDefault) { - // Value is not equal to any types after the active clause. - for (var i = end; i < witnesses.length; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - // Remove inequalities for types that appear in the - // active clause because they appear before other - // types collected so far. - for (var i = start; i < end; i++) { - facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); - } - // Add inequalities for types before the active clause unconditionally. - for (var i = 0; i < start; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - } - // When in an active clause without default the set of - // equalities is finite. - else { - // Add equalities for all types in the active clause. - for (var i = start; i < end; i++) { - facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeFacts.TypeofEQHostObject */; - } - // Remove equalities for types that appear before the - // active clause. - for (var i = 0; i < start; i++) { - facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); - } + for (var i = 0; i < witnesses.length; i++) { + var witness = i < start || i >= end ? witnesses[i] : undefined; + facts |= witness !== undefined ? typeofNEFacts.get(witness) || 32768 /* TypeFacts.TypeofNEHostObject */ : 0; } return facts; } @@ -77775,16 +78755,19 @@ var ts; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 216 /* SyntaxKind.TypeOfExpression */) { - var operandType = getTypeOfExpression(node.expression.expression); - var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); - // notEqualFacts states that the type of the switched value is not equal to every type in the switch. - var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_6 = getBaseConstraintOfType(operandType) || operandType; - // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_6.flags & 3 /* TypeFlags.AnyOrUnknown */) { - return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_1) === 556800 /* TypeFacts.AllTypeofNE */; + var witnesses = getSwitchClauseTypeOfWitnesses(node); + if (!witnesses) { + return false; } - return !!(filterType(type_6, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* TypeFlags.Never */); + var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(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 */) { + // We special case the top types to be exhaustive when all cases are handled. + return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_2) === 556800 /* TypeFacts.AllTypeofNE */; + } + // 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); if (!isLiteralType(type)) { @@ -77951,11 +78934,16 @@ var ts; if (isContextSensitive(node)) { if (contextualSignature) { var inferenceContext = getInferenceContext(node); + var instantiatedContextualSignature = void 0; if (checkMode && checkMode & 2 /* CheckMode.Inferential */) { inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); + var restType = getEffectiveRestType(contextualSignature); + if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { + instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper); + } } - var instantiatedContextualSignature = inferenceContext ? - instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature; + instantiatedContextualSignature || (instantiatedContextualSignature = inferenceContext ? + instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature); assignContextualParameterTypes(signature, instantiatedContextualSignature); } else { @@ -78145,7 +79133,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks && !(type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 131072 /* TypeFlags.Never */)) && - !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getTypeFacts(type) & 16777216 /* TypeFacts.IsUndefined */)) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); } } @@ -78254,7 +79242,7 @@ var ts; error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } if (node.operator === 39 /* SyntaxKind.PlusToken */) { - if (maybeTypeOfKind(operandType, 2112 /* TypeFlags.BigIntLike */)) { + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* TypeFlags.BigIntLike */)) { error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType))); } return numberType; @@ -78313,8 +79301,8 @@ var ts; } if (type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { - var t = types_21[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var t = types_20[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -78541,7 +79529,7 @@ var ts; // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* TypeFlags.Undefined */)) { + !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & 16777216 /* TypeFacts.IsUndefined */)) { sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -78554,6 +79542,10 @@ var ts; if (target.kind === 221 /* SyntaxKind.BinaryExpression */ && target.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; + // A default value is specified, so remove undefined from the final type. + if (strictNullChecks) { + sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); + } } if (target.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); @@ -78694,7 +79686,11 @@ var ts; var operator = operatorToken.kind; if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */ || operator === 56 /* SyntaxKind.BarBarToken */ || operator === 60 /* SyntaxKind.QuestionQuestionToken */) { if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); + var parent = node.parent; + while (parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */ + || ts.isBinaryExpression(parent) && (parent.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ || parent.operatorToken.kind === 56 /* SyntaxKind.BarBarToken */)) { + parent = parent.parent; + } checkTestingKnownTruthyCallableOrAwaitableType(node.left, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } checkTruthinessOfType(leftType, node.left); @@ -78918,6 +79914,10 @@ var ts; case 35 /* SyntaxKind.ExclamationEqualsToken */: case 36 /* SyntaxKind.EqualsEqualsEqualsToken */: case 37 /* SyntaxKind.ExclamationEqualsEqualsToken */: + if (ts.isLiteralExpressionOfObject(left) || ts.isLiteralExpressionOfObject(right)) { + var eqType = operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */; + error(errorNode, ts.Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); + } reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); }); return booleanType; case 102 /* SyntaxKind.InstanceOfKeyword */: @@ -78937,7 +79937,7 @@ var ts; case 56 /* SyntaxKind.BarBarToken */: case 75 /* SyntaxKind.BarBarEqualsToken */: { var resultType_3 = getTypeFacts(leftType) & 8388608 /* TypeFacts.Falsy */ ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* UnionReduction.Subtype */) : + getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* UnionReduction.Subtype */) : leftType; if (operator === 75 /* SyntaxKind.BarBarEqualsToken */) { checkAssignmentOperator(rightType); @@ -79189,7 +80189,7 @@ var ts; type = anyType; addLazyDiagnostic(function () { if (noImplicitAny && !ts.expressionResultIsUnused(node)) { - var contextualType = getContextualType(node); + var contextualType = getContextualType(node, /*contextFlags*/ undefined); if (!contextualType || isTypeAny(contextualType)) { error(node, ts.Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); } @@ -79230,7 +80230,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node, /*contextFlags*/ undefined) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; } function isTemplateLiteralContextualType(type) { return !!(type.flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */) || @@ -79258,7 +80258,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node, /*contextFlags*/ undefined)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -79373,7 +80373,7 @@ var ts; var type = checkExpression(node, checkMode, forceTuple); return isConstContext(node) || ts.isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : - getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node)); + getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node, /*contextFlags*/ undefined) : contextualType, node, /*contextFlags*/ undefined)); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. @@ -79483,8 +80483,8 @@ var ts; var result = []; var oldTypeParameters; var newTypeParameters; - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var tp = typeParameters_2[_i]; + for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { + var tp = typeParameters_3[_i]; var name = tp.symbol.escapedName; if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) { var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name); @@ -79806,12 +80806,14 @@ var ts; error(node, ts.Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); } else if (modifiers === 32768 /* ModifierFlags.In */ || modifiers === 65536 /* ModifierFlags.Out */) { - var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubType : markerSuperType); - var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperType : markerSubType); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); + var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck); + var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck); var saveVarianceTypeParameter = typeParameter; varianceTypeParameter = typeParameter; checkTypeAssignableTo(source, target, node, ts.Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation); varianceTypeParameter = saveVarianceTypeParameter; + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } } @@ -79832,7 +80834,7 @@ var ts; error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + if ((node.questionToken || isJSDocOptionalParameter(node)) && ts.isBindingPattern(node.name) && func.body) { error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { @@ -80161,7 +81163,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_27 = 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)); @@ -80176,7 +81178,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_27(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -80209,6 +81211,9 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); + if (ts.isMethodDeclaration(node) && node.asteriskToken && ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_a_generator); + } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // method signatures already report "implementation not allowed in ambient context" elsewhere @@ -80336,6 +81341,9 @@ var ts; return !!ts.forEachChild(node, nodeImmediatelyReferencesSuperOrThis); } function checkAccessorDeclaration(node) { + if (ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_an_accessor); + } addLazyDiagnostic(checkAccessorDeclarationDiagnostics); checkSourceElement(node.body); setNodeLinksForPrivateIdentifierScope(node); @@ -80393,6 +81401,12 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) { + if (index < typeParameters.length) { + return getTypeFromTypeNode(node.typeArguments[index]); + } + return getEffectiveTypeArguments(node, typeParameters)[index]; + } function getEffectiveTypeArguments(node, typeParameters) { return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } @@ -80634,8 +81648,11 @@ var ts; if (node.assertions) { var override = ts.getResolutionModeOverrideForClause(node.assertions.assertClause, grammarErrorOnNode); if (override) { + if (!ts.isNightly()) { + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } } } @@ -81020,7 +82037,7 @@ var ts; * @param type The type of the promise. * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. */ - function getPromisedTypeOfPromise(type, errorNode) { + function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) { // // { // type // then( // thenFunction @@ -81055,7 +82072,29 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); + var thisTypeForError; + var candidates; + for (var _i = 0, thenSignatures_1 = thenSignatures; _i < thenSignatures_1.length; _i++) { + var thenSignature = thenSignatures_1[_i]; + var thisType = getThisTypeOfSignature(thenSignature); + if (thisType && thisType !== voidType && !isTypeRelatedTo(type, thisType, subtypeRelation)) { + thisTypeForError = thisType; + } + else { + candidates = ts.append(candidates, thenSignature); + } + } + if (!candidates) { + ts.Debug.assertIsDefined(thisTypeForError); + if (thisTypeForErrorOut) { + thisTypeForErrorOut.value = thisTypeForError; + } + if (errorNode) { + error(errorNode, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError)); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(candidates, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -81109,6 +82148,34 @@ var ts; isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : type; } + function isAwaitedTypeNeeded(type) { + // If this is already an `Awaited`, we shouldn't wrap it. This helps to avoid `Awaited>` in higher-order. + if (isTypeAny(type) || isAwaitedTypeInstantiation(type)) { + return false; + } + // We only need `Awaited` if `T` contains possibly non-primitive types. + if (isGenericObjectType(type)) { + var baseConstraint = getBaseConstraintOfType(type); + // 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) : + maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { + return true; + } + } + return false; + } + function tryCreateAwaitedType(type) { + // Nothing to do if `Awaited` doesn't exist + var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); + if (awaitedSymbol) { + // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where + // an `Awaited` would suffice. + return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); + } + return undefined; + } function createAwaitedTypeIfNeeded(type) { // We wrap type `T` in `Awaited` based on the following conditions: // - `T` is not already an `Awaited`, and @@ -81117,26 +82184,10 @@ var ts; // - `T` has no base constraint, or // - The base constraint of `T` is `any`, `unknown`, `object`, or `{}`, or // - The base constraint of `T` is an object type with a callable `then` method. - if (isTypeAny(type)) { - return type; - } - // If this is already an `Awaited`, just return it. This helps to avoid `Awaited>` in higher-order. - if (isAwaitedTypeInstantiation(type)) { - return type; - } - // Only instantiate `Awaited` if `T` contains possibly non-primitive types. - if (isGenericObjectType(type)) { - var baseConstraint = getBaseConstraintOfType(type); - // Only instantiate `Awaited` if `T` 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)) { - // Nothing to do if `Awaited` doesn't exist - var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); - if (awaitedSymbol) { - // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where - // an `Awaited` would suffice. - return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); - } + if (isAwaitedTypeNeeded(type)) { + var awaitedType = tryCreateAwaitedType(type); + if (awaitedType) { + return awaitedType; } } ts.Debug.assert(getPromisedTypeOfPromise(type) === undefined, "type provided should not be a non-generic 'promise'-like."); @@ -81176,10 +82227,24 @@ var ts; } // For a union, get a union of the awaited types of each constituent. if (type.flags & 1048576 /* TypeFlags.Union */) { + if (awaitedTypeStack.lastIndexOf(type.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } var mapper = errorNode ? function (constituentType) { return getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeNoAlias; - return typeAsAwaitable.awaitedTypeOfType = mapType(type, mapper); + awaitedTypeStack.push(type.id); + var mapped = mapType(type, mapper); + awaitedTypeStack.pop(); + return typeAsAwaitable.awaitedTypeOfType = mapped; + } + // If `type` is generic and should be wrapped in `Awaited`, return it. + if (isAwaitedTypeNeeded(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; } - var promisedType = getPromisedTypeOfPromise(type); + var thisTypeForErrorOut = { value: undefined }; + var promisedType = getPromisedTypeOfPromise(type, /*errorNode*/ undefined, thisTypeForErrorOut); if (promisedType) { if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose @@ -81248,7 +82313,12 @@ var ts; if (isThenableType(type)) { if (errorNode) { ts.Debug.assertIsDefined(diagnosticMessage); - error(errorNode, diagnosticMessage, arg0); + var chain = void 0; + if (thisTypeForErrorOut.value) { + chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value)); + } + chain = ts.chainDiagnosticMessages(chain, diagnosticMessage, arg0); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, chain)); } return undefined; } @@ -81444,8 +82514,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { - var typeNode = types_22[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */ || typeNode.kind === 197 /* SyntaxKind.NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } @@ -81485,18 +82555,18 @@ var ts; } /** Check the decorators of a node */ function checkDecorators(node) { - if (!node.decorators) { - return; - } // skip this check for nodes that cannot have decorators. These should have already had an error reported by // checkGrammarDecorators. - if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node) || !node.modifiers || !ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning); } - var firstDecorator = node.decorators[0]; + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (!firstDecorator) { + return; + } checkExternalEmitHelpers(firstDecorator, 8 /* ExternalEmitHelpers.Decorate */); if (node.kind === 164 /* SyntaxKind.Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* ExternalEmitHelpers.Param */); @@ -81540,7 +82610,12 @@ var ts; break; } } - ts.forEach(node.decorators, checkDecorator); + for (var _f = 0, _g = node.modifiers; _f < _g.length; _f++) { + var modifier = _g[_f]; + if (ts.isDecorator(modifier)) { + checkDecorator(modifier); + } + } } function checkFunctionDeclaration(node) { addLazyDiagnostic(checkFunctionDeclarationDiagnostics); @@ -81571,6 +82646,11 @@ var ts; function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } + function checkJSDocLinkLikeTag(node) { + if (node.name) { + resolveJSDocMemberName(node.name, /*ignoreErrors*/ true); + } + } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); } @@ -81810,8 +82890,8 @@ var ts; return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); - for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { - var typeParameter = typeParameters_3[_i]; + for (var _i = 0, typeParameters_4 = typeParameters; _i < typeParameters_4.length; _i++) { + var typeParameter = typeParameters_4[_i]; if (!isTypeParameterUnused(typeParameter)) continue; var name = ts.idText(typeParameter.name); @@ -81971,6 +83051,22 @@ var ts; } }); } + function checkPotentialUncheckedRenamedBindingElementsInTypes() { + var _a; + for (var _i = 0, potentialUnusedRenamedBindingElementsInTypes_1 = potentialUnusedRenamedBindingElementsInTypes; _i < potentialUnusedRenamedBindingElementsInTypes_1.length; _i++) { + var node = potentialUnusedRenamedBindingElementsInTypes_1[_i]; + if (!((_a = getSymbolOfNode(node)) === null || _a === void 0 ? void 0 : _a.isReferenced)) { + var wrappingDeclaration = ts.walkUpBindingElementsAndPatterns(node); + ts.Debug.assert(ts.isParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here"); + var diagnostic = ts.createDiagnosticForNode(node.name, ts.Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, ts.declarationNameToString(node.name), ts.declarationNameToString(node.propertyName)); + if (!wrappingDeclaration.type) { + // entire parameter does not have type annotation, suggest adding an annotation + ts.addRelatedInfo(diagnostic, ts.createFileDiagnostic(ts.getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, ts.Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, ts.declarationNameToString(node.propertyName))); + } + diagnostics.add(diagnostic); + } + } + } function bindingNameText(name) { switch (name.kind) { case 79 /* SyntaxKind.Identifier */: @@ -82267,11 +83363,22 @@ var ts; // well known symbols. if (node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.name); - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkExpressionCached(node.initializer); } } if (ts.isBindingElement(node)) { + if (node.propertyName && + ts.isIdentifier(node.name) && + ts.isParameterDeclaration(node) && + ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + // type F = ({a: string}) => void; + // ^^^^^^ + // variable renaming in function type notation is confusing, + // so we forbid it even if noUnusedLocals is not enabled + potentialUnusedRenamedBindingElementsInTypes.push(node); + return; + } if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ScriptTarget.ES2018 */) { checkExternalEmitHelpers(node, 4 /* ExternalEmitHelpers.Rest */); } @@ -82304,14 +83411,14 @@ var ts; ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (ts.isParameter(node) && node.initializer && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; - var needCheckWidenedType = node.name.elements.length === 0; + var needCheckInitializer = ts.hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; + var needCheckWidenedType = !ts.some(node.name.elements, ts.not(ts.isOmittedExpression)); if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error var widenedType = getWidenedTypeForVariableLikeDeclaration(node); @@ -82338,7 +83445,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.kind === 203 /* SyntaxKind.BindingElement */ ? node.parent.parent : node)) { checkAliasSymbol(node); return; } @@ -82346,7 +83453,7 @@ var ts; if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - var initializer = ts.getEffectiveInitializer(node); + var initializer = ts.hasOnlyExpressionInitializer(node) && ts.getEffectiveInitializer(node); if (initializer) { var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && @@ -82371,7 +83478,7 @@ var ts; !(symbol.flags & 67108864 /* SymbolFlags.Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); } - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { @@ -82464,7 +83571,7 @@ var ts; return; var type = checkTruthinessExpression(location); var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) && isTypeAssertion(location.expression); - if (getFalsyFlags(type) || isPropertyExpressionCast) + if (!(getTypeFacts(type) & 4194304 /* TypeFacts.Truthy */) || isPropertyExpressionCast) return; // While it technically should be invalid for any known-truthy value // to be tested, we de-scope to functions and Promises unreferenced in @@ -82930,17 +84037,28 @@ var ts; * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. */ function getIterationTypesOfIterable(type, use, errorNode) { + var _a, _b; if (isTypeAny(type)) { return anyIterationTypes; } if (!(type.flags & 1048576 /* TypeFlags.Union */)) { - var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode); + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); if (iterationTypes_1 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } return undefined; } + else if ((_a = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _a === void 0 ? void 0 : _a.length) { + for (var _i = 0, _c = errorOutputContainer.errors; _i < _c.length; _i++) { + var diag = _c[_i]; + diagnostics.add(diag); + } + } return iterationTypes_1; } var cacheKey = use & 2 /* IterationUse.AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; @@ -82948,19 +84066,27 @@ var ts; if (cachedTypes) return cachedTypes === noIterationTypes ? undefined : cachedTypes; var allIterationTypes; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituent = _a[_i]; - var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode); + for (var _d = 0, _e = type.types; _d < _e.length; _d++) { + var constituent = _e[_d]; + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer); if (iterationTypes_2 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } setCachedIterationTypes(type, cacheKey, noIterationTypes); return undefined; } - else { - allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); + else if ((_b = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _b === void 0 ? void 0 : _b.length) { + for (var _f = 0, _g = errorOutputContainer.errors; _f < _g.length; _f++) { + var diag = _g[_f]; + diagnostics.add(diag); + } } + allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); } var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes; setCachedIterationTypes(type, cacheKey, iterationTypes); @@ -82988,47 +84114,62 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableWorker(type, use, errorNode) { + function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) { if (isTypeAny(type)) { return anyIterationTypes; } + // If we are reporting errors and encounter a cached `noIterationTypes`, we should ignore the cached value and continue as if nothing was cached. + // In addition, we should not cache any new results for this call. + var noCache = false; if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver); if (iterationTypes) { - return use & 8 /* IterationUse.ForOfFlag */ ? - getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : - iterationTypes; + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; + } + else { + return use & 8 /* IterationUse.ForOfFlag */ ? + getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : + iterationTypes; + } } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver); if (iterationTypes) { - if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - // for a sync iterable in an async context, only use the cached types if they are valid. - if (iterationTypes !== noIterationTypes) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode)); - } + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; } else { - return iterationTypes; + if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { + // for a sync iterable in an async context, only use the cached types if they are valid. + if (iterationTypes !== noIterationTypes) { + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); + } + } + else { + return iterationTypes; + } } } } if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { return iterationTypes; } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes - ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) - : noIterationTypes); + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); } else { return iterationTypes; @@ -83049,7 +84190,7 @@ var ts; } function getIterationTypesOfGlobalIterableType(globalType, resolver) { var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || - getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; } /** @@ -83103,40 +84244,56 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableSlow(type, resolver, errorNode) { + function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var _a; var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* SymbolFlags.Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); + return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); } var signatures = methodType ? getSignaturesOfType(methodType, 0 /* SignatureKind.Call */) : undefined; if (!ts.some(signatures)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); + return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); } var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature)); - var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes; - return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); + var iterationTypes = (_a = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache)) !== null && _a !== void 0 ? _a : noIterationTypes; + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { 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; - errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + } + /** + * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. + * + * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` + * record is returned. Otherwise, `undefined` is returned. + */ + function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { + return getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, /*noCache*/ false); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. * * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, `undefined` is returned. + * + * NOTE: You probably don't want to call this directly and should be calling + * `getIterationTypesOfIterator` instead. */ - function getIterationTypesOfIterator(type, resolver, errorNode) { + function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) { if (isTypeAny(type)) { return anyIterationTypes; } var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || - getIterationTypesOfIteratorFast(type, resolver) || - getIterationTypesOfIteratorSlow(type, resolver, errorNode); + getIterationTypesOfIteratorFast(type, resolver); + if (iterationTypes === noIterationTypes && errorNode) { + iterationTypes = undefined; + noCache = true; + } + iterationTypes !== null && iterationTypes !== void 0 ? iterationTypes : (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache)); return iterationTypes === noIterationTypes ? undefined : iterationTypes; } /** @@ -83174,7 +84331,7 @@ var ts; // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any` // and `undefined` in our libs by default, a custom lib *could* use different definitions. var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || - getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType; return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } @@ -83244,8 +84401,8 @@ var ts; * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, we return `undefined`. */ - function getIterationTypesOfMethod(type, resolver, methodName, errorNode) { - var _a, _b, _c, _d; + function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) { + var _a, _b, _c, _d, _e, _f; var method = getPropertyOfType(type, methodName); // Ignore 'return' or 'throw' if they are missing. if (!method && methodName !== "next") { @@ -83265,9 +84422,15 @@ var ts; var diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic; - error(errorNode, diagnostic, methodName); + if (errorOutputContainer) { + (_a = errorOutputContainer.errors) !== null && _a !== void 0 ? _a : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, diagnostic, methodName)); + } + else { + error(errorNode, diagnostic, methodName); + } } - return methodName === "next" ? anyIterationTypes : undefined; + return methodName === "next" ? noIterationTypes : undefined; } // If the method signature comes exclusively from the global iterator or generator type, // create iteration types from its type arguments like `getIterationTypesOfIteratorFast` @@ -83279,8 +84442,8 @@ var ts; if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) { var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false); var globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false); - var isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) === null || _a === void 0 ? void 0 : _a.members) === null || _b === void 0 ? void 0 : _b.get(methodName)) === methodType.symbol; - var isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) === null || _c === void 0 ? void 0 : _c.members) === null || _d === void 0 ? void 0 : _d.get(methodName)) === methodType.symbol; + var isGeneratorMethod = ((_c = (_b = globalGeneratorType.symbol) === null || _b === void 0 ? void 0 : _b.members) === null || _c === void 0 ? void 0 : _c.get(methodName)) === methodType.symbol; + var isIteratorMethod = !isGeneratorMethod && ((_e = (_d = globalIteratorType.symbol) === null || _d === void 0 ? void 0 : _d.members) === null || _e === void 0 ? void 0 : _e.get(methodName)) === methodType.symbol; if (isGeneratorMethod || isIteratorMethod) { var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType; var mapper = methodType.mapper; @@ -83320,7 +84483,13 @@ var ts; var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType); if (iterationTypes === noIterationTypes) { if (errorNode) { - error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + if (errorOutputContainer) { + (_f = errorOutputContainer.errors) !== null && _f !== void 0 ? _f : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName)); + } + else { + error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + } } yieldType = anyType; returnTypes = ts.append(returnTypes, anyType); @@ -83341,13 +84510,13 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterator` instead. */ - function getIterationTypesOfIteratorSlow(type, resolver, errorNode) { + function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var iterationTypes = combineIterationTypes([ - getIterationTypesOfMethod(type, resolver, "next", errorNode), - getIterationTypesOfMethod(type, resolver, "return", errorNode), - getIterationTypesOfMethod(type, resolver, "throw", errorNode), + getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer), ]); - return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); } /** * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like, @@ -83368,7 +84537,7 @@ var ts; var use = isAsyncGenerator ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) || - getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined); } function checkBreakOrContinueStatement(node) { // Grammar checking @@ -83379,9 +84548,14 @@ var ts; function unwrapReturnType(returnType, functionFlags) { var isGenerator = !!(functionFlags & 1 /* FunctionFlags.Generator */); var isAsync = !!(functionFlags & 2 /* FunctionFlags.Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync) || errorType : - isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : - returnType; + if (isGenerator) { + var returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync); + if (!returnIterationType) { + return errorType; + } + return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType; + } + return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func)); @@ -83601,9 +84775,10 @@ var ts; } var indexInfos = getApplicableIndexInfos(type, propNameType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; - var localPropDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || - name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ || getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_28 = function (info) { + var propDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || + name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; + var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; + 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 @@ -83611,12 +84786,16 @@ var ts; var errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !ts.some(getBaseTypes(type), function (base) { return !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType); }) ? interfaceDeclaration : undefined); if (errorNode && !isTypeAssignableTo(propType, info.type)) { - error(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + var diagnostic = createError(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + if (propDeclaration && errorNode !== propDeclaration) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(propDeclaration, ts.Diagnostics._0_is_declared_here, symbolToString(prop))); + } + diagnostics.add(diagnostic); } }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_28(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -83624,7 +84803,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_29 = 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; @@ -83639,7 +84818,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_29(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -83828,8 +85007,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { - grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (firstDecorator && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(firstDecorator, ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -83958,7 +85138,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_30 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -83975,7 +85155,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_30(member); + _loop_32(member); } } /** @@ -84063,7 +85243,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_31 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -84082,7 +85262,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_31(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -84150,18 +85330,17 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. - var _a, _b; + var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { - continue; + return "continue"; } var baseSymbol = getPropertyOfObjectType(type, base.escapedName); if (!baseSymbol) { - continue; + return "continue"; } var derived = getTargetSymbol(baseSymbol); var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); @@ -84179,14 +85358,14 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { - var otherBaseType = _d[_c]; + for (var _e = 0, _f = getBaseTypes(type); _e < _f.length; _e++) { + var otherBaseType = _f[_e]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1); if (derivedElsewhere && derivedElsewhere !== base) { - continue basePropertyCheck; + return "continue-basePropertyCheck"; } } if (derivedClassDecl.kind === 226 /* SyntaxKind.ClassExpression */) { @@ -84201,20 +85380,19 @@ var ts; // derived overrides base. var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* ModifierFlags.Private */ || derivedDeclarationFlags & 8 /* ModifierFlags.Private */) { - // either base or derived property is private - not override, skip it - continue; + return "continue"; } var errorMessage = void 0; var basePropertyFlags = base.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; var derivedPropertyFlags = derived.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor - if (baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */ + if ((ts.getCheckFlags(base) & 6 /* CheckFlags.Synthetic */ + ? (_a = base.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); }) + : (_b = base.declarations) === null || _b === void 0 ? void 0 : _b.every(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); })) + || ts.getCheckFlags(base) & 262144 /* CheckFlags.Mapped */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { - // when the base property is abstract or from an interface, base/derived flags don't need to match - // same when the derived property is from an assignment - continue; + return "continue"; } var overriddenInstanceProperty = basePropertyFlags !== 4 /* SymbolFlags.Property */ && derivedPropertyFlags === 4 /* SymbolFlags.Property */; var overriddenInstanceAccessor = basePropertyFlags === 4 /* SymbolFlags.Property */ && derivedPropertyFlags !== 4 /* SymbolFlags.Property */; @@ -84225,12 +85403,12 @@ var ts; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { - var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); + var uninitialized = (_c = derived.declarations) === null || _c === void 0 ? void 0 : _c.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* SymbolFlags.Transient */) && !(baseDeclarationFlags & 128 /* ModifierFlags.Abstract */) && !(derivedDeclarationFlags & 128 /* ModifierFlags.Abstract */) - && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { + && !((_d = derived.declarations) === null || _d === void 0 ? void 0 : _d.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -84243,13 +85421,11 @@ var ts; } } } - // correct case - continue; + return "continue"; } else if (isPrototypeProperty(base)) { if (isPrototypeProperty(derived) || derived.flags & 4 /* SymbolFlags.Property */) { - // method is overridden with method or property -- correct case - continue; + return "continue"; } else { ts.Debug.assert(!!(derived.flags & 98304 /* SymbolFlags.Accessor */)); @@ -84264,9 +85440,20 @@ var ts; } error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } + }; + basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var state_10 = _loop_34(baseProperty); + switch (state_10) { + case "continue-basePropertyCheck": continue basePropertyCheck; + } } } - function getNonInterhitedProperties(type, baseTypes, properties) { + function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { + return baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && (!ts.isPropertyDeclaration(declaration) || !declaration.initializer) + || ts.isInterfaceDeclaration(declaration.parent); + } + function getNonInheritedProperties(type, baseTypes, properties) { if (!ts.length(baseTypes)) { return properties; } @@ -84335,7 +85522,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName) || ts.isComputedPropertyName(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || containsUndefinedType(type))) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -84360,7 +85547,7 @@ var ts; ts.setParent(reference, staticBlock); reference.flowNode = staticBlock.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - if (!(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */)) { + if (!containsUndefinedType(flowType)) { return true; } } @@ -84375,7 +85562,7 @@ var ts; ts.setParent(reference, constructor); reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */); + return !containsUndefinedType(flowType); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -84891,6 +86078,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a, _b, _c, _d, _e; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -84901,6 +86089,31 @@ var ts; // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). symbol = getMergedSymbol(symbol.exportSymbol || symbol); + // A type-only import/export will already have a grammar error in a JS file, so no need to issue more errors within + if (ts.isInJSFile(node) && !(target.flags & 111551 /* SymbolFlags.Value */) && !ts.isTypeOnlyImportOrExportDeclaration(node)) { + var errorNode = ts.isImportOrExportSpecifier(node) ? node.propertyName || node.name : + ts.isNamedDeclaration(node) ? node.name : + node; + ts.Debug.assert(node.kind !== 274 /* SyntaxKind.NamespaceExport */); + if (node.kind === 275 /* SyntaxKind.ExportSpecifier */) { + var diag = error(errorNode, ts.Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); + var alreadyExportedSymbol = (_b = (_a = ts.getSourceFileOfNode(node).symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.get((node.propertyName || node.name).escapedText); + if (alreadyExportedSymbol === target) { + var exportingDeclaration = (_c = alreadyExportedSymbol.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isJSDocNode); + if (exportingDeclaration) { + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(exportingDeclaration, ts.Diagnostics._0_is_automatically_exported_here, ts.unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName))); + } + } + } + else { + ts.Debug.assert(node.kind !== 254 /* SyntaxKind.VariableDeclaration */); + var importDeclaration = ts.findAncestor(node, ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration)); + var moduleSpecifier = (_e = (importDeclaration && ((_d = ts.tryGetModuleSpecifierFromDeclaration(importDeclaration)) === null || _d === void 0 ? void 0 : _d.text))) !== null && _e !== void 0 ? _e : "..."; + var importedIdentifier = ts.unescapeLeadingUnderscores(ts.isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); + error(errorNode, ts.Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, "import(\"".concat(moduleSpecifier, "\").").concat(importedIdentifier)); + } + return; + } 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); @@ -85006,10 +86219,10 @@ var ts; var override = ts.getResolutionModeOverrideForClause(declaration.assertClause, validForTypeAssertions ? grammarErrorOnNode : undefined); if (validForTypeAssertions && override) { if (!ts.isNightly()) { - grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } return; // Other grammar checks do not apply to type-only imports with resolution mode assertions } @@ -85216,7 +86429,9 @@ var ts; error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { - markExportAsReferenced(node); + if (!node.isTypeOnly && !node.parent.parent.isTypeOnly) { + markExportAsReferenced(node); + } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); @@ -85358,12 +86573,16 @@ var ts; } } function checkSourceElementWorker(node) { - if (ts.isInJSFile(node)) { - ts.forEach(node.jsDoc, function (_a) { - var tags = _a.tags; - return ts.forEach(tags, checkSourceElement); + ts.forEach(node.jsDoc, function (_a) { + var comment = _a.comment, tags = _a.tags; + checkJSDocCommentWorker(comment); + ts.forEach(tags, function (tag) { + checkJSDocCommentWorker(tag.comment); + if (ts.isInJSFile(node)) { + checkSourceElement(tag); + } }); - } + }); var kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessively @@ -85449,6 +86668,10 @@ var ts; return checkJSDocTemplateTag(node); case 343 /* SyntaxKind.JSDocTypeTag */: return checkJSDocTypeTag(node); + case 324 /* SyntaxKind.JSDocLink */: + case 325 /* SyntaxKind.JSDocLinkCode */: + case 326 /* SyntaxKind.JSDocLinkPlain */: + return checkJSDocLinkLikeTag(node); case 340 /* SyntaxKind.JSDocParameterTag */: return checkJSDocParameterTag(node); case 347 /* SyntaxKind.JSDocPropertyTag */: @@ -85543,6 +86766,15 @@ var ts; return checkMissingDeclaration(node); } } + function checkJSDocCommentWorker(node) { + if (ts.isArray(node)) { + ts.forEach(node, function (tag) { + if (ts.isJSDocLinkLike(tag)) { + checkSourceElement(tag); + } + }); + } + } function checkJSDocTypeIsInJsFile(node) { if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); @@ -85710,6 +86942,7 @@ var ts; ts.clear(potentialNewTargetCollisions); ts.clear(potentialWeakMapSetCollisions); ts.clear(potentialReflectCollisions); + ts.clear(potentialUnusedRenamedBindingElementsInTypes); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -85725,6 +86958,9 @@ var ts; } }); } + if (!node.isDeclarationFile) { + checkPotentialUncheckedRenamedBindingElementsInTypes(); + } }); if (compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ && !node.isDeclarationFile && @@ -86098,7 +87334,7 @@ var ts; if (!result && isJSDoc_1) { var container = ts.findAncestor(name, ts.or(ts.isClassLike, ts.isInterfaceDeclaration)); if (container) { - return resolveJSDocMemberName(name, getSymbolOfNode(container)); + return resolveJSDocMemberName(name, /*ignoreErrors*/ false, getSymbolOfNode(container)); } } return result; @@ -86144,11 +87380,11 @@ var ts; * * For unqualified names, a container K may be provided as a second argument. */ - function resolveJSDocMemberName(name, container) { + function resolveJSDocMemberName(name, ignoreErrors, container) { if (ts.isEntityName(name)) { // resolve static values first var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */ | 111551 /* SymbolFlags.Value */; - var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, ignoreErrors, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); if (!symbol && ts.isIdentifier(name) && container) { symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning)); } @@ -86156,7 +87392,7 @@ var ts; return symbol; } } - var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left); + var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container); var right = ts.isIdentifier(name) ? name.escapedText : name.right.escapedText; if (left) { var proto = left.flags & 111551 /* SymbolFlags.Value */ && getPropertyOfType(getTypeOfSymbol(left), "prototype"); @@ -87147,13 +88383,20 @@ var ts; if (!fileToDirective) { return undefined; } + // computed property name should use node as value // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; - if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + var meaning; + if (node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) { meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; } + else { + meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; + if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; + } + } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -87437,7 +88680,10 @@ var ts; return checkGrammarDecorators(node) || checkGrammarModifiers(node); } function checkGrammarDecorators(node) { - if (!node.decorators) { + if (ts.canHaveIllegalDecorators(node) && ts.some(node.illegalDecorators)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node)) { return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { @@ -87450,7 +88696,7 @@ var ts; } else if (node.kind === 172 /* SyntaxKind.GetAccessor */ || node.kind === 173 /* SyntaxKind.SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + if (ts.hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } } @@ -87465,6 +88711,8 @@ var ts; var flags = 0 /* ModifierFlags.None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; if (modifier.kind !== 145 /* SyntaxKind.ReadonlyKeyword */) { if (node.kind === 166 /* SyntaxKind.PropertySignature */ || node.kind === 168 /* SyntaxKind.MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); @@ -87750,6 +88998,13 @@ var ts; case 164 /* SyntaxKind.Parameter */: case 163 /* SyntaxKind.TypeParameter */: return false; + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 179 /* SyntaxKind.FunctionType */: + case 276 /* SyntaxKind.MissingDeclaration */: + return true; default: if (node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 305 /* SyntaxKind.SourceFile */) { return false; @@ -87760,20 +89015,26 @@ var ts; case 257 /* SyntaxKind.ClassDeclaration */: case 180 /* SyntaxKind.ConstructorType */: return nodeHasAnyModifiersExcept(node, 126 /* SyntaxKind.AbstractKeyword */); + case 226 /* SyntaxKind.ClassExpression */: case 258 /* SyntaxKind.InterfaceDeclaration */: case 237 /* SyntaxKind.VariableStatement */: case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: return true; case 260 /* SyntaxKind.EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 85 /* SyntaxKind.ConstKeyword */); default: - ts.Debug.fail(); + ts.Debug.assertNever(node); } } } function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; + return modifier.kind !== allowedModifier; + } + return false; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { @@ -88065,14 +89326,20 @@ var ts; grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration - if (prop.modifiers) { + if (ts.canHaveModifiers(prop) && prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */) { + if (ts.isModifier(mod) && (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */)) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } + else if (ts.canHaveIllegalModifiers(prop) && prop.modifiers) { + for (var _d = 0, _e = prop.modifiers; _d < _e.length; _d++) { + var mod = _e[_d]; + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and @@ -88084,10 +89351,9 @@ var ts; var currentKind = void 0; switch (prop.kind) { case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); - // falls through case 296 /* SyntaxKind.PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* SyntaxKind.NumericLiteral */) { checkGrammarNumericLiteral(name); @@ -88526,9 +89792,6 @@ var ts; else { return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (!isConstOrReadonly || isInvalidInitializer) { - return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } } } function checkGrammarVariableDeclaration(node) { @@ -88695,7 +89958,7 @@ var ts; } } function checkGrammarConstructorTypeAnnotation(node) { - var type = ts.getEffectiveReturnTypeNode(node); + var type = node.type || ts.getEffectiveReturnTypeNode(node); if (type) { return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } @@ -88719,6 +89982,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Interfaces cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } @@ -88727,6 +89992,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Type literals cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } @@ -89101,7 +90368,6 @@ var ts; if (nodes === undefined || visitor === undefined) { return nodes; } - var updated; // Ensure start and count have valid values var length = nodes.length; if (start === undefined || start < 0) { @@ -89114,12 +90380,49 @@ var ts; var pos = -1; var end = -1; if (start > 0 || count < length) { - // If we are not visiting all of the original nodes, we must always create a new array. // Since this is a fragment of a node array, we do not copy over the previous location // and will only copy over `hasTrailingComma` if we are including the last element. - updated = []; hasTrailingComma = nodes.hasTrailingComma && start + count === length; } + else { + pos = nodes.pos; + end = nodes.end; + hasTrailingComma = nodes.hasTrailingComma; + } + var updated = visitArrayWorker(nodes, visitor, test, start, count); + if (updated !== nodes) { + // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. + var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); + ts.setTextRangePosEnd(updatedArray, pos, end); + return updatedArray; + } + return nodes; + } + ts.visitNodes = visitNodes; + /* @internal */ + function visitArray(nodes, visitor, test, start, count) { + if (nodes === undefined) { + return nodes; + } + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + return visitArrayWorker(nodes, visitor, test, start, count); + } + ts.visitArray = visitArray; + /* @internal */ + function visitArrayWorker(nodes, visitor, test, start, count) { + var updated; + var length = nodes.length; + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + updated = []; + } // Visit each original node. for (var i = 0; i < count; i++) { var node = nodes[i + start]; @@ -89128,9 +90431,6 @@ var ts; if (updated === undefined) { // Ensure we have a copy of `nodes`, up to the current index. updated = nodes.slice(0, i); - hasTrailingComma = nodes.hasTrailingComma; - pos = nodes.pos; - end = nodes.end; } if (visited) { if (ts.isArray(visited)) { @@ -89147,15 +90447,8 @@ var ts; } } } - if (updated) { - // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. - var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); - ts.setTextRangePosEnd(updatedArray, pos, end); - return updatedArray; - } - return nodes; + return updated !== null && updated !== void 0 ? updated : nodes; } - ts.visitNodes = visitNodes; /** * Starts a new lexical environment and visits a statement list, ending the lexical environment * and merging hoisted declarations upon completion. @@ -89227,7 +90520,7 @@ var ts; /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) : factory.getGeneratedNameForNode(parameter)), ]))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, /*initializer*/ undefined); } function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { @@ -89235,7 +90528,7 @@ var ts; context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([ factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(ts.setEmitFlags(factory.cloneNode(name), 48 /* EmitFlags.NoSourceMap */), ts.setEmitFlags(initializer, 48 /* EmitFlags.NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* EmitFlags.NoComments */)), parameter), 1536 /* EmitFlags.NoComments */)) ]), parameter), 1 /* EmitFlags.SingleLine */ | 32 /* EmitFlags.NoTrailingSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */ | 1536 /* EmitFlags.NoComments */))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, /*initializer*/ undefined); } function visitFunctionBody(node, visitor, context, nodeVisitor) { @@ -89301,7 +90594,7 @@ var ts; return factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); case 164 /* SyntaxKind.Parameter */: ts.Debug.type(node); - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + return factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 165 /* SyntaxKind.Decorator */: ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -89311,7 +90604,7 @@ var ts; return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 167 /* SyntaxKind.PropertyDeclaration */: ts.Debug.type(node); - return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), + return factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 168 /* SyntaxKind.MethodSignature */: @@ -89319,21 +90612,21 @@ var ts; return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 169 /* SyntaxKind.MethodDeclaration */: ts.Debug.type(node); - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 171 /* SyntaxKind.Constructor */: ts.Debug.type(node); - return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 172 /* SyntaxKind.GetAccessor */: ts.Debug.type(node); - return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 173 /* SyntaxKind.SetAccessor */: ts.Debug.type(node); - return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: ts.Debug.type(node); context.startLexicalEnvironment(); context.suspendLexicalEnvironment(); - return factory.updateClassStaticBlockDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 174 /* SyntaxKind.CallSignature */: ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -89342,7 +90635,7 @@ var ts; return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 176 /* SyntaxKind.IndexSignature */: ts.Debug.type(node); - return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types case 177 /* SyntaxKind.TypePredicate */: ts.Debug.type(node); @@ -89388,13 +90681,13 @@ var ts; return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); case 200 /* SyntaxKind.ImportType */: ts.Debug.type(node); - return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); case 295 /* SyntaxKind.ImportTypeAssertionContainer */: ts.Debug.type(node); return factory.updateImportTypeAssertionContainer(node, nodeVisitor(node.assertClause, visitor, ts.isNode), node.multiLine); case 197 /* SyntaxKind.NamedTupleMember */: ts.Debug.type(node); - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + return factory.updateNamedTupleMember(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 191 /* SyntaxKind.ParenthesizedType */: ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -89459,7 +90752,7 @@ var ts; return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 210 /* SyntaxKind.TaggedTemplateExpression */: ts.Debug.type(node); - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); case 211 /* SyntaxKind.TypeAssertionExpression */: ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -89507,7 +90800,7 @@ var ts; return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 226 /* SyntaxKind.ClassExpression */: ts.Debug.type(node); - return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 228 /* SyntaxKind.ExpressionWithTypeArguments */: ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); @@ -89588,22 +90881,22 @@ var ts; return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 256 /* SyntaxKind.FunctionDeclaration */: ts.Debug.type(node); - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 257 /* SyntaxKind.ClassDeclaration */: ts.Debug.type(node); - return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 258 /* SyntaxKind.InterfaceDeclaration */: ts.Debug.type(node); - return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + return factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 259 /* SyntaxKind.TypeAliasDeclaration */: ts.Debug.type(node); - return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 260 /* SyntaxKind.EnumDeclaration */: ts.Debug.type(node); - return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + return factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 261 /* SyntaxKind.ModuleDeclaration */: ts.Debug.type(node); - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + return factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); case 262 /* SyntaxKind.ModuleBlock */: ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); @@ -89615,10 +90908,10 @@ var ts; return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); case 265 /* SyntaxKind.ImportEqualsDeclaration */: ts.Debug.type(node); - return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); + return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); case 266 /* SyntaxKind.ImportDeclaration */: ts.Debug.type(node); - return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 293 /* SyntaxKind.AssertClause */: ts.Debug.type(node); return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); @@ -89642,10 +90935,10 @@ var ts; return factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); case 271 /* SyntaxKind.ExportAssignment */: ts.Debug.type(node); - return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); + return factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); case 272 /* SyntaxKind.ExportDeclaration */: ts.Debug.type(node); - return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 273 /* SyntaxKind.NamedExports */: ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); @@ -90738,6 +92031,126 @@ var ts; return !ts.isStatic(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); } ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; + if (decorators || ts.hasDecorators(parameter)) { + if (!decorators) { + decorators = new Array(numParameters); + } + decorators[i] = ts.getDecorators(parameter); + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfClass(node) { + var decorators = ts.getDecorators(node); + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + ts.getAllDecoratorsOfClass = getAllDecoratorsOfClass; + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param parent The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(member, parent) { + switch (member.kind) { + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: + return getAllDecoratorsOfAccessors(member, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 167 /* SyntaxKind.PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + ts.getAllDecoratorsOfClassElement = getAllDecoratorsOfClassElement; + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param parent The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(accessor, parent) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(parent.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = ts.hasDecorators(firstAccessor) ? firstAccessor : + secondAccessor && ts.hasDecorators(secondAccessor) ? secondAccessor : + undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = ts.getDecorators(firstAccessorWithDecorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters, + getDecorators: getAccessor && ts.getDecorators(getAccessor), + setDecorators: setAccessor && ts.getDecorators(setAccessor) + }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = ts.getDecorators(method); + var parameters = getDecoratorsOfParameters(method); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = ts.getDecorators(property); + if (!ts.some(decorators)) { + return undefined; + } + return { decorators: decorators }; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -91011,8 +92424,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */ - && !(element.transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -91078,7 +92491,7 @@ var ts; if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -91300,8 +92713,6 @@ var ts; var USE_NEW_TYPE_METADATA_FORMAT = false; var TypeScriptSubstitutionFlags; (function (TypeScriptSubstitutionFlags) { - /** Enables substitutions for decorated classes. */ - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; /** Enables substitutions for namespace exports. */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; /* Enables substitutions for unqualified enum members */ @@ -91327,9 +92738,9 @@ var ts; var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); - var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var typeSerializer = compilerOptions.emitDecoratorMetadata ? ts.createRuntimeTypeSerializer(context) : undefined; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -91344,7 +92755,6 @@ var ts; var currentNamespace; var currentNamespaceContainerName; var currentLexicalScope; - var currentNameScope; var currentScopeFirstDeclarationsOfName; var currentClassHasParameterProperties; /** @@ -91352,11 +92762,6 @@ var ts; * They are persisted between each SourceFile transformation and should not be reset. */ var enabledSubstitutions; - /** - * A map that keeps track of aliases created for classes with decorators to avoid issues - * with the double-binding behavior of classes. - */ - var classAliases; /** * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. @@ -91400,7 +92805,6 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentLexicalScope; - var savedCurrentNameScope = currentNameScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties; // Handle state changes before visiting a node. @@ -91411,7 +92815,6 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } currentLexicalScope = savedCurrentScope; - currentNameScope = savedCurrentNameScope; currentClassHasParameterProperties = savedCurrentClassHasParameterProperties; return visited; } @@ -91427,7 +92830,6 @@ var ts; case 262 /* SyntaxKind.ModuleBlock */: case 235 /* SyntaxKind.Block */: currentLexicalScope = node; - currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; case 257 /* SyntaxKind.ClassDeclaration */: @@ -91445,10 +92847,6 @@ var ts; // programs may also have an undefined name. ts.Debug.assert(node.kind === 257 /* SyntaxKind.ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)); } - if (ts.isClassDeclaration(node)) { - // XXX: should probably also cover interfaces and type aliases that can have type variables? - currentNameScope = node; - } break; } } @@ -91550,40 +92948,73 @@ var ts; return node; } /** - * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * Gets a specialized visitor that visits the immediate children of a class with TypeScript syntax. * - * @param node The node to visit. + * @param parent The class containing the elements to visit. */ - function classElementVisitor(node) { - return saveStateAndInvoke(node, classElementVisitorWorker); + function getClassElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return classElementVisitorWorker(n, parent); }); }; } /** * Specialized visitor that visits the immediate children of a class with TypeScript syntax. * * @param node The node to visit. */ - function classElementVisitorWorker(node) { + function classElementVisitorWorker(node, parent) { switch (node.kind) { case 171 /* SyntaxKind.Constructor */: return visitConstructor(node); case 167 /* SyntaxKind.PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. - return visitPropertyDeclaration(node); - case 176 /* SyntaxKind.IndexSignature */: + return visitPropertyDeclaration(node, parent); case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - // Fallback to the default visit behavior. - return visitorWorker(node); + return ts.visitEachChild(node, visitor, context); case 234 /* SyntaxKind.SemicolonClassElement */: return node; + case 176 /* SyntaxKind.IndexSignature */: + // Index signatures are elided + return; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function getObjectLiteralElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return objectLiteralElementVisitorWorker(n, parent); }); }; + } + function objectLiteralElementVisitorWorker(node, parent) { + switch (node.kind) { + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 298 /* SyntaxKind.SpreadAssignment */: + return visitor(node); + case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); + case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { + if (ts.isDecorator(node)) + return undefined; if (ts.modifierToFlag(node.kind) & 116958 /* ModifierFlags.TypeScriptModifier */) { return undefined; } @@ -91651,22 +93082,14 @@ var ts; // TypeScript type nodes are elided. // falls through case 176 /* SyntaxKind.IndexSignature */: - // TypeScript index signatures are elided. - // falls through - case 165 /* SyntaxKind.Decorator */: - // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + // TypeScript index signatures are elided. return undefined; case 259 /* SyntaxKind.TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return factory.createNotEmittedStatement(node); - case 167 /* SyntaxKind.PropertyDeclaration */: - // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects - return visitPropertyDeclaration(node); case 264 /* SyntaxKind.NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 171 /* SyntaxKind.Constructor */: - return visitConstructor(node); case 258 /* SyntaxKind.InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. @@ -91700,16 +93123,15 @@ var ts; case 228 /* SyntaxKind.ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); + case 205 /* SyntaxKind.ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 171 /* SyntaxKind.Constructor */: + case 167 /* SyntaxKind.PropertyDeclaration */: case 169 /* SyntaxKind.MethodDeclaration */: - // TypeScript method declarations may have decorators, modifiers - // or type annotations. - return visitMethodDeclaration(node); case 172 /* SyntaxKind.GetAccessor */: - // Get Accessors can have TypeScript modifiers, decorators, and type annotations. - return visitGetAccessor(node); case 173 /* SyntaxKind.SetAccessor */: - // Set Accessors can have TypeScript modifiers and type annotations. - return visitSetAccessor(node); + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + return ts.Debug.fail("Class and object literal elements must be visited with their respective visitors"); case 256 /* SyntaxKind.FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); @@ -91775,6 +93197,9 @@ var ts; !ts.isJsonSourceFile(node); return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } + function visitObjectLiteralExpression(node) { + return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, getObjectLiteralElementVisitor(node), ts.isObjectLiteralElement)); + } function getClassFacts(node, staticProperties) { var facts = 0 /* ClassFacts.None */; if (ts.some(staticProperties)) @@ -91797,17 +93222,18 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { - return ts.some(node.decorators) + return ts.hasDecorators(node) || ts.some(node.typeParameters) || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) || ts.some(node.members, hasTypeScriptClassSyntax); } function visitClassDeclaration(node) { if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */))) { - return ts.visitEachChild(node, visitor, context); + return factory.updateClassDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); var facts = getClassFacts(node, staticProperties); @@ -91815,14 +93241,25 @@ var ts; context.startLexicalEnvironment(); } var name = node.name || (facts & 5 /* ClassFacts.NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined); - var classStatement = facts & 2 /* ClassFacts.HasConstructorDecorators */ - ? createClassDeclarationHeadWithDecorators(node, name) - : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : ts.elideNodes(factory, node.modifiers); // preserve positions, if available + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var classStatement = factory.updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { + emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; + } + ts.setEmitFlags(classStatement, emitFlags); var statements = [classStatement]; - // Write any decorators of the node. - addClassElementDecorationStatements(statements, node, /*isStatic*/ false); - addClassElementDecorationStatements(statements, node, /*isStatic*/ true); - addConstructorDecorationStatement(statements, node); if (facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) { // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the // 'es2015' transformer can properly nest static initializers and decorators. The result @@ -91882,164 +93319,13 @@ var ts; } return ts.singleOrMany(statements); } - /** - * Transforms a non-decorated class declaration and appends the resulting statements. - * - * @param node A ClassDeclaration node. - * @param name The name of the class. - * @param facts Precomputed facts about the class. - */ - function createClassDeclarationHeadWithoutDecorators(node, name, facts) { - // ${modifiers} class ${name} ${heritageClauses} { - // ${members} - // } - // we do not emit modifiers on the declaration if we are emitting an IIFE - var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) - ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) - : undefined; - var classDeclaration = factory.createClassDeclaration( - /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - // To better align with the old emitter, we should not emit a trailing source map - // entry if the class has static properties. - var emitFlags = ts.getEmitFlags(node); - if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { - emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; - } - ts.setTextRange(classDeclaration, node); - ts.setOriginalNode(classDeclaration, node); - ts.setEmitFlags(classDeclaration, emitFlags); - return classDeclaration; - } - /** - * Transforms a decorated class declaration and appends the resulting statements. If - * the class requires an alias to avoid issues with double-binding, the alias is returned. - */ - function createClassDeclarationHeadWithDecorators(node, name) { - // When we emit an ES6 class that has a class decorator, we must tailor the - // emit to certain specific cases. - // - // In the simplest case, we emit the class declaration as a let declaration, and - // evaluate decorators after the close of the class body: - // - // [Example 1] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // class C { | } - // } | C = __decorate([dec], C); - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | } - // } | C = __decorate([dec], C); - // | export { C }; - // --------------------------------------------------------------------- - // - // If a class declaration contains a reference to itself *inside* of the class body, - // this introduces two bindings to the class: One outside of the class body, and one - // inside of the class body. If we apply decorators as in [Example 1] above, there - // is the possibility that the decorator `dec` will return a new value for the - // constructor, which would result in the binding inside of the class no longer - // pointing to the same reference as the binding outside of the class. - // - // As a result, we must instead rewrite all references to the class *inside* of the - // class body to instead point to a local temporary alias for the class: - // - // [Example 2] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = C_1 = class C { - // class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | var C_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export { C }; - // | var C_1; - // --------------------------------------------------------------------- - // - // If a class declaration is the default export of a module, we instead emit - // the export after the decorated declaration: - // - // [Example 3] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let default_1 = class { - // export default class { | } - // } | default_1 = __decorate([dec], default_1); - // | export default default_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | } - // } | C = __decorate([dec], C); - // | export default C; - // --------------------------------------------------------------------- - // - // If the class declaration is the default export and a reference to itself - // inside of the class body, we must emit both an alias for the class *and* - // move the export after the declaration: - // - // [Example 4] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export default C; - // | var C_1; - // --------------------------------------------------------------------- - // - var location = ts.moveRangePastDecorators(node); - var classAlias = getClassAliasIfNeeded(node); - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - // ... = class ${name} ${heritageClauses} { - // ${members} - // } - var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node); - var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, location); - // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference - // or decoratedClassAlias if the class contain self-reference. - var statement = factory.createVariableStatement( - /*modifiers*/ undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(declName, - /*exclamationToken*/ undefined, - /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) - ], 1 /* NodeFlags.Let */)); - ts.setOriginalNode(statement, node); - ts.setTextRange(statement, location); - ts.setCommentRange(statement, node); - return statement; - } function visitClassExpression(node) { - if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { - return ts.visitEachChild(node, visitor, context); - } - var classExpression = factory.createClassExpression( - /*decorators*/ undefined, - /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, node); - return classExpression; + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + return factory.updateClassExpression(node, decorators, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), isClassLikeDeclarationWithTypeScriptSyntax(node) ? + transformClassMembers(node) : + ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } /** * Transforms the members of a class. @@ -92056,7 +93342,6 @@ var ts; var parameter = parametersWithPropertyAssignments_1[_i]; if (ts.isIdentifier(parameter.name)) { members.push(ts.setOriginalNode(factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameter.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -92064,159 +93349,9 @@ var ts; } } } - ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + ts.addRange(members, ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - /** - * Gets either the static or instance members of a class that are decorated, or have - * parameters that are decorated. - * - * @param node The class containing the member. - * @param isStatic A value indicating whether to retrieve static or instance members of - * the class. - */ - function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); - } - /** - * Determines whether a class member is a static member of a class that is decorated, or - * has parameters that are decorated. - * - * @param member The class member. - */ - function isStaticDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ true, parent); - } - /** - * Determines whether a class member is an instance member of a class that is decorated, - * or has parameters that are decorated. - * - * @param member The class member. - */ - function isInstanceDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ false, parent); - } - /** - * Determines whether a class member is either a static or an instance member of a class - * that is decorated, or has parameters that are decorated. - * - * @param member The class member. - */ - function isDecoratedClassElement(member, isStaticElement, parent) { - return ts.nodeOrChildIsDecorated(member, parent) - && isStaticElement === ts.isStatic(member); - } - /** - * Gets an array of arrays of decorators for the parameters of a function-like node. - * The offset into the result array should correspond to the offset of the parameter. - * - * @param node The function-like node. - */ - function getDecoratorsOfParameters(node) { - var decorators; - if (node) { - var parameters = node.parameters; - var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); - var firstParameterOffset = firstParameterIsThis ? 1 : 0; - var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i + firstParameterOffset]; - if (decorators || parameter.decorators) { - if (!decorators) { - decorators = new Array(numParameters); - } - decorators[i] = parameter.decorators; - } - } - } - return decorators; - } - /** - * Gets an AllDecorators object containing the decorators for the class and the decorators for the - * parameters of the constructor of the class. - * - * @param node The class node. - */ - function getAllDecoratorsOfConstructor(node) { - var decorators = node.decorators; - var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); - if (!decorators && !parameters) { - return undefined; - } - return { - decorators: decorators, - parameters: parameters - }; - } - /** - * Gets an AllDecorators object containing the decorators for the member and its parameters. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function getAllDecoratorsOfClassElement(node, member) { - switch (member.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - return getAllDecoratorsOfAccessors(node, member); - case 169 /* SyntaxKind.MethodDeclaration */: - return getAllDecoratorsOfMethod(member); - case 167 /* SyntaxKind.PropertyDeclaration */: - return getAllDecoratorsOfProperty(member); - default: - return undefined; - } - } - /** - * Gets an AllDecorators object containing the decorators for the accessor and its parameters. - * - * @param node The class node that contains the accessor. - * @param accessor The class accessor member. - */ - function getAllDecoratorsOfAccessors(node, accessor) { - if (!accessor.body) { - return undefined; - } - var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; - if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { - return undefined; - } - var decorators = firstAccessorWithDecorators.decorators; - var parameters = getDecoratorsOfParameters(setAccessor); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the method and its parameters. - * - * @param method The class method member. - */ - function getAllDecoratorsOfMethod(method) { - if (!method.body) { - return undefined; - } - var decorators = method.decorators; - var parameters = getDecoratorsOfParameters(method); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the property. - * - * @param property The class property member. - */ - function getAllDecoratorsOfProperty(property) { - var decorators = property.decorators; - if (!decorators) { - return undefined; - } - return { decorators: decorators }; - } /** * Transforms all of the decorators for a declaration into an array of expressions. * @@ -92224,212 +93359,89 @@ var ts; * @param allDecorators An object containing all of the decorators for the declaration. */ function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + var _a, _b, _c, _d; if (!allDecorators) { return undefined; } - var decoratorExpressions = []; - ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); - ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, container, decoratorExpressions); - return decoratorExpressions; - } - /** - * Generates statements used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate statements for static or - * instance members. - */ - function addClassElementDecorationStatements(statements, node, isStatic) { - ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); - } - /** - * Generates expressions used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate expressions for static or - * instance members. - */ - function generateClassElementDecorationExpressions(node, isStatic) { - var members = getDecoratedClassElements(node, isStatic); - var expressions; - for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { - var member = members_8[_i]; - var expression = generateClassElementDecorationExpression(node, member); - if (expression) { - if (!expressions) { - expressions = [expression]; - } - else { - expressions.push(expression); - } - } - } - return expressions; - } - /** - * Generates an expression used to evaluate class element decorators at runtime. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function generateClassElementDecorationExpression(node, member) { - var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - // Emit the call to __decorate. Given the following: - // - // class C { - // @dec method(@dec2 x) {} - // @dec get accessor() {} - // @dec prop; - // } - // - // The emit for a method is: - // - // __decorate([ - // dec, - // __param(0, dec2), - // __metadata("design:type", Function), - // __metadata("design:paramtypes", [Object]), - // __metadata("design:returntype", void 0) - // ], C.prototype, "method", null); - // - // The emit for an accessor is: - // - // __decorate([ - // dec - // ], C.prototype, "accessor", null); - // - // The emit for a property is: - // - // __decorate([ - // dec - // ], C.prototype, "prop"); - // - var prefix = getClassMemberPrefix(node, member); - var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); - var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ - ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ - // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it - // should not invoke `Object.getOwnPropertyDescriptor`. - ? factory.createVoidZero() - // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. - // We have this extra argument here so that we can inject an explicit property descriptor at a later date. - : factory.createNull() - : undefined; - var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); - ts.setTextRange(helper, ts.moveRangePastDecorators(member)); - ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - return helper; - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function addConstructorDecorationStatement(statements, node) { - var expression = generateConstructorDecorationExpression(node); - if (expression) { - statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); - } - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function generateConstructorDecorationExpression(node) { - var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); - var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); - ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); - ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); - return expression; - } - /** - * Transforms a decorator into an expression. - * - * @param decorator The decorator node. - */ - function transformDecorator(decorator) { - return ts.visitNode(decorator.expression, visitor, ts.isExpression); + var decorators = ts.visitArray(allDecorators.decorators, visitor, ts.isDecorator); + var parameterDecorators = ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter); + var metadataDecorators = ts.some(decorators) || ts.some(parameterDecorators) ? getTypeMetadata(node, container) : undefined; + var result = factory.createNodeArray(ts.concatenate(ts.concatenate(decorators, parameterDecorators), metadataDecorators)); + var pos = (_b = (_a = ts.firstOrUndefined(allDecorators.decorators)) === null || _a === void 0 ? void 0 : _a.pos) !== null && _b !== void 0 ? _b : -1; + var end = (_d = (_c = ts.lastOrUndefined(allDecorators.decorators)) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : -1; + ts.setTextRangePosEnd(result, pos, end); + return result; } /** - * Transforms the decorators of a parameter. + * Transforms the decorators of a parameter into decorators of the class/method. * - * @param decorators The decorators for the parameter at the provided offset. + * @param parameterDecorators The decorators for the parameter at the provided offset. * @param parameterOffset The offset of the parameter. */ - function transformDecoratorsOfParameter(decorators, parameterOffset) { - var expressions; - if (decorators) { - expressions = []; - for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { - var decorator = decorators_1[_i]; - var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); - ts.setTextRange(helper, decorator.expression); + function transformDecoratorsOfParameter(parameterDecorators, parameterOffset) { + if (parameterDecorators) { + var decorators = []; + for (var _i = 0, parameterDecorators_1 = parameterDecorators; _i < parameterDecorators_1.length; _i++) { + var parameterDecorator = parameterDecorators_1[_i]; + var expression = ts.visitNode(parameterDecorator.expression, visitor, ts.isExpression); + var helper = emitHelpers().createParamHelper(expression, parameterOffset); + ts.setTextRange(helper, parameterDecorator.expression); ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - expressions.push(helper); + var decorator = factory.createDecorator(helper); + ts.setSourceMapRange(decorator, parameterDecorator.expression); + ts.setCommentRange(decorator, parameterDecorator.expression); + ts.setEmitFlags(decorator, 1536 /* EmitFlags.NoComments */); + decorators.push(decorator); } + return decorators; } - return expressions; } /** - * Adds optional type metadata for a declaration. + * Gets optional type metadata for a declaration. * * @param node The declaration node. - * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node, container, decoratorExpressions) { - if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, container, decoratorExpressions); - } - else { - addOldTypeMetadata(node, container, decoratorExpressions); - } + function getTypeMetadata(node, container) { + return USE_NEW_TYPE_METADATA_FORMAT ? + getNewTypeMetadata(node, container) : + getOldTypeMetadata(node, container); } - function addOldTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getOldTypeMetadata(node, container) { + if (typeSerializer) { + var decorators = void 0; if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node))); + var typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(typeMetadata)); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container))); + var paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container)); + decorators = ts.append(decorators, factory.createDecorator(paramTypesMetadata)); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node))); + var returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(returnTypeMetadata)); } + return decorators; } } - function addNewTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getNewTypeMetadata(node, container) { + if (typeSerializer) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + var typeProperty = factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, typeProperty); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + var paramTypeProperty = factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container))); + properties = ts.append(properties, paramTypeProperty); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + var returnTypeProperty = factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, returnTypeProperty); } if (properties) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true))); + var typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)); + return [factory.createDecorator(typeInfoMetadata)]; } } } @@ -92476,347 +93488,6 @@ var ts; } return false; } - function getAccessorTypeNode(node) { - var accessors = resolver.getAllAccessorDeclarations(node); - return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) - || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); - } - /** - * Serializes the type of a node for use with decorator type metadata. - * - * @param node The node that should have its type serialized. - */ - function serializeTypeOfNode(node) { - switch (node.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 164 /* SyntaxKind.Parameter */: - return serializeTypeNode(node.type); - case 173 /* SyntaxKind.SetAccessor */: - case 172 /* SyntaxKind.GetAccessor */: - return serializeTypeNode(getAccessorTypeNode(node)); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - return factory.createIdentifier("Function"); - default: - return factory.createVoidZero(); - } - } - /** - * Serializes the types of the parameters of a node for use with decorator type metadata. - * - * @param node The node that should have its parameter types serialized. - */ - function serializeParameterTypesOfNode(node, container) { - var valueDeclaration = ts.isClassLike(node) - ? ts.getFirstConstructorWithBody(node) - : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) - ? node - : undefined; - var expressions = []; - if (valueDeclaration) { - var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); - var numParameters = parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { - continue; - } - if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); - } - else { - expressions.push(serializeTypeOfNode(parameter)); - } - } - } - return factory.createArrayLiteralExpression(expressions); - } - function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { - var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; - if (setAccessor) { - return setAccessor.parameters; - } - } - return node.parameters; - } - /** - * Serializes the return type of a node for use with decorator type metadata. - * - * @param node The node that should have its return type serialized. - */ - function serializeReturnTypeOfNode(node) { - if (ts.isFunctionLike(node) && node.type) { - return serializeTypeNode(node.type); - } - else if (ts.isAsyncFunction(node)) { - return factory.createIdentifier("Promise"); - } - return factory.createVoidZero(); - } - /** - * Serializes a type node for use with decorator type metadata. - * - * Types are serialized in the following fashion: - * - Void types point to "undefined" (e.g. "void 0") - * - Function and Constructor types point to the global "Function" constructor. - * - Interface types with a call or construct signature types point to the global - * "Function" constructor. - * - Array and Tuple types point to the global "Array" constructor. - * - Type predicates and booleans point to the global "Boolean" constructor. - * - String literal types and strings point to the global "String" constructor. - * - Enum and number types point to the global "Number" constructor. - * - Symbol types point to the global "Symbol" constructor. - * - Type references to classes (or class-like variables) point to the constructor for the class. - * - Anything else points to the global "Object" constructor. - * - * @param node The type node to serialize. - */ - function serializeTypeNode(node) { - if (node === undefined) { - return factory.createIdentifier("Object"); - } - switch (node.kind) { - case 114 /* SyntaxKind.VoidKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - return factory.createVoidZero(); - case 191 /* SyntaxKind.ParenthesizedType */: - return serializeTypeNode(node.type); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - return factory.createIdentifier("Function"); - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: - return factory.createIdentifier("Array"); - case 177 /* SyntaxKind.TypePredicate */: - case 133 /* SyntaxKind.BooleanKeyword */: - return factory.createIdentifier("Boolean"); - case 198 /* SyntaxKind.TemplateLiteralType */: - case 150 /* SyntaxKind.StringKeyword */: - return factory.createIdentifier("String"); - case 148 /* SyntaxKind.ObjectKeyword */: - return factory.createIdentifier("Object"); - case 196 /* SyntaxKind.LiteralType */: - switch (node.literal.kind) { - case 10 /* SyntaxKind.StringLiteral */: - case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: - return factory.createIdentifier("String"); - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 8 /* SyntaxKind.NumericLiteral */: - return factory.createIdentifier("Number"); - case 9 /* SyntaxKind.BigIntLiteral */: - return getGlobalBigIntNameWithFallback(); - case 110 /* SyntaxKind.TrueKeyword */: - case 95 /* SyntaxKind.FalseKeyword */: - return factory.createIdentifier("Boolean"); - case 104 /* SyntaxKind.NullKeyword */: - return factory.createVoidZero(); - default: - return ts.Debug.failBadSyntaxKind(node.literal); - } - case 147 /* SyntaxKind.NumberKeyword */: - return factory.createIdentifier("Number"); - case 158 /* SyntaxKind.BigIntKeyword */: - return getGlobalBigIntNameWithFallback(); - case 151 /* SyntaxKind.SymbolKeyword */: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case 178 /* SyntaxKind.TypeReference */: - return serializeTypeReferenceNode(node); - case 188 /* SyntaxKind.IntersectionType */: - case 187 /* SyntaxKind.UnionType */: - return serializeTypeList(node.types); - case 189 /* SyntaxKind.ConditionalType */: - return serializeTypeList([node.trueType, node.falseType]); - case 193 /* SyntaxKind.TypeOperator */: - if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { - return serializeTypeNode(node.type); - } - break; - case 181 /* SyntaxKind.TypeQuery */: - case 194 /* SyntaxKind.IndexedAccessType */: - case 195 /* SyntaxKind.MappedType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 192 /* SyntaxKind.ThisType */: - case 200 /* SyntaxKind.ImportType */: - break; - // handle JSDoc types from an invalid parse - case 312 /* SyntaxKind.JSDocAllType */: - case 313 /* SyntaxKind.JSDocUnknownType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 318 /* SyntaxKind.JSDocVariadicType */: - case 319 /* SyntaxKind.JSDocNamepathType */: - break; - case 314 /* SyntaxKind.JSDocNullableType */: - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 316 /* SyntaxKind.JSDocOptionalType */: - return serializeTypeNode(node.type); - default: - return ts.Debug.failBadSyntaxKind(node); - } - return factory.createIdentifier("Object"); - } - function serializeTypeList(types) { - // Note when updating logic here also update getEntityNameForDecoratorMetadata - // so that aliases can be marked as referenced - var serializedUnion; - for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { - var typeNode = types_23[_i]; - while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 196 /* SyntaxKind.LiteralType */ && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */ || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { - // One of the individual is global object, return immediately - return serializedIndividual; - } - // If there exists union that is not void 0 expression, check if the the common type is identifier. - // anything more complex and we will just default to Object - else if (serializedUnion) { - // Different types - if (!ts.isIdentifier(serializedUnion) || - !ts.isIdentifier(serializedIndividual) || - serializedUnion.escapedText !== serializedIndividual.escapedText) { - return factory.createIdentifier("Object"); - } - } - else { - // Initialize the union type - serializedUnion = serializedIndividual; - } - } - // If we were able to find common type, use it - return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never - } - /** - * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with - * decorator type metadata. - * - * @param node The type reference node. - */ - function serializeTypeReferenceNode(node) { - var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); - switch (kind) { - case ts.TypeReferenceSerializationKind.Unknown: - // From conditional type type reference that cannot be resolved is Similar to any or unknown - if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { - return factory.createIdentifier("Object"); - } - var serialized = serializeEntityNameAsExpressionFallback(node.typeName); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), - /*questionToken*/ undefined, temp, - /*colonToken*/ undefined, factory.createIdentifier("Object")); - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName); - case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: - return factory.createVoidZero(); - case ts.TypeReferenceSerializationKind.BigIntLikeType: - return getGlobalBigIntNameWithFallback(); - case ts.TypeReferenceSerializationKind.BooleanType: - return factory.createIdentifier("Boolean"); - case ts.TypeReferenceSerializationKind.NumberLikeType: - return factory.createIdentifier("Number"); - case ts.TypeReferenceSerializationKind.StringLikeType: - return factory.createIdentifier("String"); - case ts.TypeReferenceSerializationKind.ArrayLikeType: - return factory.createIdentifier("Array"); - case ts.TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - return factory.createIdentifier("Function"); - case ts.TypeReferenceSerializationKind.Promise: - return factory.createIdentifier("Promise"); - case ts.TypeReferenceSerializationKind.ObjectType: - return factory.createIdentifier("Object"); - default: - return ts.Debug.assertNever(kind); - } - } - function createCheckedValue(left, right) { - return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right); - } - /** - * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 79 /* SyntaxKind.Identifier */) { - // A -> typeof A !== undefined && A - var copied = serializeEntityNameAsExpression(node); - return createCheckedValue(copied, copied); - } - if (node.left.kind === 79 /* SyntaxKind.Identifier */) { - // A.B -> typeof A !== undefined && A.B - return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); - } - // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C - var left = serializeEntityNameAsExpressionFallback(node.left); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right)); - } - /** - * Serializes an entity name as an expression for decorator type metadata. - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpression(node) { - switch (node.kind) { - case 79 /* SyntaxKind.Identifier */: - // Create a clone of the name with a new parent, and treat it as if it were - // a source tree node for the purposes of the checker. - var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); - name.original = undefined; - ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. - return name; - case 161 /* SyntaxKind.QualifiedName */: - return serializeQualifiedNameAsExpression(node); - } - } - /** - * Serializes an qualified name as an expression for decorator type metadata. - * - * @param node The qualified name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * qualified name at runtime. - */ - function serializeQualifiedNameAsExpression(node) { - return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); - } - /** - * Gets an expression that points to the global "Symbol" constructor at runtime if it is - * available. - */ - function getGlobalSymbolNameWithFallback() { - return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("Symbol"), - /*colonToken*/ undefined, factory.createIdentifier("Object")); - } - /** - * Gets an expression that points to the global "BigInt" constructor at runtime if it is - * available. - */ - function getGlobalBigIntNameWithFallback() { - return languageVersion < 99 /* ScriptTarget.ESNext */ - ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("BigInt"), - /*colonToken*/ undefined, factory.createIdentifier("Object")) - : factory.createIdentifier("BigInt"); - } /** * Gets an expression that represents a property name (for decorated properties or enums). * For a computed property, a name is generated for the node. @@ -92853,7 +93524,7 @@ var ts; // The names are used more than once when: // - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments). // - the property has a decorator. - if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) { + if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.hasDecorators(member))) { var expression = ts.visitNode(name.expression, visitor, ts.isExpression); var innerExpression = ts.skipPartiallyEmittedExpressions(expression); if (!ts.isSimpleInlineableExpression(innerExpression)) { @@ -92901,28 +93572,29 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } - function visitPropertyDeclaration(node) { - if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)) { + function visitPropertyDeclaration(node, parent) { + var isAmbient = node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */); + if (isAmbient && !ts.hasDecorators(node)) { return undefined; } - var updated = factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), + var allDecorators = ts.getAllDecoratorsOfClassElement(node, parent); + var decorators = transformAllDecoratorsOfDeclaration(node, parent, allDecorators); + // Preserve a `declare x` property with decorators to be handled by the decorators transform + if (isAmbient) { + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, factory.createModifiersFromModifierFlags(2 /* ModifierFlags.Ambient */)), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } return factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node)); } function transformConstructorBody(body, constructor) { @@ -92961,7 +93633,8 @@ var ts; statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, prologueStatementCount), true), parameterPropertyAssignments, true), statements.slice(prologueStatementCount), true); } // Add remaining statements from the body, skipping the super() call if it was found and any (already added) prologue statements - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, superStatementIndex + 1 + prologueStatementCount)); + var start = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, start)); // End the lexical environment. statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true); @@ -92987,22 +93660,19 @@ var ts; ts.setEmitFlags(localName, 1536 /* EmitFlags.NoComments */); return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(factory.createExpressionStatement(factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1)))); } - function visitMethodDeclaration(node) { + function visitMethodDeclaration(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + var allDecorators = ts.isClassLike(parent) ? ts.getAllDecoratorsOfClassElement(node, parent) : undefined; + var decorators = ts.isClassLike(parent) ? transformAllDecoratorsOfDeclaration(node, parent, allDecorators) : undefined; + return factory.updateMethodDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), node.asteriskToken, visitPropertyNameOfClassElement(node), /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } /** * Determines whether to emit an accessor declaration. We should not emit the @@ -93013,41 +93683,36 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)); } - function visitGetAccessor(node) { + function visitGetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateGetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } - function visitSetAccessor(node) { + function visitSetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateSetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return factory.createNotEmittedStatement(node); } - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + var updated = factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); if (isExportOfNamespace(node)) { @@ -93076,9 +93741,8 @@ var ts; if (ts.parameterIsThisKeyword(node)) { return undefined; } - var updated = factory.updateParameterDeclaration(node, - /*decorators*/ undefined, - /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), // preserve positions, if available + node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); if (updated !== node) { @@ -93238,7 +93902,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); @@ -93468,7 +94132,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); @@ -93581,7 +94245,6 @@ var ts; compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ ? factory.updateImportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, importClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -93656,7 +94319,6 @@ var ts; var exportClause = ts.visitNode(node.exportClause, function (bindings) { return visitNamedExportBindings(bindings, allowEmpty); }, ts.isNamedExportBindings); return exportClause ? factory.updateExportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -93714,7 +94376,6 @@ var ts; // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'. if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */) { return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, node.moduleReference.expression, /*assertClause*/ undefined), node), node); @@ -93774,12 +94435,6 @@ var ts; return isExternalModuleExport(node) && ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */); } - /** - * Creates a statement for the provided expression. This is used in calls to `map`. - */ - function expressionToStatement(expression) { - return factory.createExpressionStatement(expression); - } function addExportMemberAssignment(statements, node) { var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); @@ -93811,44 +94466,12 @@ var ts; function getNamespaceContainerName(node) { return factory.getGeneratedNameForNode(node); } - /** - * Gets a local alias for a class declaration if it is a decorated class with an internal - * reference to the static side of the class. This is necessary to avoid issues with - * double-binding semantics for the class name. - */ - function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { - enableSubstitutionForClassAliases(); - var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - hoistVariableDeclaration(classAlias); - return classAlias; - } - } - function getClassPrototype(node) { - return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); - } - function getClassMemberPrefix(node, member) { - return ts.isStatic(member) - ? factory.getDeclarationName(node) - : getClassPrototype(node); - } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */; context.enableSubstitution(79 /* SyntaxKind.Identifier */); } } - function enableSubstitutionForClassAliases() { - if ((enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) === 0) { - enabledSubstitutions |= 1 /* TypeScriptSubstitutionFlags.ClassAliases */; - // We need to enable substitutions for identifiers. This allows us to - // substitute class names inside of a class declaration. - context.enableSubstitution(79 /* SyntaxKind.Identifier */); - // Keep track of class aliases. - classAliases = []; - } - } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2 /* TypeScriptSubstitutionFlags.NamespaceExports */) === 0) { enabledSubstitutions |= 2 /* TypeScriptSubstitutionFlags.NamespaceExports */; @@ -93933,32 +94556,9 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - return trySubstituteClassAlias(node) - || trySubstituteNamespaceExportedName(node) + return trySubstituteNamespaceExportedName(node) || node; } - function trySubstituteClassAlias(node) { - if (enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - // Also, when emitting statics for class expressions, we must substitute a class alias for - // constructor references in static property initializers. - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = classAliases[declaration.id]; // TODO: GH#18217 - if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; - } - } - } - } - return undefined; - } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { @@ -94096,7 +94696,7 @@ var ts; return visited; } function visitorWorker(node, valueIsDiscarded) { - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */) { + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */) { switch (node.kind) { case 226 /* SyntaxKind.ClassExpression */: case 257 /* SyntaxKind.ClassDeclaration */: @@ -94111,8 +94711,8 @@ var ts; return visitClassStaticBlockDeclaration(node); } } - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */ || - node.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */ && + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */ || + node.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */ && shouldTransformSuperInStaticInitializers && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { @@ -94252,7 +94852,7 @@ var ts; return node; } function visitMethodOrAccessorDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.isPrivateIdentifier(node.name)) { return ts.visitEachChild(node, classElementVisitor, context); } @@ -94264,7 +94864,7 @@ var ts; } var functionName = getHoistedFunctionName(node); if (functionName) { - getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return ts.isModifier(m) && !ts.isStaticModifier(m); }), node.asteriskToken, functionName, /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); } @@ -94288,7 +94888,7 @@ var ts; } } function visitPropertyDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (ts.isPrivateIdentifier(node.name)) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { if (ts.isStatic(node)) { @@ -94296,8 +94896,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + return factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); @@ -94319,9 +94918,7 @@ var ts; if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); if (initializerStatement) { - var staticBlock = factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([initializerStatement])); + var staticBlock = factory.createClassStaticBlockDeclaration(factory.createBlock([initializerStatement])); ts.setOriginalNode(staticBlock, node); ts.setCommentRange(staticBlock, node); // Set the comment range for the statement to an empty synthetic range @@ -94397,10 +94994,11 @@ var ts; } function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) { if (node.operator === 45 /* SyntaxKind.PlusPlusToken */ || node.operator === 46 /* SyntaxKind.MinusMinusToken */) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + var operand = ts.skipParentheses(node.operand); + if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(operand)) { var info = void 0; - if (info = accessPrivateIdentifier(node.operand.name)) { - var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression); + if (info = accessPrivateIdentifier(operand.name)) { + var receiver = ts.visitNode(operand.expression, visitor, ts.isExpression); var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; var expression = createPrivateIdentifierAccess(info, readExpression); var temp = ts.isPrefixUnaryExpression(node) || valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); @@ -94416,7 +95014,7 @@ var ts; } } else if (shouldTransformSuperInStaticInitializers && - ts.isSuperProperty(node.operand) && + ts.isSuperProperty(operand) && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { // converts `++super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = ++_a), _classTemp), _b)` @@ -94429,31 +95027,31 @@ var ts; // converts `super[f()]--` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = _b--), _classTemp), _c)` var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; if (facts & 1 /* ClassFacts.ClassWasDecorated */) { - var operand = visitInvalidSuperProperty(node.operand); + var expression = visitInvalidSuperProperty(operand); return ts.isPrefixUnaryExpression(node) ? - factory.updatePrefixUnaryExpression(node, operand) : - factory.updatePostfixUnaryExpression(node, operand); + factory.updatePrefixUnaryExpression(node, expression) : + factory.updatePostfixUnaryExpression(node, expression); } if (classConstructor && superClassReference) { var setterName = void 0; var getterName = void 0; - if (ts.isPropertyAccessExpression(node.operand)) { - if (ts.isIdentifier(node.operand.name)) { - getterName = setterName = factory.createStringLiteralFromNode(node.operand.name); + if (ts.isPropertyAccessExpression(operand)) { + if (ts.isIdentifier(operand.name)) { + getterName = setterName = factory.createStringLiteralFromNode(operand.name); } } else { - if (ts.isSimpleInlineableExpression(node.operand.argumentExpression)) { - getterName = setterName = node.operand.argumentExpression; + if (ts.isSimpleInlineableExpression(operand.argumentExpression)) { + getterName = setterName = operand.argumentExpression; } else { getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, ts.visitNode(node.operand.argumentExpression, visitor, ts.isExpression)); + setterName = factory.createAssignment(getterName, ts.visitNode(operand.argumentExpression, visitor, ts.isExpression)); } } if (setterName && getterName) { var expression = factory.createReflectGetCall(superClassReference, getterName, classConstructor); - ts.setTextRange(expression, node.operand); + ts.setTextRange(expression, operand); var temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); expression = ts.expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp); expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor); @@ -94686,13 +95284,13 @@ var ts; facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } if (ts.isPropertyDeclaration(member) || ts.isClassStaticBlockDeclaration(member)) { - if (shouldTransformThisInStaticInitializers && member.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */) { + if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */) { facts |= 8 /* ClassFacts.NeedsSubstitutionForThisInClassStaticField */; if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } } - if (shouldTransformSuperInStaticInitializers && member.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */) { + if (shouldTransformSuperInStaticInitializers && member.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */) { if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */ | 4 /* ClassFacts.NeedsClassSuperReference */; } @@ -94730,8 +95328,7 @@ var ts; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* SyntaxKind.NullKeyword */); var statements = [ - factory.updateClassDeclaration(node, - /*decorators*/ undefined, node.modifiers, node.name, + factory.updateClassDeclaration(node, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; if (pendingClassReferenceAssignment) { @@ -94783,7 +95380,7 @@ var ts; temp = createClassTempVar(); getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); } - var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, + var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || ts.isPrivateIdentifier(p.name); }); if (hasTransformableStatics || ts.some(pendingExpressions)) { @@ -94851,9 +95448,7 @@ var ts; members.push(constructor); } if (!shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(pendingExpressions)) { - members.push(factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([ + members.push(factory.createClassStaticBlockDeclaration(factory.createBlock([ factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)) ]))); pendingExpressions = undefined; @@ -94890,7 +95485,6 @@ var ts; return undefined; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { @@ -95277,10 +95871,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_3 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_3, node); - ts.setCommentRange(clone_3, node); - return clone_3; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -95642,6 +96236,1001 @@ var ts; })(ts || (ts = {})); /*@internal*/ var ts; +(function (ts) { + function createRuntimeTypeSerializer(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var currentLexicalScope; + var currentNameScope; + return { + serializeTypeNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeNode, node); }, + serializeTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeOfNode, node); }, + serializeParameterTypesOfNode: function (serializerContext, node, container) { return setSerializerContextAnd(serializerContext, serializeParameterTypesOfNode, node, container); }, + serializeReturnTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeReturnTypeOfNode, node); }, + }; + function setSerializerContextAnd(serializerContext, cb, node, arg) { + var savedCurrentLexicalScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + currentLexicalScope = serializerContext.currentLexicalScope; + currentNameScope = serializerContext.currentNameScope; + var result = arg === undefined ? cb(node) : cb(node, arg); + currentLexicalScope = savedCurrentLexicalScope; + currentNameScope = savedCurrentNameScope; + return result; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 167 /* SyntaxKind.PropertyDeclaration */: + case 164 /* SyntaxKind.Parameter */: + return serializeTypeNode(node.type); + case 173 /* SyntaxKind.SetAccessor */: + case 172 /* SyntaxKind.GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 169 /* SyntaxKind.MethodDeclaration */: + return ts.factory.createIdentifier("Function"); + default: + return ts.factory.createVoidZero(); + } + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.factory.createArrayLiteralExpression(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.factory.createIdentifier("Promise"); + } + return ts.factory.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.factory.createIdentifier("Object"); + } + node = ts.skipTypeParentheses(node); + switch (node.kind) { + case 114 /* SyntaxKind.VoidKeyword */: + case 153 /* SyntaxKind.UndefinedKeyword */: + case 143 /* SyntaxKind.NeverKeyword */: + return ts.factory.createVoidZero(); + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + return ts.factory.createIdentifier("Function"); + case 183 /* SyntaxKind.ArrayType */: + case 184 /* SyntaxKind.TupleType */: + return ts.factory.createIdentifier("Array"); + case 177 /* SyntaxKind.TypePredicate */: + return node.assertsModifier ? + ts.factory.createVoidZero() : + ts.factory.createIdentifier("Boolean"); + case 133 /* SyntaxKind.BooleanKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 198 /* SyntaxKind.TemplateLiteralType */: + case 150 /* SyntaxKind.StringKeyword */: + return ts.factory.createIdentifier("String"); + case 148 /* SyntaxKind.ObjectKeyword */: + return ts.factory.createIdentifier("Object"); + case 196 /* SyntaxKind.LiteralType */: + return serializeLiteralOfLiteralTypeNode(node.literal); + case 147 /* SyntaxKind.NumberKeyword */: + return ts.factory.createIdentifier("Number"); + case 158 /* SyntaxKind.BigIntKeyword */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 151 /* SyntaxKind.SymbolKeyword */: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case 178 /* SyntaxKind.TypeReference */: + return serializeTypeReferenceNode(node); + case 188 /* SyntaxKind.IntersectionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ true); + case 187 /* SyntaxKind.UnionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ false); + case 189 /* SyntaxKind.ConditionalType */: + return serializeUnionOrIntersectionConstituents([node.trueType, node.falseType], /*isIntersection*/ false); + case 193 /* SyntaxKind.TypeOperator */: + if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { + return serializeTypeNode(node.type); + } + break; + case 181 /* SyntaxKind.TypeQuery */: + case 194 /* SyntaxKind.IndexedAccessType */: + case 195 /* SyntaxKind.MappedType */: + case 182 /* SyntaxKind.TypeLiteral */: + case 130 /* SyntaxKind.AnyKeyword */: + case 155 /* SyntaxKind.UnknownKeyword */: + case 192 /* SyntaxKind.ThisType */: + case 200 /* SyntaxKind.ImportType */: + break; + // handle JSDoc types from an invalid parse + case 312 /* SyntaxKind.JSDocAllType */: + case 313 /* SyntaxKind.JSDocUnknownType */: + case 317 /* SyntaxKind.JSDocFunctionType */: + case 318 /* SyntaxKind.JSDocVariadicType */: + case 319 /* SyntaxKind.JSDocNamepathType */: + break; + case 314 /* SyntaxKind.JSDocNullableType */: + case 315 /* SyntaxKind.JSDocNonNullableType */: + case 316 /* SyntaxKind.JSDocOptionalType */: + return serializeTypeNode(node.type); + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.factory.createIdentifier("Object"); + } + function serializeLiteralOfLiteralTypeNode(node) { + switch (node.kind) { + case 10 /* SyntaxKind.StringLiteral */: + case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: + return ts.factory.createIdentifier("String"); + case 219 /* SyntaxKind.PrefixUnaryExpression */: { + var operand = node.operand; + switch (operand.kind) { + case 8 /* SyntaxKind.NumericLiteral */: + case 9 /* SyntaxKind.BigIntLiteral */: + return serializeLiteralOfLiteralTypeNode(operand); + default: + return ts.Debug.failBadSyntaxKind(operand); + } + } + case 8 /* SyntaxKind.NumericLiteral */: + return ts.factory.createIdentifier("Number"); + case 9 /* SyntaxKind.BigIntLiteral */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 110 /* SyntaxKind.TrueKeyword */: + case 95 /* SyntaxKind.FalseKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 104 /* SyntaxKind.NullKeyword */: + return ts.factory.createVoidZero(); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function serializeUnionOrIntersectionConstituents(types, isIntersection) { + // Note when updating logic here also update `getEntityNameForDecoratorMetadata` in checker.ts so that aliases can be marked as referenced + var serializedType; + for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { + var typeNode = types_22[_i]; + typeNode = ts.skipTypeParentheses(typeNode); + if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { + if (isIntersection) + return ts.factory.createVoidZero(); // Reduce to `never` in an intersection + continue; // Elide `never` in a union + } + if (typeNode.kind === 155 /* SyntaxKind.UnknownKeyword */) { + if (!isIntersection) + return ts.factory.createIdentifier("Object"); // Reduce to `unknown` in a union + continue; // Elide `unknown` in an intersection + } + if (typeNode.kind === 130 /* SyntaxKind.AnyKeyword */) { + return ts.factory.createIdentifier("Object"); // Reduce to `any` in a union or intersection + } + if (!strictNullChecks && ((ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */) || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedConstituent = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedConstituent; + } + // If there exists union that is not `void 0` expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + if (serializedType) { + // Different types + if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) { + return ts.factory.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedType = serializedConstituent; + } + } + // If we were able to find common type, use it + return serializedType !== null && serializedType !== void 0 ? serializedType : (ts.factory.createVoidZero()); // Fallback is only hit if all union constituents are null/undefined/never + } + function equateSerializedTypeNodes(left, right) { + return ( + // temp vars used in fallback + ts.isGeneratedIdentifier(left) ? ts.isGeneratedIdentifier(right) : + // entity names + ts.isIdentifier(left) ? ts.isIdentifier(right) + && left.escapedText === right.escapedText : + ts.isPropertyAccessExpression(left) ? ts.isPropertyAccessExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) + && equateSerializedTypeNodes(left.name, right.name) : + // `void 0` + ts.isVoidExpression(left) ? ts.isVoidExpression(right) + && ts.isNumericLiteral(left.expression) && left.expression.text === "0" + && ts.isNumericLiteral(right.expression) && right.expression.text === "0" : + // `"undefined"` or `"function"` in `typeof` checks + ts.isStringLiteral(left) ? ts.isStringLiteral(right) + && left.text === right.text : + // used in `typeof` checks for fallback + ts.isTypeOfExpression(left) ? ts.isTypeOfExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // parens in `typeof` checks with temps + ts.isParenthesizedExpression(left) ? ts.isParenthesizedExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // conditionals used in fallback + ts.isConditionalExpression(left) ? ts.isConditionalExpression(right) + && equateSerializedTypeNodes(left.condition, right.condition) + && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) + && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : + // logical binary and assignments used in fallback + ts.isBinaryExpression(left) ? ts.isBinaryExpression(right) + && left.operatorToken.kind === right.operatorToken.kind + && equateSerializedTypeNodes(left.left, right.left) + && equateSerializedTypeNodes(left.right, right.right) : + false); + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with decorator type metadata. + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope !== null && currentNameScope !== void 0 ? currentNameScope : currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.factory.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createAssignment(temp, serialized), "function"), + /*questionToken*/ undefined, temp, + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.factory.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.factory.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.factory.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.factory.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.factory.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.factory.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.factory.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.factory.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + /** + * Produces an expression that results in `right` if `left` is not undefined at runtime: + * + * ``` + * typeof left !== "undefined" && right + * ``` + * + * We use `typeof L !== "undefined"` (rather than `L !== undefined`) since `L` may not be declared. + * It's acceptable for this expression to result in `false` at runtime, as the result is intended to be + * further checked by any containing expression. + */ + function createCheckedValue(left, right) { + return ts.factory.createLogicalAnd(ts.factory.createStrictInequality(ts.factory.createTypeOfExpression(left), ts.factory.createStringLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 79 /* SyntaxKind.Identifier */) { + // A -> typeof A !== "undefined" && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 79 /* SyntaxKind.Identifier */) { + // A.B -> typeof A !== "undefined" && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== "undefined" && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createLogicalAnd(ts.factory.createLogicalAnd(left.left, ts.factory.createStrictInequality(ts.factory.createAssignment(temp, left.right), ts.factory.createVoidZero())), ts.factory.createPropertyAccessExpression(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); + name.original = undefined; + ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. + return name; + case 161 /* SyntaxKind.QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * @param node The qualified name to serialize. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); + } + function getGlobalConstructorWithFallback(name) { + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createIdentifier(name), "function"), + /*questionToken*/ undefined, ts.factory.createIdentifier(name), + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + } + function getGlobalConstructor(name, minLanguageVersion) { + return languageVersion < minLanguageVersion ? + getGlobalConstructorWithFallback(name) : + ts.factory.createIdentifier(name); + } + } + ts.createRuntimeTypeSerializer = createRuntimeTypeSerializer; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformLegacyDecorators(context) { + var factory = context.factory, emitHelpers = context.getEmitHelperFactory, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + // Save the previous transformation hooks. + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onSubstituteNode = onSubstituteNode; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function modifierVisitor(node) { + return ts.isDecorator(node) ? undefined : node; + } + function visitor(node) { + if (!(node.transformFlags & 33554432 /* TransformFlags.ContainsDecorators */)) { + return node; + } + switch (node.kind) { + case 165 /* SyntaxKind.Decorator */: + // Decorators are elided. They will be emitted as part of `visitClassDeclaration`. + return undefined; + case 257 /* SyntaxKind.ClassDeclaration */: + return visitClassDeclaration(node); + case 226 /* SyntaxKind.ClassExpression */: + return visitClassExpression(node); + case 171 /* SyntaxKind.Constructor */: + return visitConstructorDeclaration(node); + case 169 /* SyntaxKind.MethodDeclaration */: + return visitMethodDeclaration(node); + case 173 /* SyntaxKind.SetAccessor */: + return visitSetAccessorDeclaration(node); + case 172 /* SyntaxKind.GetAccessor */: + return visitGetAccessorDeclaration(node); + case 167 /* SyntaxKind.PropertyDeclaration */: + return visitPropertyDeclaration(node); + case 164 /* SyntaxKind.Parameter */: + return visitParameterDeclaration(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitClassDeclaration(node) { + if (!(ts.classOrConstructorParameterIsDecorated(node) || ts.childIsDecorated(node))) + return ts.visitEachChild(node, visitor, context); + var statements = ts.hasDecorators(node) ? + transformClassDeclarationWithClassDecorators(node, node.name) : + transformClassDeclarationWithoutClassDecorators(node, node.name); + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(factory.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statements[0], ts.getEmitFlags(statements[0]) | 4194304 /* EmitFlags.HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + function decoratorContainsPrivateIdentifierInExpression(decorator) { + return !!(decorator.transformFlags & 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); + } + function parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators) { + return ts.some(parameterDecorators, decoratorContainsPrivateIdentifierInExpression); + } + function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.canHaveDecorators(member)) + continue; + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) + return true; + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) + return true; + } + return false; + } + function transformDecoratorsOfClassElements(node, members) { + var decorationStatements = []; + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ false); + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ true); + if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { + members = ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], members, true), [ + factory.createClassStaticBlockDeclaration(factory.createBlock(decorationStatements, /*multiLine*/ true)) + ], false)), members); + decorationStatements = undefined; + } + return { decorationStatements: decorationStatements, members: members }; + } + /** + * Transforms a non-decorated class declaration. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + */ + function transformClassDeclarationWithoutClassDecorators(node, name) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var _a; + var modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var updated = factory.updateClassDeclaration(node, modifiers, name, + /*typeParameters*/ undefined, heritageClauses, members); + return ts.addRange([updated], decorationStatements); + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function transformClassDeclarationWithClassDecorators(node, name) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var _a; + var location = ts.moveRangePastModifiers(node); + var classAlias = getClassAliasIfNeeded(node); + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var classExpression = factory.createClassExpression( + /*modifiers*/ undefined, name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(declName, + /*exclamationToken*/ undefined, + /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* NodeFlags.Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + var statements = [statement]; + ts.addRange(statements, decorationStatements); + addConstructorDecorationStatement(statements, node); + return statements; + } + function visitClassExpression(node) { + // Legacy decorators were not supported on class expressions + return factory.updateClassExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)); + } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)); + } + function finishClassElement(updated, original) { + if (updated !== original) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, original); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(original)); + } + return updated; + } + function visitMethodDeclaration(node) { + return finishClassElement(factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitGetAccessorDeclaration(node) { + return finishClassElement(factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitSetAccessorDeclaration(node) { + return finishClassElement(factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitPropertyDeclaration(node) { + if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */)) { + return undefined; + } + return finishClassElement(factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function visitParameterDeclaration(node) { + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* EmitFlags.NoTrailingSourceMap */); + } + return updated; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), function (expr) { return factory.createExpressionStatement(expr); })); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStaticElement, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStaticElement === ts.isStatic(member); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, function (m) { return isDecoratedClassElement(m, isStatic, node); }); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { + var member = members_8[_i]; + expressions = ts.append(expressions, generateClassElementDecorationExpression(node, member)); + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); + var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ + ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? factory.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : factory.createNull() + : undefined; + var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(helper, ts.moveRangePastModifiers(member)); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); + var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); + ts.setTextRange(helper, decorator.expression); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Gets an expression that represents a property name (for decorated properties or enums). + * For a computed property, a name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isPrivateIdentifier(name)) { + return factory.createIdentifier(""); + } + else if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression) + ? factory.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return factory.createStringLiteral(ts.idText(name)); + } + else { + return factory.cloneNode(name); + } + } + function enableSubstitutionForClassAliases() { + if (!classAliases) { + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(79 /* SyntaxKind.Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.isStatic(member) + ? factory.getDeclarationName(node) + : getClassPrototype(node); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* EmitHint.Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + var _a; + return (_a = trySubstituteClassAlias(node)) !== null && _a !== void 0 ? _a : node; + } + function trySubstituteClassAlias(node) { + if (classAliases) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; + } + } + } + } + return undefined; + } + } + ts.transformLegacyDecorators = transformLegacyDecorators; +})(ts || (ts = {})); +/*@internal*/ +var ts; (function (ts) { var ES2017SubstitutionFlags; (function (ES2017SubstitutionFlags) { @@ -95860,8 +97449,7 @@ var ts; * @param node The node to visit. */ function visitMethodDeclaration(node) { - return factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ @@ -95877,8 +97465,7 @@ var ts; * @param node The node to visit. */ function visitFunctionDeclaration(node) { - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -95893,7 +97480,7 @@ var ts; * @param node The node to visit. */ function visitFunctionExpression(node) { - return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -95908,7 +97495,7 @@ var ts; * @param node The node to visit. */ function visitArrowFunction(node) { - return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96210,7 +97797,6 @@ var ts; /* typeParameters */ undefined, /* parameters */ [ factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "v", /* questionToken */ undefined, @@ -96490,7 +98076,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -96563,7 +98149,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* SyntaxKind.CommaToken */) { @@ -96594,7 +98180,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* FlattenLevel.ObjectRest */); @@ -96635,7 +98221,7 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } @@ -96654,7 +98240,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* HierarchyFacts.IterationStatementExcludes */, 2 /* HierarchyFacts.IterationStatementIncludes */); - if (node.initializer.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -96761,17 +98347,15 @@ var ts; function visitParameter(node) { if (parametersWithPrecedingObjectRestOrSpread === null || parametersWithPrecedingObjectRestOrSpread === void 0 ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); } - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); @@ -96785,7 +98369,7 @@ var ts; if (parameters) { parameters.add(parameter); } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { parameters = new ts.Set(); } } @@ -96796,8 +98380,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateConstructorDeclaration(node, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -96807,8 +98390,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), + var updated = factory.updateGetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -96819,8 +98401,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateSetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -96830,9 +98411,8 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ - ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + var updated = factory.updateMethodDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifierLike) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), @@ -96849,8 +98429,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + var updated = factory.updateFunctionDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined @@ -97008,7 +98587,7 @@ var ts; statements = ts.append(statements, statement); } } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { containsPrecedingObjectRestOrSpread = true; var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* FlattenLevel.ObjectRest */, factory.getGeneratedNameForNode(parameter), /*doNotRecordTempVariablesInLine*/ false, @@ -97505,7 +99084,7 @@ var ts; var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1]; if (ts.isExternalModule(node)) { // Add `import` statement - var importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); + var importStatement = factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); ts.setParentRecursive(importStatement, /*incremental*/ false); statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement); } @@ -97736,22 +99315,29 @@ var ts; if (node === undefined) { return factory.createTrue(); } - else if (node.kind === 10 /* SyntaxKind.StringLiteral */) { + if (node.kind === 10 /* SyntaxKind.StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 288 /* SyntaxKind.JsxExpression */) { + if (node.kind === 288 /* SyntaxKind.JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } return ts.visitNode(node.expression, visitor, ts.isExpression); } - else { - return ts.Debug.failBadSyntaxKind(node); + if (ts.isJsxElement(node)) { + return visitJsxElement(node, /*isChild*/ false); } + if (ts.isJsxSelfClosingElement(node)) { + return visitJsxSelfClosingElement(node, /*isChild*/ false); + } + if (ts.isJsxFragment(node)) { + return visitJsxFragment(node, /*isChild*/ false); + } + return ts.Debug.failBadSyntaxKind(node); } function visitJsxText(node) { var fixed = fixupWhitespaceAndDecodeEntities(node.text); @@ -98373,7 +99959,7 @@ var ts; && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -98746,7 +100332,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], + /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], /*type*/ undefined, transformClassBody(node, extendsClauseElement)); // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier @@ -98824,7 +100410,6 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), @@ -98937,7 +100522,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass || superCallExpression) { - if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */)) { + if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -99089,7 +100674,6 @@ var ts; // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, @@ -99101,7 +100685,6 @@ var ts; else if (node.initializer) { // Initializers are elided return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.name, /*questionToken*/ undefined, @@ -99482,7 +101065,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { + if (node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { hierarchyFacts |= 65536 /* HierarchyFacts.CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -99541,8 +101124,7 @@ var ts; : node.name; exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -99768,7 +101350,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */) { + if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */) { if (node.flags & 3 /* NodeFlags.BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -99781,7 +101363,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */ + if (node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -100105,7 +101687,7 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 524288 /* TransformFlags.ContainsYield */ && + if ((property.transformFlags & 1048576 /* TransformFlags.ContainsYield */ && hierarchyFacts & 4 /* HierarchyFacts.AsyncFunctionBody */) || (hasComputed = ts.Debug.checkDefined(property.name).kind === 162 /* SyntaxKind.ComputedPropertyName */)) { numInitialProperties = i; @@ -100378,7 +101960,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 0 /* EmitFlags.None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -100493,7 +102075,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 524288 /* EmitFlags.ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -100636,7 +102218,7 @@ var ts; } } else { - loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + loopParameters.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); var checkFlags = resolver.getNodeCheckFlags(decl); if (checkFlags & 4194304 /* NodeCheckFlags.NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { var outParamName = factory.createUniqueName("out_" + ts.idText(name)); @@ -100793,10 +102375,10 @@ var ts; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); if (node.kind === 172 /* SyntaxKind.GetAccessor */) { - updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + updated = factory.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); } else { - updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body); + updated = factory.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; @@ -100975,7 +102557,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */ || + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */ || node.expression.kind === 106 /* SyntaxKind.SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -100983,7 +102565,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* EmitFlags.NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -101825,10 +103407,10 @@ var ts; case 247 /* SyntaxKind.ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -101892,8 +103474,7 @@ var ts; function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. if (node.asteriskToken) { - node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, node.modifiers, + node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(node.modifiers, /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body)), @@ -102033,7 +103614,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -103091,7 +104672,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + return !!node && (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -103722,7 +105303,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], /*type*/ undefined, factory.createBlock(buildResult, /*multiLine*/ buildResult.length > 0)), 524288 /* EmitFlags.ReuseTempVariableScope */)); } @@ -104140,7 +105721,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */ || + node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -104241,8 +105822,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ], false))) @@ -104263,7 +105844,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], /*type*/ undefined, ts.setTextRange(factory.createBlock([ factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([ factory.createVariableStatement( @@ -104312,8 +105893,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ])) @@ -104342,7 +105923,7 @@ var ts; var amdDependency = _a[_i]; if (amdDependency.name) { aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); } else { unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); @@ -104363,7 +105944,7 @@ var ts; // This is so that when printer will not substitute the identifier ts.setEmitFlags(importAliasName, 4 /* EmitFlags.NoSubstitution */); aliasedModuleNames.push(externalModuleName); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); } else { unaliasedModuleNames.push(externalModuleName); @@ -104477,7 +106058,7 @@ var ts; function visitorWorker(node, valueIsDiscarded) { // This visitor does not need to descend into the tree if there is no dynamic import, destructuring assignment, or update expression // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & (4194304 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (8388608 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -104628,7 +106209,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), visitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -104683,8 +106264,8 @@ var ts; var resolve = factory.createUniqueName("resolve"); var reject = factory.createUniqueName("reject"); var parameters = [ - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) ]; var body = factory.createBlock([ factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), @@ -104972,8 +106553,7 @@ var ts; function visitFunctionDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor), /*type*/ undefined, ts.visitEachChild(node.body, visitor, context)), /*location*/ node), @@ -105000,8 +106580,7 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor), ts.visitNodes(node.members, visitor)), node), node)); } else { @@ -105615,7 +107194,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -105648,8 +107227,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) ], /*type*/ undefined, moduleBodyBlock); // Write the call to `System.register` @@ -105784,7 +107363,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 1048576 /* TransformFlags.ContainsAwait */ ? + var modifiers = node.transformFlags & 2097152 /* TransformFlags.ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* ModifierFlags.Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -105871,10 +107450,9 @@ var ts; /*typeArguments*/ undefined, [n]))); } return factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, exportStarFunction, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], /*type*/ undefined, factory.createBlock([ factory.createVariableStatement( /*modifiers*/ undefined, factory.createVariableDeclarationList([ @@ -105965,7 +107543,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true))); } return factory.createArrayLiteralExpression(setters, /*multiLine*/ true); @@ -106063,7 +107641,7 @@ var ts; */ function visitFunctionDeclaration(node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock))); } @@ -106091,8 +107669,7 @@ var ts; var name = factory.getLocalName(node); hoistVariableDeclaration(name); // Rewrite the class declaration into an assignment of a class expression. - statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, visitor, ts.isDecorator), - /*modifiers*/ undefined, node.name, + statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -106693,7 +108270,7 @@ var ts; * @param node The node to visit. */ function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 4194304 /* TransformFlags.ContainsDynamicImport */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 8388608 /* TransformFlags.ContainsDynamicImport */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -107140,7 +108717,7 @@ var ts; // Though an error in es2020 modules, in node-flavor es2020 modules, we can helpfully transform this to a synthetic `require` call // To give easy access to a synchronous `require` in node-flavor esm. We do the transform even in scenarios where we error, but `import.meta.url` // is available, just because the output is reasonable for a node-like runtime. - return ts.getEmitScriptTarget(compilerOptions) >= ts.ModuleKind.ES2020 ? visitImportEqualsDeclaration(node) : undefined; + return ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.Node16 ? visitImportEqualsDeclaration(node) : undefined; case 271 /* SyntaxKind.ExportAssignment */: return visitExportAssignment(node); case 272 /* SyntaxKind.ExportDeclaration */: @@ -107163,7 +108740,6 @@ var ts; if (!importRequireStatements) { var createRequireName = factory.createUniqueName("_createRequire", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */); var importStatement = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamedImports([ @@ -107206,7 +108782,6 @@ var ts; function appendExportsOfImportEqualsDeclaration(statements, node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { statements = ts.append(statements, factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, ts.idText(node.name))]))); } return statements; @@ -107227,13 +108802,11 @@ var ts; var oldIdentifier = node.exportClause.name; var synthName = factory.getGeneratedNameForNode(oldIdentifier); var importDecl = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier, node.assertClause); ts.setOriginalNode(importDecl, node.exportClause); var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, synthName, oldIdentifier)])); ts.setOriginalNode(exportDecl, node); @@ -107485,7 +109058,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.SyntaxKind[node.kind])); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(node.kind))); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 254 /* SyntaxKind.VariableDeclaration */ || node.kind === 203 /* SyntaxKind.BindingElement */) { @@ -107696,7 +109269,7 @@ var ts; ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1; default: - return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.SyntaxKind[node.parent.kind])); + return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind))); } } function getTypeParameterConstraintVisibilityError() { @@ -107861,7 +109434,8 @@ var ts; trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, reportNonlocalAugmentation: reportNonlocalAugmentation, - reportNonSerializableProperty: reportNonSerializableProperty + reportNonSerializableProperty: reportNonSerializableProperty, + reportImportTypeNodeResolutionModeOverride: reportImportTypeNodeResolutionModeOverride, }; var errorNameNode; var errorFallbackNode; @@ -107988,6 +109562,11 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName)); } } + function reportImportTypeNodeResolutionModeOverride() { + if (!ts.isNightly() && (errorNameNode || errorFallbackNode)) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ @@ -108027,7 +109606,7 @@ var ts; resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -108170,7 +109749,7 @@ var ts; }); return ret; } - function filterBindingPatternInitializers(name) { + function filterBindingPatternInitializersAndRenamings(name) { if (name.kind === 79 /* SyntaxKind.Identifier */) { return name; } @@ -108186,7 +109765,12 @@ var ts; if (elem.kind === 227 /* SyntaxKind.OmittedExpression */) { return elem; } - return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + if (elem.propertyName && ts.isIdentifier(elem.propertyName) && ts.isIdentifier(elem.name) && !elem.symbol.isReferenced) { + // Unnecessary property renaming is forbidden in types, so remove renaming + return factory.updateBindingElement(elem, elem.dotDotDotToken, + /* propertyName */ undefined, elem.propertyName, shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializersAndRenamings(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); } } function ensureParameter(p, modifierMask, type) { @@ -108195,8 +109779,7 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } - var newParam = factory.updateParameterDeclaration(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + var newParam = factory.updateParameterDeclaration(p, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -108247,7 +109830,7 @@ var ts; if (node.kind === 164 /* SyntaxKind.Parameter */ || node.kind === 167 /* SyntaxKind.PropertyDeclaration */ || node.kind === 166 /* SyntaxKind.PropertySignature */) { - if (!node.initializer) + if (ts.isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } @@ -108333,7 +109916,6 @@ var ts; } if (!newValueParameter) { newValueParameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "value"); } @@ -108391,8 +109973,7 @@ var ts; if (decl.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); - return factory.updateImportEqualsDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + return factory.updateImportEqualsDeclaration(decl, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } else { var oldDiag = getSymbolAccessibilityDiagnostic; @@ -108405,31 +109986,28 @@ var ts; function transformImportDeclaration(decl) { if (!decl.importClause) { // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // The `importClause` visibility corresponds to the default's visibility. var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; if (!decl.importClause.namedBindings) { // No named bindings (either namespace or list), meaning the import is just default or should be elided - return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, + return visibleDefaultBinding && factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } if (decl.importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; - return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; + return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; } // Named imports (optionally with visible default) var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); if ((bindingList && bindingList.length) || visibleDefaultBinding) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Augmentation of export depends on import if (resolver.isImportRequiredByAugmentation(decl)) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, + return factory.updateImportDeclaration(decl, decl.modifiers, /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Nothing visible @@ -108438,7 +110016,7 @@ var ts; var mode = ts.getResolutionModeOverrideForClause(assertClause); if (mode !== undefined) { if (!ts.isNightly()) { - context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); } return assertClause; } @@ -108462,7 +110040,7 @@ var ts; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.Debug.formatSyntaxKind(i.kind))); } var priorNeedsDeclare = needsDeclare; needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); @@ -108526,7 +110104,7 @@ var ts; if (ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)) { if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; // Elide all but the first overload - return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + return cleanup(factory.createPropertyDeclaration(ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); } } if (canProduceDiagnostic && !suppressNewDiagnosticContexts) { @@ -108558,7 +110136,6 @@ var ts; case 171 /* SyntaxKind.Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* ModifierFlags.None */), /*body*/ undefined); return cleanup(ctor); @@ -108567,8 +110144,7 @@ var ts; if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - var sig = factory.createMethodDeclaration( - /*decorators*/ undefined, ensureModifiers(input), + var sig = factory.createMethodDeclaration(ensureModifiers(input), /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined); return cleanup(sig); @@ -108578,24 +110154,21 @@ var ts; return cleanup(/*returnValue*/ undefined); } var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); - return cleanup(factory.updateGetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), + return cleanup(factory.updateGetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), /*body*/ undefined)); } case 173 /* SyntaxKind.SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updateSetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), + return cleanup(factory.updateSetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), /*body*/ undefined)); } case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updatePropertyDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); + return cleanup(factory.updatePropertyDeclaration(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); case 166 /* SyntaxKind.PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); @@ -108611,8 +110184,7 @@ var ts; return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } case 176 /* SyntaxKind.IndexSignature */: { - return cleanup(factory.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); + return cleanup(factory.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); } case 254 /* SyntaxKind.VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { @@ -108651,7 +110223,7 @@ var ts; return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.assertions, input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); } - default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.SyntaxKind[input.kind])); + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(input.kind))); } } if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) { @@ -108695,8 +110267,7 @@ var ts; resultHasScopeMarker = true; // Always visible if the parent node isn't dropped for being not visible // Rewrite external module names if necessary - return factory.updateExportDeclaration(input, - /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); + return factory.updateExportDeclaration(input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); } case 271 /* SyntaxKind.ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible @@ -108719,7 +110290,7 @@ var ts; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* NodeFlags.Const */)); preserveJsDoc(statement, input); ts.removeAllComments(input); - return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + return [statement, factory.updateExportAssignment(input, input.modifiers, newId)]; } } } @@ -108734,7 +110305,7 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (125951 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (257023 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { @@ -108770,22 +110341,19 @@ var ts; var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 259 /* SyntaxKind.TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all - return cleanup(factory.updateTypeAliasDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + return cleanup(factory.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 258 /* SyntaxKind.InterfaceDeclaration */: { - return cleanup(factory.updateInterfaceDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + return cleanup(factory.updateInterfaceDeclaration(input, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 256 /* SyntaxKind.FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - var clean = cleanup(factory.updateFunctionDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), + var clean = cleanup(factory.updateFunctionDeclaration(input, ensureModifiers(input), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); if (clean && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { var props = resolver.getPropertiesOfContainerFunction(input); // Use parseNodeFactory so it is usable as an enclosing declaration - var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace_1, enclosingDeclaration); fakespace_1.locals = ts.createSymbolTable(props); fakespace_1.symbol = props[0].parent; @@ -108811,26 +110379,22 @@ var ts; } else { declarations.push(factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) { var gen = _a[0], exp = _a[1]; return factory.createExportSpecifier(/*isTypeOnly*/ false, gen, exp); })))); } - var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); + var namespaceDecl = factory.createModuleDeclaration(ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); if (!ts.hasEffectiveModifier(clean, 512 /* ModifierFlags.Default */)) { return [clean, namespaceDecl]; } var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ModifierFlags.ExportDefault */) | 2 /* ModifierFlags.Ambient */); - var cleanDeclaration = factory.updateFunctionDeclaration(clean, - /*decorators*/ undefined, modifiers, + var cleanDeclaration = factory.updateFunctionDeclaration(clean, modifiers, /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, /*body*/ undefined); - var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, - /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body); + var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, modifiers, namespaceDecl.name, namespaceDecl.body); var exportDefaultDeclaration = factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, namespaceDecl.name); if (ts.isSourceFile(input.parent)) { @@ -108873,8 +110437,7 @@ var ts; needsScopeFixMarker = oldNeedsScopeFix; resultHasScopeMarker = oldHasScopeFix; var mods = ensureModifiers(input); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; @@ -108885,8 +110448,7 @@ var ts; var id = ts.getOriginalNodeId(inner); // TODO: GH#18217 var body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, input.name, body)); } } case 257 /* SyntaxKind.ClassDeclaration */: { @@ -108903,8 +110465,7 @@ var ts; return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 79 /* SyntaxKind.Identifier */) { - return preserveJsDoc(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + return preserveJsDoc(factory.createPropertyDeclaration(ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } else { // Pattern - this is currently an error, but we emit declarations for it somewhat correctly @@ -108920,8 +110481,7 @@ var ts; elems = ts.concatenate(elems, walkBindingPattern(elem.name)); } elems = elems || []; - elems.push(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), elem.name, + elems.push(factory.createPropertyDeclaration(ensureModifiers(param), elem.name, /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), /*initializer*/ undefined)); } @@ -108935,7 +110495,6 @@ var ts; // Prevents other classes with the same public members from being used in place of the current class var privateIdentifier = hasPrivateIdentifier ? [ factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"), /*questionToken*/ undefined, /*type*/ undefined, @@ -108965,20 +110524,18 @@ var ts; } return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 104 /* SyntaxKind.NullKeyword */; })), visitDeclarationSubtree)); })); - return [statement, cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + return [statement, cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 } else { var heritageClauses = transformHeritageClauses(input.heritageClauses); - return cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + return cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members)); } } case 237 /* SyntaxKind.VariableStatement */: { return cleanup(transformVariableStatement(input)); } case 260 /* SyntaxKind.EnumDeclaration */: { - return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(factory.updateEnumDeclaration(input, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; // Rewrite enum values to their constants, if available @@ -108988,7 +110545,7 @@ var ts; } } // Anything left unhandled is an error, so this should be unreachable - return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.SyntaxKind[input.kind])); + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.Debug.formatSyntaxKind(input.kind))); function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; @@ -109062,12 +110619,12 @@ var ts; var currentFlags = ts.getEffectiveModifierFlags(node); var newFlags = ensureModifierFlags(node); if (currentFlags === newFlags) { - return node.modifiers; + return ts.visitArray(node.modifiers, function (n) { return ts.tryCast(n, ts.isModifier); }, ts.isModifier); } return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 125951 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files + var mask = 257023 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* ModifierFlags.Ambient */ : 0 /* ModifierFlags.None */; var parentIsFile = node.parent.kind === 305 /* SyntaxKind.SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { @@ -109108,7 +110665,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 125951 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } + if (modifierMask === void 0) { modifierMask = 257023 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* ModifierFlags.None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* ModifierFlags.Default */ && !(flags & 1 /* ModifierFlags.Export */)) { @@ -109230,6 +110787,7 @@ var ts; var transformers = []; ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory)); transformers.push(ts.transformTypeScript); + transformers.push(ts.transformLegacyDecorators); transformers.push(ts.transformClassFields); if (ts.getJSXTransformEnabled(compilerOptions)) { transformers.push(ts.transformJsx); @@ -109990,7 +111548,6 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; - var exportedModulesFromDeclarationEmit; // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); @@ -110000,7 +111557,6 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, - exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath; @@ -110054,14 +111610,16 @@ var ts; return; } var version = ts.version; // Extracted into a const so the form is stable between namespace and module - ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false); + var buildInfo = { bundle: bundle, program: program, version: version }; + // Pass buildinfo as additional data to avoid having to reparse + ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText(buildInfo), /*writeByteOrderMark*/ false, /*sourceFiles*/ undefined, { buildInfo: buildInfo }); } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) { if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) { return; } // Make sure not to write js file and source map file if any of them cannot be written - if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit) { emitSkipped = true; return; } @@ -110090,7 +111648,7 @@ var ts; substituteNode: transform.substituteNode, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); if (bundleBuildInfo) @@ -110126,7 +111684,7 @@ var ts; noEmitHelpers: true, module: compilerOptions.module, target: compilerOptions.target, - sourceMap: compilerOptions.sourceMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, inlineSourceMap: compilerOptions.inlineSourceMap, extendedDiagnostics: compilerOptions.extendedDiagnostics, onlyPrintJsDocStyle: true, @@ -110146,17 +111704,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: !forceDtsEmit && compilerOptions.declarationMap, + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform, declarationPrinter, { + sourceMap: printerOptions.sourceMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 305 /* SyntaxKind.SourceFile */) { - var sourceFile = declarationTransform.transformed[0]; - exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; - } } declarationTransform.dispose(); if (bundleBuildInfo) @@ -110175,7 +111729,8 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, mapOptions) { + var sourceFileOrBundle = transform.transformed[0]; var bundle = sourceFileOrBundle.kind === 306 /* SyntaxKind.Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 305 /* SyntaxKind.SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; @@ -110208,13 +111763,20 @@ var ts; if (sourceMapFilePath) { var sourceMap = sourceMapGenerator.toString(); ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + if (printer.bundleFileInfo) + printer.bundleFileInfo.mapHash = ts.computeSignature(sourceMap, ts.maybeBind(host, host.createHash)); } } else { writer.writeLine(); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos }); + var text = writer.getText(); + ts.writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos, diagnostics: transform.diagnostics }); + // We store the hash of the text written in the buildinfo to ensure that text of the referenced d.ts file is same as whats in the buildinfo + // This is needed because incremental can be toggled between two runs and we might use stale file text to do text manipulation in prepend mode + if (printer.bundleFileInfo) + printer.bundleFileInfo.hash = ts.computeSignature(text, ts.maybeBind(host, host.createHash)); // Reset state writer.clear(); } @@ -110357,34 +111919,56 @@ var ts; } /*@internal*/ function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) { + var createHash = ts.maybeBind(host, host.createHash); var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath)); - if (!buildInfoText) + var buildInfo; + if (host.getBuildInfo) { + // If host directly provides buildinfo we can get it directly. This allows host to cache the buildinfo + var hostBuildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); + if (!hostBuildInfo) + return buildInfoPath; + buildInfo = hostBuildInfo; + } + else { + var buildInfoText = host.readFile(buildInfoPath); + if (!buildInfoText) + return buildInfoPath; + buildInfo = getBuildInfo(buildInfoText); + } + if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationFilePath && !buildInfo.bundle.dts)) return buildInfoPath; var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath)); if (!jsFileText) return jsFilePath; + // If the jsFileText is not same has what it was created with, tsbuildinfo is stale so dont use it + if (ts.computeSignature(jsFileText, createHash) !== buildInfo.bundle.js.hash) + return jsFilePath; var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); // error if no source map or for now if inline sourcemap if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap) return sourceMapFilePath || "inline sourcemap decoding"; + if (sourceMapFilePath && ts.computeSignature(sourceMapText, createHash) !== buildInfo.bundle.js.mapHash) + return sourceMapFilePath; // read declaration text var declarationText = declarationFilePath && host.readFile(declarationFilePath); if (declarationFilePath && !declarationText) return declarationFilePath; + if (declarationFilePath && ts.computeSignature(declarationText, createHash) !== buildInfo.bundle.dts.hash) + return declarationFilePath; var declarationMapText = declarationMapPath && host.readFile(declarationMapPath); // error if no source map or for now if inline sourcemap if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding"; - var buildInfo = getBuildInfo(buildInfoText); - if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts)) - return buildInfoPath; + if (declarationMapPath && ts.computeSignature(declarationMapText, createHash) !== buildInfo.bundle.dts.mapHash) + return declarationMapPath; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, /*onlyOwnText*/ true); var outputFiles = []; var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); }); var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host); + var changedDtsText; + var changedDtsData; var emitHost = { getPrependNodes: ts.memoize(function () { return __spreadArray(__spreadArray([], prependNodes, true), [ownPrependInput], false); }), getCanonicalFileName: host.getCanonicalFileName, @@ -110400,7 +111984,7 @@ var ts; getResolvedProjectReferenceToRedirect: ts.returnUndefined, getProjectReferenceRedirect: ts.returnUndefined, isSourceOfProjectReferenceRedirect: ts.returnFalse, - writeFile: function (name, text, writeByteOrderMark) { + writeFile: function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { switch (name) { case jsFilePath: if (jsFileText === text) @@ -110411,8 +111995,12 @@ var ts; return; break; case buildInfoPath: - var newBuildInfo = getBuildInfo(text); + var newBuildInfo = data.buildInfo; newBuildInfo.program = buildInfo.program; + if (newBuildInfo.program && changedDtsText !== undefined && config.options.composite) { + // Update the output signature + newBuildInfo.program.outSignature = ts.computeSignature(changedDtsText, createHash, changedDtsData); + } // Update sourceFileInfo var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles; newBuildInfo.bundle.js.sources = js.sources; @@ -110420,11 +112008,13 @@ var ts; newBuildInfo.bundle.dts.sources = dts.sources; } newBuildInfo.bundle.sourceFiles = sourceFiles; - outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark }); + outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark, buildInfo: newBuildInfo }); return; case declarationFilePath: if (declarationText === text) return; + changedDtsText = text; + changedDtsData = data; break; case declarationMapPath: if (declarationMapText === text) @@ -110443,6 +112033,7 @@ var ts; getSourceFileFromReference: ts.returnUndefined, redirectTargetsMap: ts.createMultiMap(), getFileIncludeReasons: ts.notImplemented, + createHash: createHash, }; emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers)); @@ -111530,8 +113121,7 @@ var ts; } } function emitParameter(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); @@ -111542,7 +113132,7 @@ var ts; emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); @@ -111552,7 +113142,6 @@ var ts; // Type members // function emitPropertySignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); @@ -111560,8 +113149,7 @@ var ts; writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); emit(node.exclamationToken); @@ -111571,7 +113159,6 @@ var ts; } function emitMethodSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); @@ -111582,16 +113169,13 @@ var ts; popNameGenerationScope(node); } function emitMethodDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.asteriskToken); emit(node.name); emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitClassStaticBlockDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("static"); emitBlockFunctionBody(node.body); } @@ -111601,8 +113185,7 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword(node.kind === 172 /* SyntaxKind.GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); @@ -111610,8 +113193,6 @@ var ts; } function emitCallSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); @@ -111620,8 +113201,6 @@ var ts; } function emitConstructSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -111631,7 +113210,6 @@ var ts; popNameGenerationScope(node); } function emitIndexSignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); @@ -112024,7 +113602,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitSignatureAndBody(node, emitArrowFunctionHead); } @@ -112505,7 +114082,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitFunctionDeclarationOrExpression(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); emit(node.asteriskToken); @@ -112563,8 +114139,8 @@ var ts; if (!ts.nodeIsSynthesized(body) && currentSourceFile && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { return false; } - if (getLeadingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */) - || getClosingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */)) { + if (getLeadingLineTerminatorCount(body, ts.firstOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */) + || getClosingLineTerminatorCount(body, ts.lastOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */, body.statements)) { return false; } var previousStatement; @@ -112612,8 +114188,7 @@ var ts; } function emitClassDeclarationOrExpression(node) { ts.forEach(node.members, generateMemberNames); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword("class"); if (node.name) { writeSpace(); @@ -112634,7 +114209,6 @@ var ts; } } function emitInterfaceDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("interface"); writeSpace(); @@ -112647,7 +114221,6 @@ var ts; writePunctuation("}"); } function emitTypeAliasDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("type"); writeSpace(); @@ -113274,8 +114847,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* BundleFileSectionKind.Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_24 = types; _d < types_24.length; _d++) { - var directive = types_24[_d]; + for (var _d = 0, types_23 = types; _d < types_23.length; _d++) { + var directive = types_23[_d]; var pos = writer.getTextPos(); var resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.impliedNodeFormat) ? "resolution-mode=\"".concat(directive.resolutionMode === ts.ModuleKind.ESNext ? "import" : "require", "\"") @@ -113449,12 +115022,52 @@ var ts; emit(node); write = savedWrite; } - function emitModifiers(node, modifiers) { - if (modifiers && modifiers.length) { - emitList(node, modifiers, 262656 /* ListFormat.Modifiers */); - writeSpace(); + function emitDecoratorsAndModifiers(node, modifiers) { + if (modifiers === null || modifiers === void 0 ? void 0 : modifiers.length) { + if (ts.every(modifiers, ts.isModifier)) { + // if all modifier-likes are `Modifier`, simply emit the array as modifiers. + return emitModifiers(node, modifiers); + } + if (ts.every(modifiers, ts.isDecorator)) { + // if all modifier-likes are `Decorator`, simply emit the array as decorators. + return emitDecorators(node, modifiers); + } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(modifiers); + // partition modifiers into contiguous chunks of `Modifier` or `Decorator` + var lastMode = void 0; + var mode = void 0; + var start = 0; + var pos = 0; + while (start < modifiers.length) { + while (pos < modifiers.length) { + var modifier = modifiers[pos]; + mode = ts.isDecorator(modifier) ? "decorators" : "modifiers"; + if (lastMode === undefined) { + lastMode = mode; + } + else if (mode !== lastMode) { + break; + } + pos++; + } + var textRange = { pos: -1, end: -1 }; + if (start === 0) + textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) + textRange.end = modifiers.end; + emitNodeListItems(emit, node, modifiers, lastMode === "modifiers" ? 2359808 /* ListFormat.Modifiers */ : 2146305 /* ListFormat.Decorators */, + /*parenthesizerRule*/ undefined, start, pos - start, + /*hasTrailingComma*/ false, textRange); + start = pos; + lastMode = mode; + pos++; + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(modifiers); } } + function emitModifiers(node, modifiers) { + emitList(node, modifiers, 2359808 /* ListFormat.Modifiers */); + } function emitTypeAnnotation(node) { if (node) { writePunctuation(":"); @@ -113532,11 +115145,9 @@ var ts; && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head && !parentNode.type // arrow function may not have return type annotation - && !ts.some(parentNode.decorators) // parent may not have decorators - && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.modifiers) // parent may not have decorators or modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters - && !ts.some(parameter.decorators) // parameter may not have decorators - && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !ts.some(parameter.modifiers) // parameter may not have decorators or modifiers && !parameter.dotDotDotToken // parameter may not be rest && !parameter.questionToken // parameter may not be optional && !parameter.type // parameter may not have a type annotation @@ -113591,12 +115202,8 @@ var ts; } var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 32768 /* ListFormat.OptionalIfEmpty */) { - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); return; } if (format & 15360 /* ListFormat.BracketsMask */) { @@ -113605,9 +115212,7 @@ var ts; emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); if (isEmpty) { // Write a line terminator if the parent node was multi-line if (format & 1 /* ListFormat.MultiLine */ && !(preserveSourceNewlines && (!parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { @@ -113618,123 +115223,128 @@ var ts; } } else { - ts.Debug.type(children); - // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; - var shouldEmitInterveningComments = mayEmitInterveningComments; - var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217 - if (leadingLineTerminatorCount) { - writeLine(leadingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { - writeSpace(); - } - // Increase the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { - increaseIndent(); + emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, children.hasTrailingComma, children); + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); + if (format & 15360 /* ListFormat.BracketsMask */) { + if (isEmpty && children) { + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } - var emitListItem = getEmitListItem(emit, parenthesizerRule); - // Emit each child. - var previousSibling = void 0; - var previousSourceFileTextKind = void 0; - var shouldDecreaseIndentAfterEmit = false; - for (var i = 0; i < count; i++) { - var child = children[start + i]; - // Write the delimiter if this is not the first node. - if (format & 32 /* ListFormat.AsteriskDelimited */) { - // always write JSDoc in the format "\n *" - writeLine(); - writeDelimiter(format); - } - else if (previousSibling) { - // i.e - // function commentedParameters( - // /* Parameter a */ - // a - // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline - // , - if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { - emitLeadingCommentsOfPosition(previousSibling.end); - } - writeDelimiter(format); - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write either a line terminator or whitespace to separate the elements. - var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); - if (separatingLineTerminatorCount > 0) { - // If a synthesized node in a single-line list starts on a new - // line, we should increase the indent. - if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { - increaseIndent(); - shouldDecreaseIndentAfterEmit = true; - } - writeLine(separatingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { - writeSpace(); - } - } - // Emit this child. - previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); - if (shouldEmitInterveningComments) { - var commentRange = ts.getCommentRange(child); - emitTrailingCommentsOfPosition(commentRange.pos); - } - else { - shouldEmitInterveningComments = mayEmitInterveningComments; - } - nextListElementPos = child.pos; - emitListItem(child, emit, parenthesizerRule, i); - if (shouldDecreaseIndentAfterEmit) { - decreaseIndent(); - shouldDecreaseIndentAfterEmit = false; + writePunctuation(getClosingBracket(format)); + } + } + /** + * Emits a list without brackets or raising events. + * + * NOTE: You probably don't want to call this directly and should be using `emitList` or `emitExpressionList` instead. + */ + function emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, hasTrailingComma, childrenTextRange) { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children[start], format); + if (leadingLineTerminatorCount) { + writeLine(leadingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + increaseIndent(); + } + var emitListItem = getEmitListItem(emit, parenthesizerRule); + // Emit each child. + var previousSibling; + var previousSourceFileTextKind; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* ListFormat.AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write either a line terminator or whitespace to separate the elements. + var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); + if (separatingLineTerminatorCount > 0) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(separatingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { + writeSpace(); } - previousSibling = child; } - // Write a trailing comma, if requested. - var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; - var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); - var hasTrailingComma = (children === null || children === void 0 ? void 0 : children.hasTrailingComma) && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); - if (hasTrailingComma) { - if (previousSibling && !skipTrailingComments) { - emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); - } - else { - writePunctuation(","); - } + // Emit this child. + previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); + if (shouldEmitInterveningComments) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); } - // Emit any trailing comment of the last element in the list - // i.e - // var array = [... - // 2 - // /* end of element 2 */ - // ]; - if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { - emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); - } - // Decrease the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + nextListElementPos = child.pos; + emitListItem(child, emit, parenthesizerRule, i); + if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; } - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write the closing line terminator or closing whitespace. - var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format); - if (closingLineTerminatorCount) { - writeLine(closingLineTerminatorCount); + previousSibling = child; + } + // Write a trailing comma, if requested. + var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; + var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); + var emitTrailingComma = hasTrailingComma && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); + if (emitTrailingComma) { + if (previousSibling && !skipTrailingComments) { + emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); } - else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { - writeSpace(); + else { + writePunctuation(","); } } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { + emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange === null || childrenTextRange === void 0 ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end); } - if (format & 15360 /* ListFormat.BracketsMask */) { - if (isEmpty && children) { - emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists - } - writePunctuation(getClosingBracket(format)); + // Decrease the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + decreaseIndent(); + } + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write the closing line terminator or closing whitespace. + var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children[start + count - 1], format, childrenTextRange); + if (closingLineTerminatorCount) { + writeLine(closingLineTerminatorCount); + } + else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { + writeSpace(); } } // Writers @@ -113864,16 +115474,15 @@ var ts; decreaseIndent(); } } - function getLeadingLineTerminatorCount(parentNode, children, format) { + function getLeadingLineTerminatorCount(parentNode, firstChild, format) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var firstChild_1 = children[0]; - if (firstChild_1 === undefined) { + if (firstChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (firstChild_1.pos === nextListElementPos) { + if (firstChild.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading // line terminators have already been written as the separating line terminators of the // parent list. Example: @@ -113891,20 +115500,20 @@ var ts; // leading newline to start the modifiers. return 0; } - if (firstChild_1.kind === 11 /* SyntaxKind.JsxText */) { + if (firstChild.kind === 11 /* SyntaxKind.JsxText */) { // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && - !ts.nodeIsSynthesized(firstChild_1) && - (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { + !ts.nodeIsSynthesized(firstChild) && + (!firstChild.parent || ts.getOriginalNode(firstChild.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild.pos, parentNode.pos, currentSourceFile, includeComments); }); } - return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; + return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; } - if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) { + if (synthesizedNodeStartsOnNewLine(firstChild, format)) { return 1; } } @@ -113944,18 +115553,17 @@ var ts; } return format & 1 /* ListFormat.MultiLine */ ? 1 : 0; } - function getClosingLineTerminatorCount(parentNode, children, format) { + function getClosingLineTerminatorCount(parentNode, lastChild, format, childrenTextRange) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { - var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; + var end_1 = childrenTextRange && !ts.positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; @@ -113993,14 +115601,14 @@ var ts; return lines; } function writeLineSeparatorsAndIndentBefore(node, parent) { - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, node, 0 /* ListFormat.None */); if (leadingNewlines) { writeLinesAndIndent(leadingNewlines, /*writeSpaceIfNotIndenting*/ false); } return !!leadingNewlines; } function writeLineSeparatorsAfter(node, parent) { - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, node, 0 /* ListFormat.None */, /*childrenTextRange*/ undefined); if (trailingNewlines) { writeLine(trailingNewlines); } @@ -115527,12 +117135,10 @@ var ts; } ts.createCompilerHost = createCompilerHost; /*@internal*/ - // TODO(shkamat): update this after reworking ts build API function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = new ts.Map(); var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); - var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash; function getSourceFile(fileName, languageVersionOrOptions, onError) { var text; try { @@ -115565,7 +117171,7 @@ var ts; // NOTE: If patchWriteFileEnsuringDirectory has been called, // the system.writeFile will do its own directory creation and // the ensureDirectoriesExist call will always be redundant. - ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -115575,35 +117181,6 @@ var ts; } } } - var outputFingerprints; - function writeFileWorker(fileName, data, writeByteOrderMark) { - if (!ts.isWatchSet(options) || !system.getModifiedTime) { - system.writeFile(fileName, data, writeByteOrderMark); - return; - } - if (!outputFingerprints) { - outputFingerprints = new ts.Map(); - } - var hash = computeHash(data); - var mtimeBefore = system.getModifiedTime(fileName); - if (mtimeBefore) { - var fingerprint = outputFingerprints.get(fileName); - // If output has not been changed, and the file has no external modification - if (fingerprint && - fingerprint.byteOrderMark === writeByteOrderMark && - fingerprint.hash === hash && - fingerprint.mtime.getTime() === mtimeBefore.getTime()) { - return; - } - } - system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; - outputFingerprints.set(fileName, { - hash: hash, - byteOrderMark: writeByteOrderMark, - mtime: mtimeAfter - }); - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -115710,7 +117287,7 @@ var ts; }; } // directoryExists - if (originalDirectoryExists && originalCreateDirectory) { + if (originalDirectoryExists) { host.directoryExists = function (directory) { var key = toPath(directory); var value = directoryExistsCache.get(key); @@ -115720,11 +117297,13 @@ var ts; directoryExistsCache.set(key, !!newValue); return newValue; }; - host.createDirectory = function (directory) { - var key = toPath(directory); - directoryExistsCache.delete(key); - originalCreateDirectory.call(host, directory); - }; + if (originalCreateDirectory) { + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } } return { originalReadFile: originalReadFile, @@ -115945,12 +117524,14 @@ var ts; } ts.loadWithTypeDirectiveCache = loadWithTypeDirectiveCache; ; - /* @internal */ + /** + * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly + * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. + */ function getModeForFileReference(ref, containingFileMode) { return (ts.isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode; } ts.getModeForFileReference = getModeForFileReference; - /* @internal */ function getModeForResolutionAtIndex(file, index) { if (file.impliedNodeFormat === undefined) return undefined; @@ -115971,7 +117552,15 @@ var ts; return false; } ts.isExclusivelyTypeOnlyImportOrExport = isExclusivelyTypeOnlyImportOrExport; - /* @internal */ + /** + * Calculates the final resolution mode for a given module reference node. This is generally the explicitly provided resolution mode, if + * one exists, or the mode of the containing source file. (Excepting import=require, which is always commonjs, and dynamic import, which is always esm). + * Notably, this function always returns `undefined` if the containing file has an `undefined` `impliedNodeFormat` - this field is only set when + * `moduleResolution` is `node16`+. + * @param file The file the import or import-like reference is contained within + * @param usage The module reference string + * @returns The final resolution mode of the import + */ function getModeForUsageLocation(file, usage) { var _a, _b; if (file.impliedNodeFormat === undefined) @@ -116217,6 +117806,12 @@ var ts; * @returns `undefined` if the path has no relevant implied format, `ModuleKind.ESNext` for esm format, and `ModuleKind.CommonJS` for cjs format */ function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, options) { + var result = getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options); + return typeof result === "object" ? result.impliedNodeFormat : result; + } + ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + /*@internal*/ + function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) { switch (ts.getEmitModuleResolutionKind(options)) { case ts.ModuleResolutionKind.Node16: case ts.ModuleResolutionKind.NodeNext: @@ -116228,11 +117823,16 @@ var ts; return undefined; } function lookupFromPackageJson() { - var scope = ts.getPackageScopeForPath(fileName, packageJsonInfoCache, host, options); - return (scope === null || scope === void 0 ? void 0 : scope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + var state = ts.getTemporaryModuleResolutionState(packageJsonInfoCache, host, options); + var packageJsonLocations = []; + state.failedLookupLocations = packageJsonLocations; + state.affectingLocations = packageJsonLocations; + var packageJsonScope = ts.getPackageScopeForPath(fileName, state); + var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope }; } } - ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + ts.getImpliedNodeFormatForFileWorker = getImpliedNodeFormatForFileWorker; /** @internal */ ts.plainJSErrors = new ts.Set([ // binder errors @@ -116325,6 +117925,9 @@ var ts; ts.Diagnostics.extends_clause_already_seen.code, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + ts.Diagnostics.Class_constructor_may_not_be_a_generator.code, + ts.Diagnostics.Class_constructor_may_not_be_an_accessor.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]); /** * Determine if source file needs to be re-created even if its text hasn't changed @@ -116554,7 +118157,7 @@ var ts; for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); - if (shouldCreateNewSourceFile || !newFile || + if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // old file wasn't redirect but new file is (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); @@ -116891,7 +118494,7 @@ var ts; // `result[i]` is either a `ResolvedModuleFull` or a marker. // If it is the former, we can leave it as is. if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; // TODO: GH#18217 + result[i] = undefined; } } else { @@ -116947,7 +118550,7 @@ var ts; }); } function tryReuseStructureFromOldProgram() { - var _a; + var _a, _b; if (!oldProgram) { return 0 /* StructureIsReused.Not */; } @@ -116988,12 +118591,15 @@ var ts; var seenPackageNames = new ts.Map(); for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; + var sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options); var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat) + : host.getSourceFile(oldSourceFile.fileName, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat); // TODO: GH#18217 if (!newSourceFile) { return 0 /* StructureIsReused.Not */; } + newSourceFile.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope; ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); var fileChanged = void 0; if (oldSourceFile.redirectInfo) { @@ -117033,38 +118639,43 @@ var ts; seenPackageNames.set(packageName, newKind); } if (fileChanged) { + if (oldSourceFile.impliedNodeFormat !== newSourceFile.impliedNodeFormat) { + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } // The `newSourceFile` object was created for the new program. - if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { // 'lib' references has changed. Matches behavior in changesAffectModuleResolution structureIsReused = 1 /* StructureIsReused.SafeModules */; } - if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + else if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files structureIsReused = 1 /* StructureIsReused.SafeModules */; } // check tripleslash references - if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed structureIsReused = 1 /* StructureIsReused.SafeModules */; } - // check imports and module augmentations - collectExternalModuleReferences(newSourceFile); - if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - // imports has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - // moduleAugmentations has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { - // dynamicImport has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - // 'types' references has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; + else { + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); @@ -117082,18 +118693,18 @@ var ts; return structureIsReused; } var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); - for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) { - var oldFile = oldSourceFiles_3[_b]; + for (var _c = 0, oldSourceFiles_3 = oldSourceFiles; _c < oldSourceFiles_3.length; _c++) { + var oldFile = oldSourceFiles_3[_c]; if (!ts.contains(modifiedFiles, oldFile)) { - for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) { - var moduleName = _d[_c]; + for (var _d = 0, _e = oldFile.ambientModuleNames; _d < _e.length; _d++) { + var moduleName = _e[_d]; ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); } } } // try to verify results of module resolution - for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) { - var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile; + for (var _f = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _f < modifiedSourceFiles_1.length; _f++) { + var _g = modifiedSourceFiles_1[_f], oldSourceFile = _g.oldFile, newSourceFile = _g.newFile; var moduleNames = getModuleNames(newSourceFile); var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); // ensure that module resolution results are still correct @@ -117120,14 +118731,14 @@ var ts; if (structureIsReused !== 2 /* StructureIsReused.Completely */) { return structureIsReused; } - if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host))) { + if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_b = host.hasChangedAutomaticTypeDirectiveNames) === null || _b === void 0 ? void 0 : _b.call(host))) { return 1 /* StructureIsReused.SafeModules */; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); - for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) { - var newSourceFile = newSourceFiles_1[_g]; + for (var _h = 0, newSourceFiles_1 = newSourceFiles; _h < newSourceFiles_1.length; _h++) { + var newSourceFile = newSourceFiles_1[_h]; filesByName.set(newSourceFile.path, newSourceFile); } var oldFilesByNameMap = oldProgram.getFilesByNameMap(); @@ -117189,6 +118800,7 @@ var ts; getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); }, redirectTargetsMap: redirectTargetsMap, getFileIncludeReasons: program.getFileIncludeReasons, + createHash: ts.maybeBind(host, host.createHash), }; } function writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data) { @@ -117542,7 +119154,7 @@ var ts; } } function walkArray(nodes, parent) { - if (parent.decorators === nodes && !options.experimentalDecorators) { + if (ts.canHaveModifiers(parent) && parent.modifiers === nodes && ts.some(nodes, ts.isDecorator) && !options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { @@ -117573,7 +119185,7 @@ var ts; if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { + if (ts.isModifier(modifier) && modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); } } @@ -117582,7 +119194,7 @@ var ts; break; case 164 /* SyntaxKind.Parameter */: // Check modifiers of parameter declaration - if (nodes === parent.modifiers) { + if (nodes === parent.modifiers && ts.some(nodes, ts.isModifier)) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -117701,7 +119313,7 @@ var ts; } function createSyntheticImport(text, file) { var externalHelpersModuleReference = ts.factory.createStringLiteral(text); - var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); + var importDecl = ts.factory.createImportDeclaration(/*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); ts.addEmitFlags(importDecl, 67108864 /* EmitFlags.NeverApplyImportHelper */); ts.setParent(externalHelpersModuleReference, importDecl); ts.setParent(importDecl, file); @@ -117909,13 +119521,16 @@ var ts; addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) { + var _a; var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; redirect.resolvedPath = resolvedPath; redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + redirect.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + redirect.packageJsonScope = sourceFileOptions.packageJsonScope; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { @@ -117944,14 +119559,14 @@ var ts; // It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache // and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way // to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront. - var impliedNodeFormat = getImpliedNodeFormatForFile(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); - return { - languageVersion: ts.getEmitScriptTarget(options), - impliedNodeFormat: impliedNodeFormat, - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(options) - }; + var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); + var languageVersion = ts.getEmitScriptTarget(options); + var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options); + return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) : + { languageVersion: languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator }; } function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { + var _a, _b; var path = toPath(fileName); if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(path); @@ -118038,14 +119653,15 @@ var ts; } } // We haven't looked for this file, do so now and cache result - var file = host.getSourceFile(fileName, getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options), function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile); + var sourceFileOptions = getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options); + var file = host.getSourceFile(fileName, sourceFileOptions, function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile || (((_a = oldProgram === null || oldProgram === void 0 ? void 0 : oldProgram.getSourceFileByPath(toPath(fileName))) === null || _a === void 0 ? void 0 : _a.impliedNodeFormat) !== sourceFileOptions.impliedNodeFormat)); if (packageId) { var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName, sourceFileOptions); redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, redirectedPath); addFileIncludeReason(dupFile, reason); @@ -118066,6 +119682,8 @@ var ts; file.path = path; file.resolvedPath = toPath(fileName); file.originalFileName = originalFileName; + file.packageJsonLocations = ((_b = sourceFileOptions.packageJsonLocations) === null || _b === void 0 ? void 0 : _b.length) ? sourceFileOptions.packageJsonLocations : undefined; + file.packageJsonScope = sourceFileOptions.packageJsonScope; addFileIncludeReason(file, reason); if (host.useCaseSensitiveFileNames()) { var pathLowerCase = ts.toFileNameLowerCase(path); @@ -118205,13 +119823,13 @@ var ts; ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); var mode = ref.resolutionMode || file.impliedNodeFormat; if (mode && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { - programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); + programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); } processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, }); } } function processTypeReferenceDirective(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -118696,7 +120314,7 @@ var ts; fileIncludeReasons = undefined; var location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason); var fileIncludeReasonDetails = fileIncludeReasons && ts.chainDiagnosticMessages(fileIncludeReasons, ts.Diagnostics.The_file_is_in_the_program_because_Colon); - var redirectInfo = file && ts.explainIfFileIsRedirect(file); + var redirectInfo = file && ts.explainIfFileIsRedirectAndImpliedFormat(file); var chain = ts.chainDiagnosticMessages.apply(void 0, __spreadArray([redirectInfo ? fileIncludeReasonDetails ? __spreadArray([fileIncludeReasonDetails], redirectInfo, true) : redirectInfo : fileIncludeReasonDetails, diagnostic], args || ts.emptyArray, false)); return location && isReferenceFileLocation(location) ? ts.createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : @@ -118766,7 +120384,7 @@ var ts; } var matchedByInclude = ts.getMatchedIncludeSpec(program, fileName); // Could be additional files specified as roots - if (!matchedByInclude) + if (!matchedByInclude || !ts.isString(matchedByInclude)) return undefined; configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude); message = ts.Diagnostics.File_is_matched_by_include_pattern_specified_here; @@ -119290,8 +120908,8 @@ var ts; (function (ts) { function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) { var outputFiles = []; - var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit; - return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; + var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics; + return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -119302,13 +120920,9 @@ var ts; function createManyToManyPathMap() { function create(forward, reverse, deleted) { var map = { - clone: function () { return create(new ts.Map(forward), new ts.Map(reverse), deleted && new ts.Set(deleted)); }, - forEach: function (fn) { return forward.forEach(fn); }, getKeys: function (v) { return reverse.get(v); }, getValues: function (k) { return forward.get(k); }, - hasKey: function (k) { return forward.has(k); }, keys: function () { return forward.keys(); }, - deletedKeys: function () { return deleted; }, deleteKey: function (k) { (deleted || (deleted = new ts.Set())).add(k); var set = forward.get(k); @@ -119335,11 +120949,6 @@ var ts; }); return map; }, - clear: function () { - forward.clear(); - reverse.clear(); - deleted === null || deleted === void 0 ? void 0 : deleted.clear(); - } }; return map; } @@ -119467,18 +121076,21 @@ var ts; * Creates the state of file references and signature for the new program from oldState if it is safe */ function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b, _c; var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? createManyToManyPathMap() : undefined; var exportedModulesMap = referencedMap ? createManyToManyPathMap() : undefined; - var hasCalledUpdateShapeSignature = new ts.Set(); var useOldState = canReuseOldState(referencedMap, oldState); // Ensure source files have parent pointers set newProgram.getTypeChecker(); // Create the reference map, and set the file infos - for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + for (var _i = 0, _d = newProgram.getSourceFiles(); _i < _d.length; _i++) { + var sourceFile = _d[_i]; var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); - var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined; + var oldUncommittedSignature = useOldState ? (_a = oldState.oldSignatures) === null || _a === void 0 ? void 0 : _a.get(sourceFile.resolvedPath) : undefined; + var signature = oldUncommittedSignature === undefined ? + useOldState ? (_b = oldState.fileInfos.get(sourceFile.resolvedPath)) === null || _b === void 0 ? void 0 : _b.signature : undefined : + oldUncommittedSignature || undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -119486,19 +121098,26 @@ var ts; } // Copy old visible to outside files map if (useOldState) { - var exportedModules = oldState.exportedModulesMap.getValues(sourceFile.resolvedPath); + var oldUncommittedExportedModules = (_c = oldState.oldExportedModulesMap) === null || _c === void 0 ? void 0 : _c.get(sourceFile.resolvedPath); + var exportedModules = oldUncommittedExportedModules === undefined ? + oldState.exportedModulesMap.getValues(sourceFile.resolvedPath) : + oldUncommittedExportedModules || undefined; if (exportedModules) { exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, impliedFormat: sourceFile.impliedNodeFormat }); + fileInfos.set(sourceFile.resolvedPath, { + version: version_2, + signature: signature, + affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, + impliedFormat: sourceFile.impliedNodeFormat + }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } @@ -119512,120 +121131,95 @@ var ts; } BuilderState.releaseCache = releaseCache; /** - * Creates a clone of the state + * Gets the files affected by the path from the program */ - function clone(state) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var _a, _b; - // Dont need to backup allFiles info since its cache anyway - return { - fileInfos: new ts.Map(state.fileInfos), - referencedMap: (_a = state.referencedMap) === null || _a === void 0 ? void 0 : _a.clone(), - exportedModulesMap: (_b = state.exportedModulesMap) === null || _b === void 0 ? void 0 : _b.clone(), - hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), - useFileVersionAsSignature: state.useFileVersionAsSignature, - }; + var result = getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); + return result; } - BuilderState.clone = clone; - /** - * Gets the files affected by the path from the program - */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { - // Since the operation could be cancelled, the signatures are always stored in the cache - // They will be committed once it is safe to use them - // eg when calling this api from tsserver, if there is no cancellation of the operation - // In the other cases the affected files signatures are committed only after the iteration through the result is complete - var signatureCache = cacheToUpdateSignature || new ts.Map(); + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var sourceFile = programOfThisState.getSourceFileByPath(path); if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); - if (!cacheToUpdateSignature) { - // Commit all the signatures in the signature cache - updateSignaturesFromCache(state, signatureCache); - } - return result; + return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName); } - BuilderState.getFilesAffectedBy = getFilesAffectedBy; - /** - * Updates the signatures from the cache into state's fileinfo signatures - * This should be called whenever it is safe to commit the state of the builder - */ - function updateSignaturesFromCache(state, signatureCache) { - signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); }); - } - BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + BuilderState.getFilesAffectedByWithOldState = getFilesAffectedByWithOldState; function updateSignatureOfFile(state, signature, path) { state.fileInfos.get(path).signature = signature; - state.hasCalledUpdateShapeSignature.add(path); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(path); } BuilderState.updateSignatureOfFile = updateSignatureOfFile; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache, useFileVersionAsSignature) { + function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName, useFileVersionAsSignature) { + var _a; if (useFileVersionAsSignature === void 0) { useFileVersionAsSignature = state.useFileVersionAsSignature; } - ts.Debug.assert(!!sourceFile); - ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) { + if ((_a = state.hasCalledUpdateShapeSignature) === null || _a === void 0 ? void 0 : _a.has(sourceFile.resolvedPath)) return false; - } var info = state.fileInfos.get(sourceFile.resolvedPath); - if (!info) - return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) { - var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, - /*emitOnlyDtsFiles*/ true, cancellationToken, + programOfThisState.emit(sourceFile, function (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) { + ts.Debug.assert(ts.isDeclarationFileName(fileName), "File extension for signature expected to be dts: Got:: ".concat(fileName)); + latestSignature = ts.computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data); + if (latestSignature !== prevSignature) { + updateExportedModules(state, sourceFile, sourceFiles[0].exportedModulesFromDeclarationEmit); + } + }, cancellationToken, + /*emitOnlyDtsFiles*/ true, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); - if (firstDts_1) { - ts.Debug.assert(ts.isDeclarationFileName(firstDts_1.name), "File extension for signature expected to be dts", function () { return "Found: ".concat(ts.getAnyExtensionFromPath(firstDts_1.name), " for ").concat(firstDts_1.name, ":: All output files: ").concat(JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; }))); }); - latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); - if (exportedModulesMapCache && latestSignature !== prevSignature) { - updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); - } - } } // Default is to use file version as signature if (latestSignature === undefined) { latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { + if (state.exportedModulesMap && latestSignature !== prevSignature) { + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); // All the references in this file are exported var references = state.referencedMap ? state.referencedMap.getValues(sourceFile.resolvedPath) : undefined; if (references) { - exportedModulesMapCache.set(sourceFile.resolvedPath, references); + state.exportedModulesMap.set(sourceFile.resolvedPath, references); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } } } - cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); + (state.oldSignatures || (state.oldSignatures = new ts.Map())).set(sourceFile.resolvedPath, prevSignature || false); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(sourceFile.resolvedPath); + info.signature = latestSignature; return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** * Coverts the declaration emit result into exported modules map */ - function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + function updateExportedModules(state, sourceFile, exportedModulesFromDeclarationEmit) { + if (!state.exportedModulesMap) + return; + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); if (!exportedModulesFromDeclarationEmit) { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); return; } var exportedModules; exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFilesFromImportedModuleSymbol(symbol)); }); if (exportedModules) { - exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules); + state.exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } function addExportedModule(exportedModulePaths) { if (exportedModulePaths === null || exportedModulePaths === void 0 ? void 0 : exportedModulePaths.length) { @@ -119637,19 +121231,6 @@ var ts; } } BuilderState.updateExportedModules = updateExportedModules; - /** - * Updates the exported modules from cache into state's exported modules map - * This should be called whenever it is safe to commit the state of the builder - */ - function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { - var _a; - if (exportedModulesMapCache) { - ts.Debug.assert(!!state.exportedModulesMap); - (_a = exportedModulesMapCache.deletedKeys()) === null || _a === void 0 ? void 0 : _a.forEach(function (path) { return state.exportedModulesMap.deleteKey(path); }); - exportedModulesMapCache.forEach(function (exportedModules, path) { return state.exportedModulesMap.set(path, exportedModules); }); - } - } - BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -119770,7 +121351,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cancellationToken, computeHash, getCanonicalFileName) { if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -119790,7 +121371,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, computeHash, getCanonicalFileName)) { queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } @@ -119816,32 +121397,33 @@ var ts; * Create the state so that we can iterate on changedFiles/affected files */ function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; + var outFilePath = ts.outFile(compilerOptions); // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them - if (!ts.outFile(compilerOptions)) { + if (!outFilePath) { state.semanticDiagnosticsPerFile = new ts.Map(); } + else if (compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.outSignature) && outFilePath === ts.outFile(oldState === null || oldState === void 0 ? void 0 : oldState.compilerOptions)) { + state.outSignature = oldState === null || oldState === void 0 ? void 0 : oldState.outSignature; + } state.changedFilesSet = new ts.Set(); + state.latestChangedDtsFile = compilerOptions.composite ? oldState === null || oldState === void 0 ? void 0 : oldState.latestChangedDtsFile : undefined; var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + var canCopyEmitSignatures = compilerOptions.composite && + (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && + !outFilePath && + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); if (useOldState) { - // Verify the sanity of old state - if (!oldState.currentChangedFilePath) { - var affectedSignatures = oldState.currentAffectedFilesSignatures; - ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); - } - var changedFilesSet = oldState.changedFilesSet; - if (canCopySemanticDiagnostics) { - ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); - } // Copy old state's changed files set - changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); }); - if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) { + (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); + if (!outFilePath && oldState.affectedFilesPendingEmit) { state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice(); state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind); state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; @@ -119862,6 +121444,8 @@ var ts; !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || // versions dont match oldInfo.version !== info.version || + // Implied formats dont match + oldInfo.impliedFormat !== info.impliedFormat || // Referenced files changed !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || // Referenced file was deleted in the new program @@ -119885,27 +121469,25 @@ var ts; state.semanticDiagnosticsFromOldState.add(sourceFilePath); } } + if (canCopyEmitSignatures) { + var oldEmitSignature = oldState.emitSignatures.get(sourceFilePath); + if (oldEmitSignature) + (state.emitSignatures || (state.emitSignatures = new ts.Map())).set(sourceFilePath, oldEmitSignature); + } }); // If the global file is removed, add all files as changed if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) { ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined) .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); }); } - else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { + else if (oldCompilerOptions && !outFilePath && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { // Add all files to affectedFilesPendingEmit since emit changed newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* BuilderFileEmit.Full */); }); ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set(); } - if (useOldState) { - // Any time the interpretation of a source file changes, mark it as changed - ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { - if (state.fileInfos.has(sourceFilePath) && state.fileInfos.get(sourceFilePath).impliedFormat !== info.impliedFormat) { - state.changedFilesSet.add(sourceFilePath); - } - }); - } - state.buildInfoEmitPending = !!state.changedFilesSet.size; + // Since old states change files set is copied, any additional change means we would need to emit build info + state.buildInfoEmitPending = !useOldState || state.changedFilesSet.size !== (((_b = oldState.changedFilesSet) === null || _b === void 0 ? void 0 : _b.size) || 0); return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -119941,30 +121523,35 @@ var ts; ts.BuilderState.releaseCache(state); state.program = undefined; } - /** - * Creates a clone of the state - */ - function cloneBuilderProgramState(state) { - var _a; - var newState = ts.BuilderState.clone(state); - newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile); - newState.changedFilesSet = new ts.Set(state.changedFilesSet); - newState.affectedFiles = state.affectedFiles; - newState.affectedFilesIndex = state.affectedFilesIndex; - newState.currentChangedFilePath = state.currentChangedFilePath; - newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures); - newState.currentAffectedFilesExportedModulesMap = (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clone(); - newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles); - newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; - newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState); - newState.program = state.program; - newState.compilerOptions = state.compilerOptions; - newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(); - newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind); - newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; - newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles); - newState.programEmitComplete = state.programEmitComplete; - return newState; + function backupBuilderProgramEmitState(state) { + var outFilePath = ts.outFile(state.compilerOptions); + // Only in --out changeFileSet is kept around till emit + ts.Debug.assert(!state.changedFilesSet.size || outFilePath); + return { + affectedFilesPendingEmit: state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(), + affectedFilesPendingEmitKind: state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind), + affectedFilesPendingEmitIndex: state.affectedFilesPendingEmitIndex, + seenEmittedFiles: state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles), + programEmitComplete: state.programEmitComplete, + emitSignatures: state.emitSignatures && new ts.Map(state.emitSignatures), + outSignature: state.outSignature, + latestChangedDtsFile: state.latestChangedDtsFile, + hasChangedEmitSignature: state.hasChangedEmitSignature, + changedFilesSet: outFilePath ? new ts.Set(state.changedFilesSet) : undefined, + }; + } + function restoreBuilderProgramEmitState(state, savedEmitState) { + state.affectedFilesPendingEmit = savedEmitState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitKind = savedEmitState.affectedFilesPendingEmitKind; + state.affectedFilesPendingEmitIndex = savedEmitState.affectedFilesPendingEmitIndex; + state.seenEmittedFiles = savedEmitState.seenEmittedFiles; + state.programEmitComplete = savedEmitState.programEmitComplete; + state.emitSignatures = savedEmitState.emitSignatures; + state.outSignature = savedEmitState.outSignature; + state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile; + state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; + if (savedEmitState.changedFilesSet) + state.changedFilesSet = savedEmitState.changedFilesSet; } /** * Verifies that source file is ok to be used in calls that arent handled by next @@ -119978,8 +121565,8 @@ var ts; * This is to allow the callers to be able to actually remove affected file only when the operation is complete * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained */ - function getNextAffectedFile(state, cancellationToken, computeHash, host) { - var _a; + function getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { @@ -119990,7 +121577,7 @@ var ts; if (!seenAffectedFiles.has(affectedFile.resolvedPath)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); return affectedFile; } affectedFilesIndex++; @@ -119999,10 +121586,8 @@ var ts; state.changedFilesSet.delete(state.currentChangedFilePath); state.currentChangedFilePath = undefined; // Commit the changes in file signature - ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); - state.currentAffectedFilesSignatures.clear(); - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); - (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clear(); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); state.affectedFiles = undefined; } // Get next changed file @@ -120020,12 +121605,7 @@ var ts; return program; } // Get next batch of affected files - if (!state.currentAffectedFilesSignatures) - state.currentAffectedFilesSignatures = new ts.Map(); - if (state.exportedModulesMap) { - state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap()); - } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedByWithOldState(state, program, nextKey.value, cancellationToken, computeHash, getCanonicalFileName); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; if (!state.seenAffectedFiles) @@ -120076,8 +121656,7 @@ var ts; * Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ - function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -120085,19 +121664,18 @@ var ts; // When a change affects the global scope, all files are considered to be affected without updating their signature // That means when affected file is handled, its signature can be out of date // To avoid this, ensure that we update the signature for any affected file in this scenario. - ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, cancellationToken, computeHash, getCanonicalFileName); return; } - ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: ".concat(affectedFile.fileName)); if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; - handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); } /** * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled, * Also we need to make sure signature is updated for these files */ - function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, host) { + function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { var program = ts.Debug.checkDefined(state.program); @@ -120108,7 +121686,7 @@ var ts; // This ensures that we dont later during incremental builds considering wrong signature. // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build // But we avoid expensive full shape computation, as using file version as shape is enough for correctness. - ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap, !host.disableUseFileVersionAsSignature); + ts.BuilderState.updateShapeSignature(state, program, sourceFile, cancellationToken, computeHash, getCanonicalFileName, !host.disableUseFileVersionAsSignature); // If not dts emit, nothing more to do if (ts.getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, 0 /* BuilderFileEmit.DtsOnly */); @@ -120129,41 +121707,25 @@ var ts; return !state.semanticDiagnosticsFromOldState.size; } function isChangedSignature(state, path) { - var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path); - var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; + var oldSignature = ts.Debug.checkDefined(state.oldSignatures).get(path) || undefined; + var newSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; return newSignature !== oldSignature; } - function forEachKeyOfExportedModulesMap(state, filePath, fn) { - // Go through exported modules from cache first - var keys = state.currentAffectedFilesExportedModulesMap.getKeys(filePath); - var result = keys && ts.forEachKey(keys, fn); - if (result) - return result; - // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - keys = state.exportedModulesMap.getKeys(filePath); - return keys && ts.forEachKey(keys, function (exportedFromPath) { - var _a; - // If the cache had an updated value, skip - return !state.currentAffectedFilesExportedModulesMap.hasKey(exportedFromPath) && - !((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(exportedFromPath)) ? - fn(exportedFromPath) : - undefined; - }); - } - function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host) { var _a; if (!((_a = state.fileInfos.get(filePath)) === null || _a === void 0 ? void 0 : _a.affectsGlobalScope)) return false; // Every file needs to be handled ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, state.program, /*firstSourceFile*/ undefined) - .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, host); }); + .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, getCanonicalFileName, host); }); removeDiagnosticsOfLibraryFiles(state); return true; } /** * Iterate on referencing modules that export entities from affected file and delete diagnostics and add pending emit */ - function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a; // If there was change in signature (dts output) for the changed file, // then only we need to handle pending file emit if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) @@ -120180,9 +121742,9 @@ var ts; var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { seenFileNamesMap.set(currentPath, true); - if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host)) return; - handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, host); + handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host); if (isChangedSignature(state, currentPath)) { var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath); queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); @@ -120190,16 +121752,15 @@ var ts; } } } - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); var seenFileAndExportsOfFile = new ts.Set(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, affectedFile.resolvedPath, function (exportedFromPath) { - if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, host)) + (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; var references = state.referencedMap.getKeys(exportedFromPath); return references && ts.forEachKey(references, function (filePath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); }); } @@ -120207,23 +121768,22 @@ var ts; * handle dts and semantic diagnostics on file and iterate on anything that exports this file * return true when all work is done and we can exit handling dts emit and semantic diagnostics */ - function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) return undefined; - if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; - handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, host); - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host); // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, filePath, function (exportedFromPath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + (_a = state.exportedModulesMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); // Remove diagnostics of files that import this file (without going to exports of referencing files) - (_a = state.referencedMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (referencingFilePath) { + (_b = state.referencedMap.getKeys(filePath)) === null || _b === void 0 ? void 0 : _b.forEach(function (referencingFilePath) { return !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file handleDtsMayChangeOf(// Dont add to seen since this is not yet done with the export removal - state, referencingFilePath, cancellationToken, computeHash, host); + state, referencingFilePath, cancellationToken, computeHash, getCanonicalFileName, host); }); return undefined; } @@ -120241,12 +121801,13 @@ var ts; } else { state.seenAffectedFiles.add(affected.resolvedPath); + // Change in changeSet/affectedFilesPendingEmit, buildInfo needs to be emitted + state.buildInfoEmitPending = true; if (emitKind !== undefined) { (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind); } if (isPendingEmit) { state.affectedFilesPendingEmitIndex++; - state.buildInfoEmitPending = true; } else { state.affectedFilesIndex++; @@ -120294,25 +121855,62 @@ var ts; } return ts.filterSemanticDiagnostics(diagnostics, state.compilerOptions); } + function isProgramBundleEmitBuildInfo(info) { + return !!ts.outFile(info.options || {}); + } + ts.isProgramBundleEmitBuildInfo = isProgramBundleEmitBuildInfo; /** * Gets the program information to be emitted in buildInfo so that we can use it to create new program */ function getProgramBuildInfo(state, getCanonicalFileName) { - if (ts.outFile(state.compilerOptions)) - return undefined; + var outFilePath = ts.outFile(state.compilerOptions); + if (outFilePath && !state.compilerOptions.composite) + return; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); + // Convert the file name to Path here if we set the fileName instead to optimize multiple d.ts file emits and having to compute Canonical path + var latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : undefined; + if (outFilePath) { + var fileNames_1 = []; + var fileInfos_1 = []; + state.program.getRootFileNames().forEach(function (f) { + var sourceFile = state.program.getSourceFile(f); + if (!sourceFile) + return; + fileNames_1.push(relativeToBuildInfo(sourceFile.resolvedPath)); + fileInfos_1.push(sourceFile.version); + }); + var result_15 = { + fileNames: fileNames_1, + fileInfos: fileInfos_1, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsBundleEmitBuildInfo"), + outSignature: state.outSignature, + latestChangedDtsFile: latestChangedDtsFile, + }; + return result_15; + } var fileNames = []; var fileNameToFileId = new ts.Map(); var fileIdsList; var fileNamesToFileIdListId; + var emitSignatures; var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var _b, _c; var key = _a[0], value = _a[1]; // Ensure fileId var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); - var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + var oldSignature = (_b = state.oldSignatures) === null || _b === void 0 ? void 0 : _b.get(key); + var actualSignature = oldSignature !== undefined ? oldSignature || undefined : value.signature; + if (state.compilerOptions.composite) { + var file = state.program.getSourceFileByPath(key); + if (!ts.isJsonSourceFile(file) && ts.sourceFileMayBeEmitted(file, state.program)) { + var emitSignature = (_c = state.emitSignatures) === null || _c === void 0 ? void 0 : _c.get(key); + if (emitSignature !== actualSignature) { + (emitSignatures || (emitSignatures = [])).push(emitSignature === undefined ? fileId : [fileId, emitSignature]); + } + } + } return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? // If file version is same as signature, dont serialize signature @@ -120320,11 +121918,11 @@ var ts; // If file info only contains version and signature and both are same we can just write string value.version : actualSignature !== undefined ? // If signature is not same as version, encode signature in the fileInfo - signature === undefined ? + oldSignature === undefined ? // If we havent computed signature, use fileInfo as is value : // Serialize fileInfo with new updated signature - { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : + { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : // Signature of the FileInfo is undefined, serialize it as false { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }; }); @@ -120339,17 +121937,13 @@ var ts; if (state.exportedModulesMap) { exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var _a; - if (state.currentAffectedFilesExportedModulesMap) { - if ((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(key)) { - return undefined; - } - var newValue = state.currentAffectedFilesExportedModulesMap.getValues(key); - if (newValue) { - return [toFileId(key), toFileIdListId(newValue)]; - } - } + var oldValue = (_a = state.oldExportedModulesMap) === null || _a === void 0 ? void 0 : _a.get(key); // Not in temporary cache, use existing value - return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue === undefined) + return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue) + return [toFileId(key), toFileIdListId(oldValue)]; + return undefined; }); } var semanticDiagnosticsPerFile; @@ -120360,9 +121954,7 @@ var ts; (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ toFileId(key), - state.hasReusableDiagnostic ? - value : - convertToReusableDiagnostics(value, relativeToBuildInfo) + convertToReusableDiagnostics(value, relativeToBuildInfo) ] : toFileId(key)); } @@ -120377,16 +121969,27 @@ var ts; } } } - return { + var changeFileSet; + if (state.changedFilesSet.size) { + for (var _d = 0, _e = ts.arrayFrom(state.changedFilesSet.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { + var path = _e[_d]; + (changeFileSet || (changeFileSet = [])).push(toFileId(path)); + } + } + var result = { fileNames: fileNames, fileInfos: fileInfos, - options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsMultiFileEmitBuildInfo"), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, affectedFilesPendingEmit: affectedFilesPendingEmit, + changeFileSet: changeFileSet, + emitSignatures: emitSignatures, + latestChangedDtsFile: latestChangedDtsFile, }; + return result; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } @@ -120411,24 +122014,21 @@ var ts; } return fileIdListId; } - } - function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { - var result; - var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var name = _a[_i]; - var optionKey = name.toLowerCase(); - var optionInfo = optionsNameMap.get(optionKey); - if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || - // We need to store `strict`, even though it won't be examined directly, so that the - // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly from the buildinfo - optionKey === "strict" || - // We need to store these to determine whether `lib` files need to be rechecked. - optionKey === "skiplibcheck" || optionKey === "skipdefaultlibcheck") { - (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); + /** + * @param optionKey key of CommandLineOption to use to determine if the option should be serialized in tsbuildinfo + */ + function convertToProgramBuildInfoCompilerOptions(options, optionKey) { + var result; + var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo[optionKey]) { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfoEnsuringAbsolutePath); + } } + return result; } - return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { if (option) { @@ -120502,6 +122102,41 @@ var ts; return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; } ts.getBuilderCreationParameters = getBuilderCreationParameters; + function getTextHandlingSourceMapForSignature(text, data) { + return (data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text; + } + function computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data) { + var _a; + text = getTextHandlingSourceMapForSignature(text, data); + var sourceFileDirectory; + if ((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length) { + text += data.diagnostics.map(function (diagnostic) { + return "".concat(locationInfo(diagnostic)).concat(ts.DiagnosticCategory[diagnostic.category]).concat(diagnostic.code, ": ").concat(flattenDiagnosticMessageText(diagnostic.messageText)); + }).join("\n"); + } + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(text); + function flattenDiagnosticMessageText(diagnostic) { + return ts.isString(diagnostic) ? + diagnostic : + diagnostic === undefined ? + "" : + !diagnostic.next ? + diagnostic.messageText : + diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText).join("\n"); + } + function locationInfo(diagnostic) { + if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) + return "(".concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + if (sourceFileDirectory === undefined) + sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath); + return "".concat(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceFileDirectory, diagnostic.file.resolvedPath, getCanonicalFileName)), "(").concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + } + } + ts.computeSignatureWithDiagnostics = computeSignatureWithDiagnostics; + function computeSignature(text, computeHash, data) { + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); + } + ts.computeSignature = computeSignature; function createBuilderProgram(kind, _a) { var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; // Return same program if underlying program doesnt change @@ -120520,7 +122155,6 @@ var ts; */ var computeHash = ts.maybeBind(host, host.createHash); var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); - var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 @@ -120529,21 +122163,13 @@ var ts; var getState = function () { return state; }; var builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics); builderProgram.getState = getState; - builderProgram.backupState = function () { - ts.Debug.assert(backupState === undefined); - backupState = cloneBuilderProgramState(state); - }; - builderProgram.restoreState = function () { - state = ts.Debug.checkDefined(backupState); - backupState = undefined; - }; + builderProgram.saveEmitState = function () { return backupBuilderProgramEmitState(state); }; + builderProgram.restoreEmitState = function (saved) { return restoreBuilderProgramEmitState(state, saved); }; + builderProgram.hasChangedEmitSignature = function () { return !!state.hasChangedEmitSignature; }; builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); }; builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; builderProgram.emit = emit; - builderProgram.releaseProgram = function () { - releaseCache(state); - backupState = undefined; - }; + builderProgram.releaseProgram = function () { return releaseCache(state); }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; } @@ -120570,7 +122196,7 @@ var ts; * in that order would be used to write the files */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); var emitKind = 1 /* BuilderFileEmit.Full */; var isPendingEmitFile = false; if (!affected) { @@ -120601,34 +122227,68 @@ var ts; return toAffectedFileEmitResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, affected !== state.program && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* BuilderFileEmit.DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile); } - function getWriteFileUpdatingSignatureCallback(writeFile) { + function getWriteFileCallback(writeFile, customTransformers) { return function (fileName, text, writeByteOrderMark, onError, sourceFiles, data) { - var _a; + var _a, _b, _c, _d, _e, _f, _g; if (ts.isDeclarationFileName(fileName)) { - ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); - var file = sourceFiles[0]; - var info = state.fileInfos.get(file.resolvedPath); - var signature = ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.get(file.resolvedPath)) || info.signature; - if (signature === file.version) { - var newSignature = (computeHash || ts.generateDjb2Hash)((data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text); - if (newSignature !== file.version) { // Update it - if (host.storeFilesChangingSignatureDuringEmit) - (state.filesChangingSignature || (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); - if (state.exportedModulesMap) - ts.BuilderState.updateExportedModules(file, file.exportedModulesFromDeclarationEmit, state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap())); - if (state.affectedFiles && state.affectedFilesIndex < state.affectedFiles.length) { - state.currentAffectedFilesSignatures.set(file.resolvedPath, newSignature); - } - else { - info.signature = newSignature; - if (state.exportedModulesMap) - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + if (!ts.outFile(state.compilerOptions)) { + ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); + var emitSignature = void 0; + if (!customTransformers) { + var file = sourceFiles[0]; + var info = state.fileInfos.get(file.resolvedPath); + if (info.signature === file.version) { + var signature = computeSignatureWithDiagnostics(file, text, computeHash, getCanonicalFileName, data); + // With d.ts diagnostics they are also part of the signature so emitSignature will be different from it since its just hash of d.ts + if (!((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length)) + emitSignature = signature; + if (signature !== file.version) { // Update it + if (host.storeFilesChangingSignatureDuringEmit) + ((_b = state.filesChangingSignature) !== null && _b !== void 0 ? _b : (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); + if (state.exportedModulesMap) + ts.BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit); + if (state.affectedFiles) { + // Keep old signature so we know what to undo if cancellation happens + var existing = (_c = state.oldSignatures) === null || _c === void 0 ? void 0 : _c.get(file.resolvedPath); + if (existing === undefined) + ((_d = state.oldSignatures) !== null && _d !== void 0 ? _d : (state.oldSignatures = new ts.Map())).set(file.resolvedPath, info.signature || false); + info.signature = signature; + } + else { + // These are directly commited + info.signature = signature; + (_e = state.oldExportedModulesMap) === null || _e === void 0 ? void 0 : _e.clear(); + } + } } } + // Store d.ts emit hash so later can be compared to check if d.ts has changed. + // Currently we do this only for composite projects since these are the only projects that can be referenced by other projects + // and would need their d.ts change time in --build mode + if (state.compilerOptions.composite) { + var filePath = sourceFiles[0].resolvedPath; + var oldSignature = (_f = state.emitSignatures) === null || _f === void 0 ? void 0 : _f.get(filePath); + emitSignature !== null && emitSignature !== void 0 ? emitSignature : (emitSignature = computeSignature(text, computeHash, data)); + // Dont write dts files if they didn't change + if (emitSignature === oldSignature) + return; + ((_g = state.emitSignatures) !== null && _g !== void 0 ? _g : (state.emitSignatures = new ts.Map())).set(filePath, emitSignature); + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; + } + } + else if (state.compilerOptions.composite) { + var newSignature = computeSignature(text, computeHash, data); + // Dont write dts files if they didn't change + if (newSignature === state.outSignature) + return; + state.outSignature = newSignature; + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; } } if (writeFile) @@ -120694,8 +122354,8 @@ var ts; } } } - return ts.Debug.checkDefined(state.program).emit(targetSourceFile, !ts.outFile(state.compilerOptions) && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + return ts.Debug.checkDefined(state.program).emit(targetSourceFile, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers); } /** @@ -120704,7 +122364,7 @@ var ts; */ function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { while (true) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); if (!affected) { // Done return undefined; @@ -120784,29 +122444,59 @@ var ts; { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; } ts.toBuilderStateFileInfo = toBuilderStateFileInfo; - function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { - var _a; + function createBuilderProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a, _b, _c, _d; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var filePaths = program.fileNames.map(toPath); - var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); - var fileInfos = new ts.Map(); - program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); - var state = { - fileInfos: fileInfos, - compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, - referencedMap: toManyToManyPathMap(program.referencedMap), - exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), - hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), - affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, - }; + var state; + var filePaths; + var filePathsSetList; + var latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : undefined; + if (isProgramBundleEmitBuildInfo(program)) { + state = { + fileInfos: new ts.Map(), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + latestChangedDtsFile: latestChangedDtsFile, + outSignature: program.outSignature, + }; + } + else { + filePaths = (_a = program.fileNames) === null || _a === void 0 ? void 0 : _a.map(toPath); + filePathsSetList = (_b = program.fileIdsList) === null || _b === void 0 ? void 0 : _b.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); + var fileInfos_2 = new ts.Map(); + var emitSignatures_1 = ((_c = program.options) === null || _c === void 0 ? void 0 : _c.composite) && !ts.outFile(program.options) ? new ts.Map() : undefined; + program.fileInfos.forEach(function (fileInfo, index) { + var path = toFilePath(index + 1); + var stateFileInfo = toBuilderStateFileInfo(fileInfo); + fileInfos_2.set(path, stateFileInfo); + if (emitSignatures_1 && stateFileInfo.signature) + emitSignatures_1.set(path, stateFileInfo.signature); + }); + (_d = program.emitSignatures) === null || _d === void 0 ? void 0 : _d.forEach(function (value) { + if (ts.isNumber(value)) + emitSignatures_1.delete(toFilePath(value)); + else + emitSignatures_1.set(toFilePath(value[0]), value[1]); + }); + state = { + fileInfos: fileInfos_2, + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toManyToManyPathMap(program.referencedMap), + exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), + hasReusableDiagnostic: true, + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, + changedFilesSet: new ts.Set(ts.map(program.changeFileSet, toFilePath)), + latestChangedDtsFile: latestChangedDtsFile, + emitSignatures: (emitSignatures_1 === null || emitSignatures_1 === void 0 ? void 0 : emitSignatures_1.size) ? emitSignatures_1 : undefined, + }; + } return { getState: function () { return state; }, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: ts.notImplemented, getProgramOrUndefined: ts.returnUndefined, releaseProgram: ts.noop, @@ -120826,6 +122516,7 @@ var ts; getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented, emitBuildInfo: ts.notImplemented, close: ts.noop, + hasChangedEmitSignature: ts.returnFalse, }; function toPath(path) { return ts.toPath(path, buildInfoDirectory, getCanonicalFileName); @@ -120851,12 +122542,24 @@ var ts; return map; } } - ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; + ts.createBuilderProgramUsingProgramBuildInfo = createBuilderProgramUsingProgramBuildInfo; + function getBuildInfoFileVersionMap(program, buildInfoPath, host) { + var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var fileInfos = new ts.Map(); + program.fileInfos.forEach(function (fileInfo, index) { + var path = ts.toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName); + var version = ts.isString(fileInfo) ? fileInfo : fileInfo.version; // eslint-disable-line @typescript-eslint/no-unnecessary-type-assertion + fileInfos.set(path, version); + }); + return fileInfos; + } + ts.getBuildInfoFileVersionMap = getBuildInfoFileVersionMap; function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { return { getState: ts.notImplemented, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: getProgram, getProgramOrUndefined: function () { return getState().program; }, releaseProgram: function () { return getState().program = undefined; }, @@ -120916,7 +122619,7 @@ var ts; * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" * @param dirPath */ - function canWatchDirectory(dirPath) { + function canWatchDirectoryOrFile(dirPath) { var rootLength = ts.getRootLength(dirPath); if (dirPath.length === rootLength) { // Ignore "/", "c:/" @@ -120953,15 +122656,19 @@ var ts; } return true; } - ts.canWatchDirectory = canWatchDirectory; + ts.canWatchDirectoryOrFile = canWatchDirectoryOrFile; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var resolutionsWithFailedLookups = []; + var resolutionsWithOnlyAffectingLocations = []; var resolvedFileToResolution = ts.createMultiMap(); + var impliedFormatPackageJsons = new ts.Map(); var hasChangedAutomaticTypeDirectiveNames = false; + var affectingPathChecksForFile; + var affectingPathChecks; var failedLookupChecks; var startsWithPathChecks; var isInDirectoryChecks; @@ -120988,6 +122695,7 @@ var ts; var failedLookupDefaultExtensions = [".ts" /* Extension.Ts */, ".tsx" /* Extension.Tsx */, ".js" /* Extension.Js */, ".jsx" /* Extension.Jsx */, ".json" /* Extension.Json */]; var customFailedLookupPaths = new ts.Map(); var directoryWatchesOfFailedLookups = new ts.Map(); + var fileWatchesOfAffectingLocations = new ts.Map(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0; @@ -120999,7 +122707,7 @@ var ts; finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + startCachingPerDirectoryResolution: startCachingPerDirectoryResolution, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -121030,6 +122738,7 @@ var ts; } function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + ts.clearMap(fileWatchesOfAffectingLocations, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); @@ -121037,12 +122746,15 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; + resolutionsWithOnlyAffectingLocations.length = 0; failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; - // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update - // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - clearPerDirectoryResolutions(); + affectingPathChecks = undefined; + affectingPathChecksForFile = undefined; + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); + impliedFormatPackageJsons.clear(); hasChangedAutomaticTypeDirectiveNames = false; } function startRecordingFilesWithChangedResolutions() { @@ -121074,25 +122786,60 @@ var ts; return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } - function clearPerDirectoryResolutions() { - moduleResolutionCache.clear(); - typeReferenceDirectiveResolutionCache.clear(); + function startCachingPerDirectoryResolution() { + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } - function finishCachingPerDirectoryResolution() { + function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = undefined; - clearPerDirectoryResolutions(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + // Update file watches + if (newProgram !== oldProgram) { + newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFiles().forEach(function (newFile) { + var _a, _b, _c; + var expected = ts.isExternalOrCommonJsModule(newFile) ? (_b = (_a = newFile.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0 : 0; + var existing = (_c = impliedFormatPackageJsons.get(newFile.path)) !== null && _c !== void 0 ? _c : ts.emptyArray; + for (var i = existing.length; i < expected; i++) { + createFileWatcherOfAffectingLocation(newFile.packageJsonLocations[i], /*forResolution*/ false); + } + if (existing.length > expected) { + for (var i = expected; i < existing.length; i++) { + fileWatchesOfAffectingLocations.get(existing[i]).files--; + } + } + if (expected) + impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations); + else + impliedFormatPackageJsons.delete(newFile.path); + }); + impliedFormatPackageJsons.forEach(function (existing, path) { + if (!(newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFileByPath(path))) { + existing.forEach(function (location) { return fileWatchesOfAffectingLocations.get(location).files--; }); + impliedFormatPackageJsons.delete(path); + } + }); + } directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); + fileWatchesOfAffectingLocations.forEach(function (watcher, path) { + if (watcher.files === 0 && watcher.resolutions === 0) { + fileWatchesOfAffectingLocations.delete(path); + watcher.watcher.close(); + } + }); hasChangedAutomaticTypeDirectiveNames = false; } function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference, _containingSourceFile, mode) { - var _a; + var _a, _b; var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { @@ -121103,11 +122850,12 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _c = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _c.resolvedModule, failedLookupLocations = _c.failedLookupLocations, affectingLocations = _c.affectingLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = primaryResult.affectingLocations).push.apply(_b, affectingLocations); return primaryResult; } } @@ -121312,7 +123060,7 @@ var ts; } // If the directory is node_modules use it to watch, always watch it recursively if (ts.isNodeModulesDirectory(dirPath)) { - return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + return canWatchDirectoryOrFile(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -121330,7 +123078,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + return canWatchDirectoryOrFile(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -121358,10 +123106,11 @@ var ts; } function watchFailedLookupLocationOfResolution(resolution) { ts.Debug.assert(!!resolution.refCount); - var failedLookupLocations = resolution.failedLookupLocations; - if (!failedLookupLocations.length) + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (!failedLookupLocations.length && !affectingLocations.length) return; - resolutionsWithFailedLookups.push(resolution); + if (failedLookupLocations.length) + resolutionsWithFailedLookups.push(resolution); var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; @@ -121388,12 +123137,87 @@ var ts; // This is always non recursive setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } + watchAffectingLocationsOfResolution(resolution, !failedLookupLocations.length); + } + function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { + ts.Debug.assert(!!resolution.refCount); + var affectingLocations = resolution.affectingLocations; + if (!affectingLocations.length) + return; + if (addToResolutionsWithOnlyAffectingLocations) + resolutionsWithOnlyAffectingLocations.push(resolution); + // Watch package json + for (var _i = 0, affectingLocations_1 = affectingLocations; _i < affectingLocations_1.length; _i++) { + var affectingLocation = affectingLocations_1[_i]; + createFileWatcherOfAffectingLocation(affectingLocation, /*forResolution*/ true); + } + } + function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) { + var fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation); + if (fileWatcher) { + if (forResolution) + fileWatcher.resolutions++; + else + fileWatcher.files++; + return; + } + var locationToWatch = affectingLocation; + if (resolutionHost.realpath) { + locationToWatch = resolutionHost.realpath(affectingLocation); + if (affectingLocation !== locationToWatch) { + var fileWatcher_1 = fileWatchesOfAffectingLocations.get(locationToWatch); + if (fileWatcher_1) { + if (forResolution) + fileWatcher_1.resolutions++; + else + fileWatcher_1.files++; + fileWatcher_1.paths.add(affectingLocation); + fileWatchesOfAffectingLocations.set(affectingLocation, fileWatcher_1); + return; + } + } + } + var paths = new ts.Set(); + paths.add(locationToWatch); + var actualWatcher = canWatchDirectoryOrFile(resolutionHost.toPath(locationToWatch)) ? + resolutionHost.watchAffectingFileLocation(locationToWatch, function (fileName, eventKind) { + cachedDirectoryStructureHost === null || cachedDirectoryStructureHost === void 0 ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + paths.forEach(function (path) { + if (watcher.resolutions) + (affectingPathChecks !== null && affectingPathChecks !== void 0 ? affectingPathChecks : (affectingPathChecks = new ts.Set())).add(path); + if (watcher.files) + (affectingPathChecksForFile !== null && affectingPathChecksForFile !== void 0 ? affectingPathChecksForFile : (affectingPathChecksForFile = new ts.Set())).add(path); + packageJsonMap === null || packageJsonMap === void 0 ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); + }); + resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); + }) : ts.noopFileWatcher; + var watcher = { + watcher: actualWatcher !== ts.noopFileWatcher ? { + close: function () { + actualWatcher.close(); + // Ensure when watching symlinked package.json, we can close the actual file watcher only once + actualWatcher = ts.noopFileWatcher; + } + } : actualWatcher, + resolutions: forResolution ? 1 : 0, + files: forResolution ? 0 : 1, + paths: paths, + }; + fileWatchesOfAffectingLocations.set(locationToWatch, watcher); + if (affectingLocation !== locationToWatch) { + fileWatchesOfAffectingLocations.set(affectingLocation, watcher); + paths.add(affectingLocation); + } } function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { var program = resolutionHost.getCurrentProgram(); if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) { resolutions.forEach(watchFailedLookupLocationOfResolution); } + else { + resolutions.forEach(function (resolution) { return watchAffectingLocationsOfResolution(resolution, /*addToResolutionWithOnlyAffectingLocations*/ true); }); + } } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); @@ -121415,38 +123239,44 @@ var ts; if (resolved && resolved.resolvedFileName) { resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution); } - if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { - // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups - return; - } - var failedLookupLocations = resolution.failedLookupLocations; - var removeAtRoot = false; - for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { - var failedLookupLocation = failedLookupLocations_2[_i]; - var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (toWatch) { - var dirPath = toWatch.dirPath; - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - if (dirPath === rootPath) { - removeAtRoot = true; - } - else { - removeDirectoryWatcher(dirPath); - } } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + else if (affectingLocations.length) { + ts.unorderedRemoveItem(resolutionsWithOnlyAffectingLocations, resolution); } - if (removeAtRoot) { - removeDirectoryWatcher(rootPath); + for (var _a = 0, affectingLocations_2 = affectingLocations; _a < affectingLocations_2.length; _a++) { + var affectingLocation = affectingLocations_2[_a]; + var watcher = fileWatchesOfAffectingLocations.get(affectingLocation); + watcher.resolutions--; } } function removeDirectoryWatcher(dirPath) { @@ -121500,7 +123330,7 @@ var ts; resolution.isInvalidated = invalidated = true; for (var _a = 0, _b = ts.Debug.checkDefined(resolution.files); _a < _b.length; _a++) { var containingFilePath = _b[_a]; - (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); // When its a file with inferred types resolution, invalidate type reference directive resolution hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile); } @@ -121525,7 +123355,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = new ts.Set())).add(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -121543,7 +123373,7 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { @@ -121555,7 +123385,7 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); // If the invalidated file is from a node_modules package, invalidate everything else // in the package since we might not get notifications for other files in the package. // This hardens our logic against unreliable file watchers. @@ -121567,22 +123397,46 @@ var ts; resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { - return false; + var _a; + var invalidated = false; + if (affectingPathChecksForFile) { + (_a = resolutionHost.getCurrentProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFiles().forEach(function (f) { + if (ts.some(f.packageJsonLocations, function (location) { return affectingPathChecksForFile.has(location); })) { + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(f.path); + invalidated = true; + } + }); + affectingPathChecksForFile = undefined; + } + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks && !affectingPathChecks) { + return invalidated; + } + invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach(function (_value, path) { return isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : undefined; }); } - var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; + invalidated = invalidateResolutions(resolutionsWithOnlyAffectingLocations, canInvalidatedFailedLookupResolutionWithAffectingLocation) || invalidated; + affectingPathChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { - return resolution.failedLookupLocations.some(function (location) { - var locationPath = resolutionHost.toPath(location); - return ts.contains(failedLookupChecks, locationPath) || - ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || - (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); - }); + if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) + return true; + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) + return false; + return resolution.failedLookupLocations.some(function (location) { return isInvalidatedFailedLookup(resolutionHost.toPath(location)); }); + } + function isInvalidatedFailedLookup(locationPath) { + return (failedLookupChecks === null || failedLookupChecks === void 0 ? void 0 : failedLookupChecks.has(locationPath)) || + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + ts.firstDefinedIterator((isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath) ? true : undefined; }); + } + function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) { + return !!affectingPathChecks && resolution.affectingLocations.some(function (location) { return affectingPathChecks.has(location); }); } function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); @@ -121648,7 +123502,7 @@ var ts; function directoryExistsForTypeRootWatch(nodeTypesDirectory) { var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); var dirPath = resolutionHost.toPath(dir); - return dirPath === rootPath || canWatchDirectory(dirPath); + return dirPath === rootPath || canWatchDirectoryOrFile(dirPath); } } ts.createResolutionCache = createResolutionCache; @@ -121759,7 +123613,7 @@ var ts; var info = getInfo(importingSourceFileName, host); var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences, options); return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode); }) || - getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences); + getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences, options) { if (options === void 0) { options = {}; } @@ -121842,7 +123696,7 @@ var ts; return nodeModulesSpecifiers; } if (!specifier && !modulePath.isRedirect) { - var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences); + var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); if (ts.pathIsBareSpecifier(local)) { pathsSpecifiers = ts.append(pathsSpecifiers, local); } @@ -121870,7 +123724,7 @@ var ts; var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); return { getCanonicalFileName: getCanonicalFileName, importingSourceFileName: importingSourceFileName, sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, _a) { + function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, _a) { var ending = _a.ending, relativePreference = _a.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var sourceDirectory = info.sourceDirectory, getCanonicalFileName = info.getCanonicalFileName; @@ -121884,9 +123738,8 @@ var ts; if (!relativeToBaseUrl) { return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); - var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths; + var fromPaths = paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, getAllowedEndings(ending, compilerOptions, importMode), host, compilerOptions); + var nonRelative = fromPaths === undefined && baseUrl !== undefined ? removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) : fromPaths; if (!nonRelative) { return relativePath; } @@ -121972,9 +123825,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -121994,10 +123847,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_17 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_17) + return result_17; } }); }); @@ -122039,7 +123892,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_32 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -122063,9 +123916,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_10 = _loop_32(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_10 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -122121,28 +123974,102 @@ var ts; return ambientModuleDeclare.name.text; } } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + function getAllowedEndings(preferredEnding, compilerOptions, importMode) { + if (ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && importMode === ts.ModuleKind.ESNext) { + return [2 /* Ending.JsExtension */]; + } + switch (preferredEnding) { + case 2 /* Ending.JsExtension */: return [2 /* Ending.JsExtension */, 0 /* Ending.Minimal */, 1 /* Ending.Index */]; + case 1 /* Ending.Index */: return [1 /* Ending.Index */, 0 /* Ending.Minimal */, 2 /* Ending.JsExtension */]; + case 0 /* Ending.Minimal */: return [0 /* Ending.Minimal */, 1 /* Ending.Index */, 2 /* Ending.JsExtension */]; + default: ts.Debug.assertNever(preferredEnding); + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(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, + // meaning a '.ts' or '.d.ts' extension is allowed to resolve. This is distinct from the case where a '*' substitution + // causes a module specifier to have an extension, i.e. the extension comes from the module specifier in a JS/TS file + // and matches the '*'. For example: + // + // Module Specifier | Path Mapping (key: [pattern]) | Interpolation | Resolution Action + // ---------------------->------------------------------->--------------------->--------------------------------------------------------------- + // import "@app/foo" -> "@app/*": ["./src/app/*.ts"] -> "./src/app/foo.ts" -> tryFile("./src/app/foo.ts") || [continue resolution algorithm] + // import "@app/foo.ts" -> "@app/*": ["./src/app/*"] -> "./src/app/foo.ts" -> [continue resolution algorithm] + // + // (https://github.com/microsoft/TypeScript/blob/ad4ded80e1d58f0bf36ac16bea71bc10d9f09895/src/compiler/moduleNameResolver.ts#L2509-L2516) + // + // The interpolation produced by both scenarios is identical, but only in the former, where the extension is encoded in + // the path mapping rather than in the module specifier, will we prioritize a file lookup on the interpolation result. + // (In fact, currently, the latter scenario will necessarily fail since no resolution mode recognizes '.ts' as a valid + // extension for a module specifier.) + // + // Here, this means we need to be careful about whether we generate a match from the target filename (typically with a + // .ts extension) or the possible relative module specifiers representing that file: + // + // Filename | Relative Module Specifier Candidates | Path Mapping | Filename Result | Module Specifier Results + // --------------------<----------------------------------------------<------------------------------<-------------------||---------------------------- + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*.d.ts"] <- @app/haha || (none) + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*"] <- (none) || @app/haha, @app/haha.js + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*.d.ts"] <- @app/foo/index || (none) + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*"] <- (none) || @app/foo, @app/foo/index, @app/foo/index.js + // dist/wow.js.js <- dist/wow.js, dist/wow.js.js <- "@app/*": ["./dist/*.js"] <- @app/wow.js || @app/wow, @app/wow.js + // + // The "Filename Result" can be generated only if `pattern` has an extension. Care must be taken that the list of + // relative module specifiers to run the interpolation (a) is actually valid for the module resolution mode, (b) takes + // into account the existence of other files (e.g. 'dist/wow.js' cannot refer to 'dist/wow.js.js' if 'dist/wow.js' + // exists) and (c) that they are ordered by preference. The last row shows that the filename result and module + // specifier results are not mutually exclusive. Note that the filename result is a higher priority in module + // resolution, but as long criteria (b) above is met, I don't think its result needs to be the highest priority result + // in module specifier generation. I have included it last, as it's difficult to tell exactly where it should be + // sorted among the others for a particular value of `importModuleSpecifierEnding`. + var candidates = allowedEndings.map(function (ending) { return ({ + ending: ending, + value: removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) + }); }); + if (ts.tryGetExtensionFromPath(pattern)) { + candidates.push({ ending: undefined, value: relativeToBaseUrl }); + } if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix) || - !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); - return key.replace("*", matchedStar); + var prefix = pattern.substring(0, indexOfStar); + var suffix = pattern.substring(indexOfStar + 1); + for (var _b = 0, candidates_3 = candidates; _b < candidates_3.length; _b++) { + var _c = candidates_3[_b], ending = _c.ending, value = _c.value; + if (value.length >= prefix.length + suffix.length && + ts.startsWith(value, prefix) && + ts.endsWith(value, suffix) && + validateEnding({ ending: ending, value: value })) { + var matchedStar = value.substring(prefix.length, value.length - suffix.length); + return { value: key.replace("*", matchedStar) }; + } } } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; + else if (ts.some(candidates, function (c) { return c.ending !== 0 /* Ending.Minimal */ && pattern === c.value; }) || + ts.some(candidates, function (c) { return c.ending === 0 /* Ending.Minimal */ && pattern === c.value && validateEnding(c); })) { + return { value: key }; } + }; + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } + function validateEnding(_a) { + var ending = _a.ending, value = _a.value; + // Optimization: `removeExtensionAndIndexPostFix` can query the file system (a good bit) if `ending` is `Minimal`, the basename + // is 'index', and a `host` is provided. To avoid that until it's unavoidable, we ran the function with no `host` above. Only + // here, after we've checked that the minimal ending is indeed a match (via the length and prefix/suffix checks / `some` calls), + // do we check that the host-validated result is consistent with the answer we got before. If it's not, it falls back to the + // `Ending.Index` result, which should already be in the list of candidates if `Minimal` was. (Note: the assumption here is + // that every module resolution mode that supports dropping extensions also supports dropping `/index`. Like literally + // everything else in this file, this logic needs to be updated if that's not true in some future module resolution mode.) + return ending !== 0 /* Ending.Minimal */ || value === removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions, host); + } } var MatchingMode; (function (MatchingMode) { @@ -122238,10 +124165,10 @@ var ts; return undefined; } // Simplify the full file path to something that can be resolved by Node. + var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var moduleSpecifier = path; var isPackageRootPath = false; if (!packageNameOnly) { - var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var packageRootIndex = parts.packageRootIndex; var moduleFileName = void 0; while (true) { @@ -122290,15 +124217,13 @@ var ts; var packageRootPath = path.substring(0, packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); var moduleFileToTry = path; + var maybeBlockedByTypesVersions = false; var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) { var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); + var importMode = overrideMode || importingSourceFile.impliedNodeFormat; if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { - // `conditions` *could* be made to go against `importingSourceFile.impliedNodeFormat` if something wanted to generate - // an ImportEqualsDeclaration in an ESM-implied file or an ImportCall in a CJS-implied file. But since this function is - // usually called to conjure an import out of thin air, we don't have an existing usage to call `getModeForUsageAtIndex` - // with, so for now we just stick with the mode of the file. - var conditions = ["node", overrideMode || importingSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext ? "import" : "require", "types"]; + var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"]; var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, ts.getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions) : undefined; @@ -122317,16 +124242,26 @@ var ts; : undefined; if (versionPaths) { var subModuleName = path.slice(packageRootPath.length + 1); - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Ending.Minimal */, options), versionPaths.paths); - if (fromPaths !== undefined) { + var fromPaths = tryGetModuleNameFromPaths(subModuleName, versionPaths.paths, getAllowedEndings(preferences.ending, options, importMode), host, options); + if (fromPaths === undefined) { + maybeBlockedByTypesVersions = true; + } + else { moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths); } } // If the file is the main module, it can be imported by the package name var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; - if (ts.isString(mainFileRelative)) { + if (ts.isString(mainFileRelative) && !(maybeBlockedByTypesVersions && ts.matchPatternOrExact(ts.tryParsePatterns(versionPaths.paths), mainFileRelative))) { + // The 'main' file is also subject to mapping through typesVersions, and we couldn't come up with a path + // explicitly through typesVersions, so if it matches a key in typesVersions now, it's not reachable. + // (The only way this can happen is if some file in a package that's not resolvable from outside the + // package got pulled into the program anyway, e.g. transitively through a file that *is* reachable. It + // happens very easily in fourslash tests though, since every test file listed gets included. See + // importNameCodeFix_typesVersions.ts for an example.) var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + // ^ An arbitrary removal of file extension for this comparison is almost certainly wrong return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry }; } } @@ -122621,23 +124556,46 @@ var ts; var file = _c[_i]; write("".concat(toFileName(file, relativeFileName))); (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write(" ".concat(fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText)); }); - (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); + (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); } } ts.explainFiles = explainFiles; - function explainIfFileIsRedirect(file, fileNameConvertor) { + function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { + var _a; var result; if (file.path !== file.resolvedPath) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); } if (file.redirectInfo) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); } + if (ts.isExternalOrCommonJsModule(file)) { + switch (file.impliedNodeFormat) { + case ts.ModuleKind.ESNext: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + break; + case ts.ModuleKind.CommonJS: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, file.packageJsonScope.packageJsonContent.type ? + ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : + ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + else if ((_a = file.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found)); + } + break; + } + } return result; } - ts.explainIfFileIsRedirect = explainIfFileIsRedirect; + ts.explainIfFileIsRedirectAndImpliedFormat = explainIfFileIsRedirectAndImpliedFormat; function getMatchedFileSpec(program, fileName) { var _a; var configFile = program.getCompilerOptions().configFile; @@ -122654,6 +124612,9 @@ var ts; var configFile = program.getCompilerOptions().configFile; if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedIncludeSpecs)) return undefined; + // Return true if its default include spec + if (configFile.configFileSpecs.isDefaultIncludeSpec) + return true; var isJsonFile = ts.fileExtensionIs(fileName, ".json" /* Extension.Json */); var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); var useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); @@ -122719,11 +124680,13 @@ var ts; if (matchedByFiles) return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Part_of_files_list_in_tsconfig_json); var matchedByInclude = getMatchedIncludeSpec(program, fileName); - return matchedByInclude ? + return ts.isString(matchedByInclude) ? ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) : - // Could be additional files specified as roots - ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation); + // Could be additional files specified as roots or matched by default include + ts.chainDiagnosticMessages(/*details*/ undefined, matchedByInclude ? + ts.Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : + ts.Diagnostics.Root_file_specified_for_compilation); case ts.FileIncludeKind.SourceFromProjectReference: case ts.FileIncludeKind.OutputFromProjectReference: var isOutput = reason.kind === ts.FileIncludeKind.OutputFromProjectReference; @@ -122842,11 +124805,19 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", + AffectingFileLocation: "File location affecting resolution", TypeRoots: "Type roots", ConfigFileOfReferencedProject: "Config file of referened project", ExtendedConfigOfReferencedProject: "Extended config file of referenced project", WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", PackageJson: "package.json file", + ClosedScriptInfo: "Closed Script info", + ConfigFileForInferredRoot: "Config file for the inferred project root", + NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache", + MissingSourceMapFile: "Missing source map file", + NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root", + MissingGeneratedFile: "Missing generated file", + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -122955,6 +124926,7 @@ var ts; createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, storeFilesChangingSignatureDuringEmit: system.storeFilesChangingSignatureDuringEmit, + now: ts.maybeBind(system, system.now), }; } ts.createProgramHost = createProgramHost; @@ -123022,20 +124994,27 @@ var ts; var ts; (function (ts) { function readBuilderProgram(compilerOptions, host) { - if (ts.outFile(compilerOptions)) - return undefined; var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions); if (!buildInfoPath) return undefined; - var content = host.readFile(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); + var buildInfo; + if (host.getBuildInfo) { + // host provides buildinfo, get it from there. This allows host to cache it + buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); + if (!buildInfo) + return undefined; + } + else { + var content = host.readFile(buildInfoPath); + if (!content) + return undefined; + buildInfo = ts.getBuildInfo(content); + } if (buildInfo.version !== ts.version) return undefined; if (!buildInfo.program) return undefined; - return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); + return ts.createBuilderProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); } ts.readBuilderProgram = readBuilderProgram; function createIncrementalCompilerHost(options, system) { @@ -123088,14 +125067,12 @@ var ts; var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc var missingFilesMap; // Map of file watchers for the missing files - var packageJsonMap; // map of watchers for package json files used in module resolution var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations var parsedConfigs; // Parsed commandline and watching cached for referenced projects var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation - var changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution var reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files @@ -123152,6 +125129,7 @@ var ts; compilerHost.getCompilationSettings = function () { return compilerOptions; }; compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect); compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); }; + compilerHost.watchAffectingFileLocation = function (file, cb) { return watchFile(file, cb, ts.PollingInterval.High, watchOptions, ts.WatchType.AffectingFileLocation); }; compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); }; compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations; @@ -123185,6 +125163,9 @@ var ts; return host.resolveTypeReferenceDirectives.apply(host, args); }) : (function (typeDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference, containingFileMode); }); + compilerHost.getModuleResolutionCache = host.resolveModuleNames ? + ts.maybeBind(host, host.getModuleResolutionCache) : + (function () { return resolutionCache.getModuleResolutionCache(); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); @@ -123234,10 +125215,6 @@ var ts; }); parsedConfigs = undefined; } - if (packageJsonMap) { - ts.clearMap(packageJsonMap, ts.closeFileWatcher); - packageJsonMap = undefined; - } } function getCurrentBuilderProgram() { return builderProgram; @@ -123251,12 +125228,12 @@ var ts; var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); - if (program && (changesAffectResolution || ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions))) { + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { resolutionCache.clear(); } } // All resolutions are invalid if user provided resolutions - var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution); + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { @@ -123272,7 +125249,6 @@ var ts; } createNewProgram(hasInvalidatedResolution); } - changesAffectResolution = false; // reset for next sync reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); @@ -123292,16 +125268,11 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + var oldProgram = getCurrentProgram(); builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); - // map package json cache entries to their realpaths so we don't try to watch across symlinks - var packageCacheEntries = ts.map(resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [compilerHost.realpath ? toPath(compilerHost.realpath(path)) : path, data]; - }); - resolutionCache.finishCachingPerDirectoryResolution(); + resolutionCache.finishCachingPerDirectoryResolution(builderProgram.getProgram(), oldProgram); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath); - ts.updatePackageJsonWatch(packageCacheEntries, packageJsonMap || (packageJsonMap = new ts.Map()), watchPackageJsonLookupPath); if (needsUpdateInTypeRootWatch) { resolutionCache.updateTypeRootsWatch(); } @@ -123381,9 +125352,6 @@ var ts; sourceFilesCache.set(path, false); } } - if (sourceFile) { - sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); - } return sourceFile; } return hostSourceFile.sourceFile; @@ -123498,6 +125466,7 @@ var ts; } function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; rootFileNames = ts.getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions); if (ts.updateErrorForNoInputFiles(rootFileNames, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; @@ -123606,21 +125575,6 @@ var ts; ts.noopFileWatcher : watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } - function watchPackageJsonLookupPath(packageJsonPath) { - // If the package.json is pulled into the compilation itself (eg, via json imports), don't add a second watcher here - return sourceFilesCache.has(packageJsonPath) ? - ts.noopFileWatcher : - watchFilePath(packageJsonPath, packageJsonPath, onPackageJsonChange, ts.PollingInterval.High, watchOptions, ts.WatchType.PackageJson); - } - function onPackageJsonChange(fileName, eventKind, path) { - updateCachedSystemWithFile(fileName, path, eventKind); - // package.json changes invalidate module resolution and can change the set of loaded files - // so if we witness a change to one, we have to do a full reload - reloadLevel = ts.ConfigFileProgramReloadLevel.Full; - changesAffectResolution = true; - // Update the program - scheduleProgramUpdate(); - } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { @@ -123778,14 +125732,17 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream"; - UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate"; - UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream"; - UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["OutOfDateBuildInfo"] = 7] = "OutOfDateBuildInfo"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 8] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 9] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 10] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 11] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["UpToDateWithInputFileText"] = 12] = "UpToDateWithInputFileText"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 13] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ForceBuild"] = 14] = "ForceBuild"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); function resolveConfigFileProjectName(project) { if (ts.fileExtensionIs(project, ".json" /* Extension.Json */)) { @@ -123830,9 +125787,12 @@ var ts; function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); }); } - function newer(date1, date2) { - return date2 > date1 ? date2 : date1; + /*@internal*/ + /** Helper to use now method instead of current date for testing purposes to get consistent baselines */ + function getCurrentTime(host) { + return host.now ? host.now() : new Date(); } + ts.getCurrentTime = getCurrentTime; /*@internal*/ function isCircularBuildOrder(buildOrder) { return !!buildOrder && !!buildOrder.buildOrder; @@ -123907,6 +125867,7 @@ var ts; compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); }; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); + compilerHost.getModuleResolutionCache = ts.maybeBind(host, host.getModuleResolutionCache); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { @@ -123922,6 +125883,7 @@ var ts; return ts.loadWithTypeDirectiveCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader_4); }; } + compilerHost.getBuildInfo = function (fileName, configFilePath) { return getBuildInfo(state, fileName, toResolvedConfigFilePath(state, configFilePath), /*modifiedTime*/ undefined); }; var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -123938,8 +125900,9 @@ var ts; resolvedConfigFilePaths: new ts.Map(), configFileCache: new ts.Map(), projectStatus: new ts.Map(), - buildInfoChecked: new ts.Map(), extendedConfigCache: new ts.Map(), + buildInfoCache: new ts.Map(), + outputTimeStamps: new ts.Map(), builderPrograms: new ts.Map(), diagnostics: new ts.Map(), projectPendingBuild: new ts.Map(), @@ -123955,7 +125918,6 @@ var ts; allProjectBuildPending: true, needsSummary: true, watchAllProjectsPending: watch, - currentInvalidatedProject: undefined, // Watch state watch: watch, allWatchedWildcardDirectories: new ts.Map(), @@ -123963,6 +125925,7 @@ var ts; allWatchedConfigFiles: new ts.Map(), allWatchedExtendedConfigFiles: new ts.Map(), allWatchedPackageJsonFiles: new ts.Map(), + filesWatched: new ts.Map(), lastCachedPackageJsonLookups: new ts.Map(), timerToBuildInvalidatedProject: undefined, reportFileChangeDetected: false, @@ -124069,11 +126032,12 @@ var ts; // Config file cache ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete); - ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.buildInfoCache, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.outputTimeStamps, currentProjects, noopOnDelete); // Remove watches for the program no longer in the solution if (state.watch) { ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher }); @@ -124188,7 +126152,6 @@ var ts; })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {})); function doneInvalidatedProject(state, projectPath) { state.projectPendingBuild.delete(projectPath); - state.currentInvalidatedProject = undefined; return state.diagnostics.has(projectPath) ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; @@ -124364,21 +126327,21 @@ var ts; } function emit(writeFileCallback, cancellationToken, customTransformers) { var _a; - var _b, _c; + var _b, _c, _d; ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.Emit); // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly - program.backupState(); + var saved = program.saveEmitState(); var declDiagnostics; var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; var outputFiles = []; var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, /*write*/ undefined, - /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, + /*reportSummary*/ undefined, function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark, buildInfo: data === null || data === void 0 ? void 0 : data.buildInfo }); }, cancellationToken, /*emitOnlyDts*/ false, customTransformers || ((_c = (_b = state.host).getCustomTransformers) === null || _c === void 0 ? void 0 : _c.call(_b, project))).emitResult; // Don't emit .d.ts if there are decl file errors if (declDiagnostics) { - program.restoreState(); + program.restoreEmitState(saved); (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step); return { emitSkipped: true, @@ -124387,38 +126350,38 @@ var ts; } // Actual Emit var host = state.host, compilerHost = state.compilerHost; - var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; - var newestDeclarationFileContentChangedTime = minimumDate; - var anyDtsChanged = false; + var resultFlags = ((_d = program.hasChangedEmitSignature) === null || _d === void 0 ? void 0 : _d.call(program)) ? BuildResultFlags.None : BuildResultFlags.DeclarationOutputUnchanged; var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var options = program.getCompilerOptions(); + var isIncremental = ts.isIncrementalCompilation(options); + var outputTimeStampMap; + var now; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; - var priorChangeTime; - if (!anyDtsChanged && ts.isDeclarationFileName(name)) { - // Check for unchanged .d.ts files - if (host.fileExists(name) && state.readFileWithCache(name) === text) { - priorChangeTime = host.getModifiedTime(name); - } - else { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - anyDtsChanged = true; - } - } + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; + var path = toPath(state, name); emittedOutputs.set(toPath(state, name), name); + if (buildInfo) + setBuildInfo(state, buildInfo, projectPath, options, resultFlags); ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); - if (priorChangeTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + if (!isIncremental && state.watch) { + (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); } }); - finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); + finishEmit(emitterDiagnostics, emittedOutputs, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); return emitResult; } function emitBuildInfo(writeFileCallback, cancellationToken) { ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.EmitBuildInfo); - var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken); + var emitResult = program.emitBuildInfo(function (name, text, writeByteOrderMark, onError, sourceFiles, data) { + if (data === null || data === void 0 ? void 0 : data.buildInfo) + setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), BuildResultFlags.DeclarationOutputUnchanged); + if (writeFileCallback) + writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); + else + state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); + }, cancellationToken); if (emitResult.diagnostics.length) { reportErrors(state, emitResult.diagnostics); state.diagnostics.set(projectPath, __spreadArray(__spreadArray([], state.diagnostics.get(projectPath), true), emitResult.diagnostics, true)); @@ -124431,7 +126394,7 @@ var ts; step = BuildStep.QueueReferencingProjects; return emitResult; } - function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) { + function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) { var _a; var emitDiagnostics = emitterDiagnostics.getDiagnostics(); if (emitDiagnostics.length) { @@ -124442,13 +126405,10 @@ var ts; emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); }); } // Update time stamps for rest of the outputs - var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); + updateOutputTimestampsWorker(state, config, projectPath, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); state.diagnostics.delete(projectPath); state.projectStatus.set(projectPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ? - maximumDate : - newestDeclarationFileContentChangedTime, oldestOutputFileName: oldestOutputFileName }); afterProgramDone(state, program, config); @@ -124483,13 +126443,21 @@ var ts; ts.Debug.assert(!!outputFiles.length); var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; + var existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var _b, _c; + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; emittedOutputs.set(toPath(state, name), name); + if (buildInfo) { + if (((_b = buildInfo.program) === null || _b === void 0 ? void 0 : _b.outSignature) !== ((_c = existingBuildInfo.program) === null || _c === void 0 ? void 0 : _c.outSignature)) { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + } + setBuildInfo(state, buildInfo, projectPath, config.options, resultFlags); + } ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); }); - var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged); + var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, outputFiles[0].name, resultFlags); return { emitSkipped: false, diagnostics: emitDiagnostics }; } function executeSteps(till, cancellationToken, writeFile, customTransformers) { @@ -124539,17 +126507,11 @@ var ts; !!ts.getConfigFileParsingDiagnostics(config).length || !ts.isIncrementalCompilation(config.options); } - function getNextInvalidatedProject(state, buildOrder, reportQueue) { + function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { if (!state.projectPendingBuild.size) return undefined; if (isCircularBuildOrder(buildOrder)) return undefined; - if (state.currentInvalidatedProject) { - // Only if same buildOrder the currentInvalidated project can be sent again - return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ? - state.currentInvalidatedProject : - undefined; - } var options = state.options, projectPendingBuild = state.projectPendingBuild; for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { var project = buildOrder[projectIndex]; @@ -124582,9 +126544,9 @@ var ts; watchPackageJsonFiles(state, project, projectPath, config); } var status = getUpToDateStatus(state, config, projectPath); - verboseReportProjectStatus(state, project, status); if (!options.force) { if (status.type === ts.UpToDateStatusType.UpToDate) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Up to date, skip @@ -124594,12 +126556,20 @@ var ts; } continue; } - if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) { + if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes || status.type === ts.UpToDateStatusType.UpToDateWithInputFileText) { reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); - return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder); + return { + kind: InvalidatedProjectKind.UpdateOutputFileStamps, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config + }; } } if (status.type === ts.UpToDateStatusType.UpstreamBlocked) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); if (options.verbose) { @@ -124610,17 +126580,37 @@ var ts; continue; } if (status.type === ts.UpToDateStatusType.ContainerOnly) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Do nothing continue; } - return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ? - InvalidatedProjectKind.Build : - InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder); + return { + kind: needsBuild(state, status, config) ? + InvalidatedProjectKind.Build : + InvalidatedProjectKind.UpdateBundle, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config, + }; } return undefined; } + function createInvalidatedProjectWithInfo(state, info, buildOrder) { + verboseReportProjectStatus(state, info.project, info.status); + return info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps ? + createBuildOrUpdateInvalidedProject(info.kind, state, info.project, info.projectPath, info.projectIndex, info.config, buildOrder) : + createUpdateOutputFileStampsProject(state, info.project, info.projectPath, info.config, buildOrder); + } + function getNextInvalidatedProject(state, buildOrder, reportQueue) { + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); + if (!info) + return info; + return createInvalidatedProjectWithInfo(state, info, buildOrder); + } function listEmittedFile(_a, proj, file) { var write = _a.write; if (write && proj.options.listEmittedFiles) { @@ -124638,7 +126628,7 @@ var ts; } function afterProgramDone(state, program, config) { if (program) { - if (program && state.write) + if (state.write) ts.listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); @@ -124651,7 +126641,8 @@ var ts; state.projectCompilerOptions = state.baseCompilerOptions; } function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) { - var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions()); + // Since buildinfo has changeset and diagnostics when doing multi file emit, only --out cannot emit buildinfo if it has errors + var canEmitBuildInfo = program && !ts.outFile(program.getCompilerOptions()); reportAndStoreErrors(state, resolvedPath, diagnostics); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: "".concat(errorType, " errors") }); if (canEmitBuildInfo) @@ -124659,9 +126650,107 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } + function isFileWatcherWithModifiedTime(value) { + return !!value.watcher; + } + function getModifiedTime(state, fileName) { + var path = toPath(state, fileName); + var existing = state.filesWatched.get(path); + if (state.watch && !!existing) { + if (!isFileWatcherWithModifiedTime(existing)) + return existing; + if (existing.modifiedTime) + return existing.modifiedTime; + } + // In watch mode we store the modified times in the cache + // This is either Date | FileWatcherWithModifiedTime because we query modified times first and + // then after complete compilation of the project, watch the files so we dont want to loose these modified times. + var result = ts.getModifiedTime(state.host, fileName); + if (state.watch) { + if (existing) + existing.modifiedTime = result; + else + state.filesWatched.set(path, result); + } + return result; + } + function watchFile(state, file, callback, pollingInterval, options, watchType, project) { + var path = toPath(state, file); + var existing = state.filesWatched.get(path); + if (existing && isFileWatcherWithModifiedTime(existing)) { + existing.callbacks.push(callback); + } + else { + var watcher = state.watchFile(file, function (fileName, eventKind, modifiedTime) { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + existing.modifiedTime = modifiedTime; + existing.callbacks.forEach(function (cb) { return cb(fileName, eventKind, modifiedTime); }); + }, pollingInterval, options, watchType, project); + state.filesWatched.set(path, { callbacks: [callback], watcher: watcher, modifiedTime: existing }); + } + return { + close: function () { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + if (existing.callbacks.length === 1) { + state.filesWatched.delete(path); + ts.closeFileWatcherOf(existing); + } + else { + ts.unorderedRemoveItem(existing.callbacks, callback); + } + } + }; + } + function getOutputTimeStampMap(state, resolvedConfigFilePath) { + // Output timestamps are stored only in watch mode + if (!state.watch) + return undefined; + var result = state.outputTimeStamps.get(resolvedConfigFilePath); + if (!result) + state.outputTimeStamps.set(resolvedConfigFilePath, result = new ts.Map()); + return result; + } + function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) { + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(options); + var existing = getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath); + var modifiedTime = getCurrentTime(state.host); + if (existing) { + existing.buildInfo = buildInfo; + existing.modifiedTime = modifiedTime; + if (!(resultFlags & BuildResultFlags.DeclarationOutputUnchanged)) + existing.latestChangedDtsTime = modifiedTime; + } + else { + state.buildInfoCache.set(resolvedConfigPath, { + path: toPath(state, buildInfoPath), + buildInfo: buildInfo, + modifiedTime: modifiedTime, + latestChangedDtsTime: resultFlags & BuildResultFlags.DeclarationOutputUnchanged ? undefined : modifiedTime, + }); + } + } + function getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + return (existing === null || existing === void 0 ? void 0 : existing.path) === path ? existing : undefined; + } + function getBuildInfo(state, buildInfoPath, resolvedConfigPath, modifiedTime) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + if (existing !== undefined && existing.path === path) { + return existing.buildInfo || undefined; + } + var value = state.readFileWithCache(buildInfoPath); + var buildInfo = value ? ts.getBuildInfo(value) : undefined; + ts.Debug.assert(modifiedTime || !buildInfo); + state.buildInfoCache.set(resolvedConfigPath, { path: path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || ts.missingFileModifiedTime }); + return buildInfo; + } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = ts.getModifiedTime(state.host, configFile); + var tsconfigTime = getModifiedTime(state, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -124671,88 +126760,24 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { - var force = !!state.options.force; - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - var host = state.host; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: ts.UpToDateStatusType.Unbuildable, - reason: "".concat(inputFile, " does not exist") - }; - } - if (!force) { - var inputTime = ts.getModifiedTime(host, inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - } + var _a, _b; // Container if no files are specified in the project if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) { return { type: ts.UpToDateStatusType.ContainerOnly }; } - // Collect the expected outputs of this project - var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - if (!force) { - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = ts.getModifiedTime(host, output); - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (ts.isDeclarationFileName(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; + // Fast check to see if reference projects are upto date and error free + var referenceStatuses; + var force = !!state.options.force; if (project.projectReferences) { state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream }); - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); + for (var _i = 0, _c = project.projectReferences; _i < _c.length; _i++) { + var ref = _c[_i]; var resolvedRef = ts.resolveProjectReferencePath(ref); var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef); - var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath); + var resolvedConfig = parseConfigFile(state, resolvedRef, resolvedRefPath); + var refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath); // Its a circular reference ignore the status of this project if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream || refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project @@ -124774,75 +126799,192 @@ var ts; upstreamProjectName: ref.path }; } - // Check oldest output file name only if there is no missing output file name - // (a check we will have skipped if this is a forced build) - if (!force && !missingOutputFileName) { - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + if (!force) + (referenceStatuses || (referenceStatuses = [])).push({ ref: ref, refStatus: refStatus, resolvedRefPath: resolvedRefPath, resolvedConfig: resolvedConfig }); + } + } + if (force) + return { type: ts.UpToDateStatusType.ForceBuild }; + // Check buildinfo first + var host = state.host; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); + var oldestOutputFileName; + var oldestOutputFileTime = maximumDate; + var buildInfoTime; + var buildInfoProgram; + var buildInfoVersionMap; + if (buildInfoPath) { + var buildInfoCacheEntry_1 = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath); + buildInfoTime = (buildInfoCacheEntry_1 === null || buildInfoCacheEntry_1 === void 0 ? void 0 : buildInfoCacheEntry_1.modifiedTime) || ts.getModifiedTime(host, buildInfoPath); + if (buildInfoTime === ts.missingFileModifiedTime) { + if (!buildInfoCacheEntry_1) { + state.buildInfoCache.set(resolvedPath, { + path: toPath(state, buildInfoPath), + buildInfo: false, + modifiedTime: buildInfoTime + }); + } + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: buildInfoPath + }; + } + var buildInfo = ts.Debug.checkDefined(getBuildInfo(state, buildInfoPath, resolvedPath, buildInfoTime)); + if ((buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + return { + type: ts.UpToDateStatusType.TsVersionOutputOfDate, + version: buildInfo.version + }; + } + if (buildInfo.program) { + // If there are pending changes that are not emitted, project is out of date + 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))) { return { - type: ts.UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path + type: ts.UpToDateStatusType.OutOfDateBuildInfo, + buildInfoFile: buildInfoPath }; } + buildInfoProgram = buildInfo.program; } + oldestOutputFileTime = buildInfoTime; + oldestOutputFileName = buildInfoPath; } - if (missingOutputFileName !== undefined) { - return { - type: ts.UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; + // Check input files + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + /** True if input file has changed timestamp but text is not changed, we can then do only timestamp updates on output to make it look up-to-date later */ + var pseudoInputUpToDate = false; + // Get timestamps of input files + for (var _d = 0, _e = project.fileNames; _d < _e.length; _d++) { + var inputFile = _e[_d]; + var inputTime = getModifiedTime(state, inputFile); + if (inputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.Unbuildable, + reason: "".concat(inputFile, " does not exist") + }; + } + // If an buildInfo is older than the newest input, we can stop checking + if (buildInfoTime && buildInfoTime < inputTime) { + var version_3 = void 0; + var currentVersion = void 0; + if (buildInfoProgram) { + // Read files and see if they are same, read is anyways cached + if (!buildInfoVersionMap) + buildInfoVersionMap = ts.getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + version_3 = buildInfoVersionMap.get(toPath(state, inputFile)); + var text = version_3 ? state.readFileWithCache(inputFile) : undefined; + currentVersion = text && (host.createHash || ts.generateDjb2Hash)(text); + if (version_3 && version_3 === currentVersion) + pseudoInputUpToDate = true; + } + if (!version_3 || version_3 !== currentVersion) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: buildInfoPath, + newerInputFileName: inputFile + }; + } + } + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - if (isOutOfDateWithInputs) { - return { - type: ts.UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; + // Now see if all outputs are newer than the newest input + // Dont check output timestamps if we have buildinfo telling us output is uptodate + if (!buildInfoPath) { + // Collect the expected outputs of this project + var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, resolvedPath); + for (var _f = 0, outputs_1 = outputs; _f < outputs_1.length; _f++) { + var output = outputs_1[_f]; + var path = toPath(state, output); + // Output is missing; can stop checking + var outputTime = outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.get(path); + if (!outputTime) { + outputTime = ts.getModifiedTime(state.host, output); + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.set(path, outputTime); + } + if (outputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: output + }; + } + // If an output is older than the newest input, we can stop checking + if (outputTime < newestInputFileTime) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: output, + newerInputFileName: newestInputFileName + }; + } + // No need to get newestDeclarationFileContentChangedTime since thats needed only for composite projects + // And composite projects are the only ones that can be referenced + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + } } - else { - // Check tsconfig time - var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); - if (configStatus) - return configStatus; - // Check extended config time - var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); - if (extendedConfigStatus) - return extendedConfigStatus; - // Check package file time - var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { - var path = _a[0]; - return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); - }); - if (dependentPackageFileStatus) - return dependentPackageFileStatus; - } - if (!force && !state.buildInfoChecked.has(resolvedPath)) { - state.buildInfoChecked.set(resolvedPath, true); - var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); - if (buildInfoPath) { - var value = state.readFileWithCache(buildInfoPath); - var buildInfo = value && ts.getBuildInfo(value); - if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + var seenRefs = buildInfoPath ? new ts.Set() : undefined; + var buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath); + seenRefs === null || seenRefs === void 0 ? void 0 : seenRefs.add(resolvedPath); + /** Inputs are up-to-date, just need either timestamp update or bundle prepend manipulation to make it look up-to-date */ + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (referenceStatuses) { + for (var _g = 0, referenceStatuses_1 = referenceStatuses; _g < referenceStatuses_1.length; _g++) { + var _h = referenceStatuses_1[_g], ref = _h.ref, refStatus = _h.refStatus, resolvedConfig = _h.resolvedConfig, resolvedRefPath = _h.resolvedRefPath; + usesPrepend = usesPrepend || !!(ref.prepend); + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // Check if tsbuildinfo path is shared, then we need to rebuild + if (buildInfoCacheEntry && hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath)) { return { - type: ts.UpToDateStatusType.TsVersionOutputOfDate, - version: buildInfo.version + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: buildInfoPath, + newerProjectName: ref.path }; } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + var newestDeclarationFileContentChangedTime = getLatestChangedDtsTime(state, resolvedConfig.options, resolvedRefPath); + if (newestDeclarationFileContentChangedTime && newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + // Check package file time + var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { + var path = _a[0]; + return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); + }); + if (dependentPackageFileStatus) + return dependentPackageFileStatus; if (usesPrepend && pseudoUpToDate) { return { type: ts.UpToDateStatusType.OutOfDateWithPrepend, @@ -124852,15 +126994,36 @@ var ts; } // Up to date return { - type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + type: pseudoUpToDate ? + ts.UpToDateStatusType.UpToDateWithUpstreamTypes : + pseudoInputUpToDate ? + ts.UpToDateStatusType.UpToDateWithInputFileText : + ts.UpToDateStatusType.UpToDate, newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, oldestOutputFileName: oldestOutputFileName }; } + function hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath) { + if (seenRefs.has(resolvedRefPath)) + return false; + seenRefs.add(resolvedRefPath); + var refBuildInfo = state.buildInfoCache.get(resolvedRefPath); + if (refBuildInfo.path === buildInfoCacheEntry.path) + return true; + if (resolvedConfig.projectReferences) { + // Check references + for (var _i = 0, _a = resolvedConfig.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRef = ts.resolveProjectReferencePath(ref); + var resolvedRefPath_1 = toResolvedConfigFilePath(state, resolvedRef); + var resolvedConfig_1 = parseConfigFile(state, resolvedRef, resolvedRefPath_1); + if (hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig_1, resolvedRefPath_1)) + return true; + } + } + return false; + } function getUpToDateStatus(state, project, resolvedPath) { if (project === undefined) { return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; @@ -124873,39 +127036,71 @@ var ts; state.projectStatus.set(resolvedPath, actual); return actual; } - function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) { if (proj.options.noEmit) - return priorNewestUpdateTime; + return; + var now; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(proj.options); + if (buildInfoPath) { + // For incremental projects, only buildinfo needs to be upto date with timestamp check + // as we dont check output files for up-to-date ness + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(toPath(state, buildInfoPath)))) { + if (!!state.options.verbose) + reportStatus(state, verboseMessage, proj.options.configFilePath); + state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); + getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; + } + state.outputTimeStamps.delete(projectPath); + return; + } var host = state.host; var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, projectPath); + var modifiedOutputs = outputTimeStampMap ? new ts.Set() : undefined; if (!skipOutputs || outputs.length !== skipOutputs.size) { var reportVerbose = !!state.options.verbose; - var now = host.now ? host.now() : new Date(); for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { var file = outputs_2[_i]; - if (skipOutputs && skipOutputs.has(toPath(state, file))) { + var path = toPath(state, file); + if (skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(path)) continue; - } if (reportVerbose) { reportVerbose = false; reportStatus(state, verboseMessage, proj.options.configFilePath); } - if (ts.isDeclarationFileName(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); + host.setModifiedTime(file, now || (now = getCurrentTime(state.host))); + // Store output timestamps in a map because non incremental build will need to check them to determine up-to-dateness + if (outputTimeStampMap) { + outputTimeStampMap.set(path, now); + modifiedOutputs.add(path); } - host.setModifiedTime(file, now); } } - return priorNewestUpdateTime; + // Clear out timestamps not in output list any more + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.forEach(function (_value, key) { + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) + outputTimeStampMap.delete(key); + }); + } + function getLatestChangedDtsTime(state, options, resolvedConfigPath) { + if (!options.composite) + return undefined; + var entry = ts.Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); + if (entry.latestChangedDtsTime !== undefined) + return entry.latestChangedDtsTime || undefined; + var latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? + state.host.getModifiedTime(ts.getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, ts.getDirectoryPath(entry.path))) : + undefined; + entry.latestChangedDtsTime = latestChangedDtsTime || false; + return latestChangedDtsTime; } function updateOutputTimestamps(state, proj, resolvedPath) { if (state.options.dry) { return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath); } - var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); + updateOutputTimestampsWorker(state, proj, resolvedPath, ts.Diagnostics.Updating_output_timestamps_of_project_0); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: priorNewestUpdateTime, oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames()) }); } @@ -124951,6 +127146,7 @@ var ts; break; } // falls through + case ts.UpToDateStatusType.UpToDateWithInputFileText: case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: case ts.UpToDateStatusType.OutOfDateWithPrepend: if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { @@ -125061,9 +127257,9 @@ var ts; function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) { state.reportFileChangeDetected = true; invalidateProject(state, resolvedPath, reloadLevel); - scheduleBuildInvalidatedProject(state); + scheduleBuildInvalidatedProject(state, 250, /*changeDetected*/ true); } - function scheduleBuildInvalidatedProject(state) { + function scheduleBuildInvalidatedProject(state, time, changeDetected) { var hostWithWatch = state.hostWithWatch; if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; @@ -125071,25 +127267,38 @@ var ts; if (state.timerToBuildInvalidatedProject) { hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject); } - state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state); + state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, state, changeDetected); } - function buildNextInvalidatedProject(state) { + function buildNextInvalidatedProject(state, changeDetected) { state.timerToBuildInvalidatedProject = undefined; if (state.reportFileChangeDetected) { state.reportFileChangeDetected = false; state.projectErrorsReported.clear(); reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation); } + var projectsBuilt = 0; var buildOrder = getBuildOrder(state); var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false); if (invalidatedProject) { invalidatedProject.done(); - if (state.projectPendingBuild.size) { - // Schedule next project for build - if (state.watch && !state.timerToBuildInvalidatedProject) { - scheduleBuildInvalidatedProject(state); + projectsBuilt++; + while (state.projectPendingBuild.size) { + // If already scheduled, skip + if (state.timerToBuildInvalidatedProject) + return; + // Before scheduling check if the next project needs build + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, /*reportQueue*/ false); + if (!info) + break; // Nothing to build any more + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps && (changeDetected || projectsBuilt === 5)) { + // Schedule next project for build + scheduleBuildInvalidatedProject(state, 100, /*changeDetected*/ false); + return; } - return; + var project = createInvalidatedProjectWithInfo(state, info, buildOrder); + project.done(); + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps) + projectsBuilt++; } } disableCache(state); @@ -125098,12 +127307,10 @@ var ts; function watchConfigFile(state, resolved, resolvedPath, parsed) { if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; - state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(resolved, function () { - invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); - }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); + state.allWatchedConfigFiles.set(resolvedPath, watchFile(state, resolved, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(state, extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -125135,7 +127342,7 @@ var ts; if (!state.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), { - createNewValue: function (_path, input) { return state.watchFile(input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, + createNewValue: function (_path, input) { return watchFile(state, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -125143,7 +127350,7 @@ var ts; if (!state.watch || !state.lastCachedPackageJsonLookups) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), new ts.Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), { - createNewValue: function (path, _input) { return state.watchFile(path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, + createNewValue: function (path, _input) { return watchFile(state, path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -125193,8 +127400,6 @@ var ts; return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath); }, invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); }, - buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); }, - getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); }, close: function () { return stopWatching(state); }, }; } @@ -125275,19 +127480,18 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { - if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { - return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); - } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); case ts.UpToDateStatusType.OutOfDateWithUpstream: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.OutputMissing: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName)); + case ts.UpToDateStatusType.OutOfDateBuildInfo: + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), relName(state, status.buildInfoFile)); case ts.UpToDateStatusType.UpToDate: if (status.newestInputFileTime !== undefined) { - return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); } // Don't report anything for "up to date because it was already built" -- too verbose break; @@ -125295,6 +127499,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName)); + case ts.UpToDateStatusType.UpToDateWithInputFileText: + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, relName(state, configFileName)); case ts.UpToDateStatusType.UpstreamOutOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName)); case ts.UpToDateStatusType.UpstreamBlocked: @@ -125305,6 +127511,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason); case ts.UpToDateStatusType.TsVersionOutputOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, ts.version); + case ts.UpToDateStatusType.ForceBuild: + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); case ts.UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects // falls through @@ -126440,6 +128648,8 @@ var ts; case 256 /* SyntaxKind.FunctionDeclaration */: case 213 /* SyntaxKind.FunctionExpression */: return getAdjustedLocationForFunction(node); + case 171 /* SyntaxKind.Constructor */: + return node; } } if (ts.isNamedDeclaration(node)) { @@ -126528,7 +128738,7 @@ var ts; // // NOTE: If the node is a modifier, we don't adjust its location if it is the `default` modifier as that is handled // specially by `getSymbolAtLocation`. - if (ts.isModifier(node) && (forRename || node.kind !== 88 /* SyntaxKind.DefaultKeyword */) ? ts.contains(parent.modifiers, node) : + if (ts.isModifier(node) && (forRename || node.kind !== 88 /* SyntaxKind.DefaultKeyword */) ? ts.canHaveModifiers(parent) && ts.contains(parent.modifiers, node) : node.kind === 84 /* SyntaxKind.ClassKeyword */ ? ts.isClassDeclaration(parent) || ts.isClassExpression(node) : node.kind === 98 /* SyntaxKind.FunctionKeyword */ ? ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(node) : node.kind === 118 /* SyntaxKind.InterfaceKeyword */ ? ts.isInterfaceDeclaration(parent) : @@ -126767,12 +128977,18 @@ var ts; // flag causes us to return the first node whose end position matches the position and which produces and acceptable token // kind. Meanwhile, if includePrecedingTokenAtEndPosition is unset, we look for the first node whose start is <= the // position and whose end is greater than the position. + // There are more sophisticated end tests later, but this one is very fast + // and allows us to skip a bunch of work + var end = children[middle].getEnd(); + if (end < position) { + return -1 /* Comparison.LessThan */; + } var start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { return 1 /* Comparison.GreaterThan */; } // first element whose start position is before the input and whose end position is after or equal to the input - if (nodeContainsPosition(children[middle])) { + if (nodeContainsPosition(children[middle], start, end)) { if (children[middle - 1]) { // we want the _first_ element that contains the position, so left-recur if the prior node also contains the position if (nodeContainsPosition(children[middle - 1])) { @@ -126804,13 +129020,16 @@ var ts; case "continue-outer": continue outer; } } - function nodeContainsPosition(node) { - var start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true); + function nodeContainsPosition(node, start, end) { + end !== null && end !== void 0 ? end : (end = node.getEnd()); + if (end < position) { + return false; + } + start !== null && start !== void 0 ? start : (start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true)); if (start > position) { // If this child begins after position, then all subsequent children will as well. return false; } - var end = node.getEnd(); if (position < end || (position === end && (node.kind === 1 /* SyntaxKind.EndOfFileToken */ || includeEndPosition))) { return true; } @@ -127508,7 +129727,6 @@ var ts; ts.makeImportIfNecessary = makeImportIfNecessary; function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) { return ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? ts.factory.createNamedImports(namedImports) : undefined) : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier, @@ -127598,7 +129816,7 @@ var ts; node.getEnd() <= ts.textSpanEnd(span); } function findModifier(node, kind) { - return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + return ts.canHaveModifiers(node) ? ts.find(node.modifiers, function (m) { return m.kind === kind; }) : undefined; } ts.findModifier = findModifier; function insertImports(changes, sourceFile, imports, blankLineBetween) { @@ -127677,6 +129895,41 @@ var ts; return true; } ts.isTextWhiteSpaceLike = isTextWhiteSpaceLike; + function getMappedLocation(location, sourceMapper, fileExists) { + var mapsTo = sourceMapper.tryGetSourcePosition(location); + return mapsTo && (!fileExists || fileExists(ts.normalizePath(mapsTo.fileName)) ? mapsTo : undefined); + } + ts.getMappedLocation = getMappedLocation; + function getMappedDocumentSpan(documentSpan, sourceMapper, fileExists) { + var fileName = documentSpan.fileName, textSpan = documentSpan.textSpan; + var newPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start }, sourceMapper, fileExists); + if (!newPosition) + return undefined; + var newEndPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start + textSpan.length }, sourceMapper, fileExists); + var newLength = newEndPosition + ? newEndPosition.pos - newPosition.pos + : textSpan.length; // This shouldn't happen + return { + fileName: newPosition.fileName, + textSpan: { + start: newPosition.pos, + length: newLength, + }, + originalFileName: documentSpan.fileName, + originalTextSpan: documentSpan.textSpan, + contextSpan: getMappedContextSpan(documentSpan, sourceMapper, fileExists), + originalContextSpan: documentSpan.contextSpan + }; + } + ts.getMappedDocumentSpan = getMappedDocumentSpan; + function getMappedContextSpan(documentSpan, sourceMapper, fileExists) { + var contextSpanStart = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, sourceMapper, fileExists); + var contextSpanEnd = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length }, sourceMapper, fileExists); + return contextSpanStart && contextSpanEnd ? + { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : + undefined; + } + ts.getMappedContextSpan = getMappedContextSpan; // #endregion // Display-part writer helpers // #region @@ -128170,7 +130423,7 @@ var ts; for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { var change = textChanges_1[_b]; var span = change.span, newText = change.newText; - var index = indexInTextChange(newText, name); + var index = indexInTextChange(newText, ts.escapeString(name)); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. @@ -129138,32 +131391,41 @@ var ts; || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } - function forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, cb) { + function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { var _a, _b; - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var excludePatterns = preferences.autoImportFileExcludePatterns && ts.mapDefined(preferences.autoImportFileExcludePatterns, function (spec) { + // The client is expected to send rooted path specs since we don't know + // what directory a relative path is relative to. + var pattern = ts.getPatternFromSpec(spec, "", "exclude"); + return pattern ? ts.getRegexFromPattern(pattern, useCaseSensitiveFileNames) : undefined; + }); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); var autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)); if (autoImportProvider) { var start = ts.timestamp(); - forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); + forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: ".concat(ts.timestamp() - start)); } } ts.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModule(checker, allSourceFiles, cb) { - for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { - var ambient = _a[_i]; - if (!ts.stringContains(ambient.name, "*")) { + function forEachExternalModule(checker, allSourceFiles, excludePatterns, cb) { + var _a; + var isExcluded = function (fileName) { return excludePatterns === null || excludePatterns === void 0 ? void 0 : excludePatterns.some(function (p) { return p.test(fileName); }); }; + for (var _i = 0, _b = checker.getAmbientModules(); _i < _b.length; _i++) { + var ambient = _b[_i]; + if (!ts.stringContains(ambient.name, "*") && !(excludePatterns && ((_a = ambient.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return isExcluded(d.getSourceFile().fileName); })))) { cb(ambient, /*sourceFile*/ undefined); } } - for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { - var sourceFile = allSourceFiles_1[_b]; - if (ts.isExternalOrCommonJsModule(sourceFile)) { + for (var _c = 0, allSourceFiles_1 = allSourceFiles; _c < allSourceFiles_1.length; _c++) { + var sourceFile = allSourceFiles_1[_c]; + if (ts.isExternalOrCommonJsModule(sourceFile) && !isExcluded(sourceFile.fileName)) { cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } } } - function getExportInfoMap(importingFile, host, program, cancellationToken) { + function getExportInfoMap(importingFile, host, program, preferences, cancellationToken) { var _a, _b, _c, _d, _e; var start = ts.timestamp(); // Pulling the AutoImportProvider project will trigger its updateGraph if pending, @@ -129183,7 +131445,7 @@ var ts; var compilerOptions = program.getCompilerOptions(); var moduleCount = 0; try { - forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { + forEachExternalModuleToImportFrom(program, host, preferences, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { if (++moduleCount % 100 === 0) cancellationToken === null || cancellationToken === void 0 ? void 0 : cancellationToken.throwIfCancellationRequested(); var seenExports = new ts.Map(); @@ -130524,6 +132786,26 @@ var ts; (function (Completions) { var StringCompletions; (function (StringCompletions) { + var _a; + var kindPrecedence = (_a = {}, + _a["directory" /* ScriptElementKind.directory */] = 0, + _a["script" /* ScriptElementKind.scriptElement */] = 1, + _a["external module name" /* ScriptElementKind.externalModuleName */] = 2, + _a); + function createNameAndKindSet() { + var map = new ts.Map(); + function add(value) { + var existing = map.get(value.name); + if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value.kind]) { + map.set(value.name, value); + } + } + return { + add: add, + has: map.has.bind(map), + values: map.values.bind(map), + }; + } function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); @@ -130627,11 +132909,11 @@ var ts; var parent = walkUpParentheses(node.parent); switch (parent.kind) { case 196 /* SyntaxKind.LiteralType */: { - var grandParent = walkUpParentheses(parent.parent); - switch (grandParent.kind) { + var grandParent_1 = walkUpParentheses(parent.parent); + switch (grandParent_1.kind) { + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: case 178 /* SyntaxKind.TypeReference */: { - var typeReference_1 = grandParent; - var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === typeReference_1; }); + var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === grandParent_1; }); if (typeArgument) { return { kind: 2 /* StringLiteralCompletionKind.Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), isNewIdentifier: false }; } @@ -130644,7 +132926,7 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - var _a = grandParent, indexType = _a.indexType, objectType = _a.objectType; + var _a = grandParent_1, indexType = _a.indexType, objectType = _a.objectType; if (!ts.rangeContainsPosition(indexType, position)) { return undefined; } @@ -130652,11 +132934,11 @@ var ts; case 200 /* SyntaxKind.ImportType */: return { kind: 0 /* StringLiteralCompletionKind.Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; case 187 /* SyntaxKind.UnionType */: { - if (!ts.isTypeReferenceNode(grandParent.parent)) { + if (!ts.isTypeReferenceNode(grandParent_1.parent)) { return undefined; } - var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent); - var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(grandParent_1, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent_1)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); return { kind: 2 /* StringLiteralCompletionKind.Types */, types: types, isNewIdentifier: false }; } default: @@ -130805,11 +133087,12 @@ var ts; } function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { var literalValue = ts.normalizeSlashes(node.text); + var mode = ts.isStringLiteralLike(node) ? ts.getModeForUsageLocation(sourceFile, node) : undefined; var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, getIncludeExtensionOption()) - : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, compilerOptions, host, getIncludeExtensionOption(), typeChecker); function getIncludeExtensionOption() { var mode = ts.isStringLiteralLike(node) ? ts.getModeForUsageLocation(sourceFile, node) : undefined; return preferences.importModuleSpecifierEnding === "js" || mode === ts.ModuleKind.ESNext ? 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */ : 0 /* IncludeExtensionsOption.Exclude */; @@ -130825,7 +133108,7 @@ var ts; return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + return ts.arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath).values()); } } function isEmitResolutionKindUsingNodeModules(compilerOptions) { @@ -130861,7 +133144,7 @@ var ts; var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); - return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); + return ts.flatMap(baseDirectories, function (baseDirectory) { return ts.arrayFrom(getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude).values()); }); } var IncludeExtensionsOption; (function (IncludeExtensionsOption) { @@ -130872,9 +133155,9 @@ var ts; /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { - var extensions = _a.extensions, includeExtensionsOption = _a.includeExtensionsOption; - if (result === void 0) { result = []; } + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensionOptions, host, exclude, result) { + var _a; + if (result === void 0) { result = createNameAndKindSet(); } if (fragment === undefined) { fragment = ""; } @@ -130890,92 +133173,124 @@ var ts; fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths var absolutePath = ts.resolvePath(scriptPath, fragment); var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); + // check for a version redirect + var packageJsonPath = ts.findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionPaths = (_a = ts.getPackageJsonTypesVersionsPaths(typesVersions)) === null || _a === void 0 ? void 0 : _a.paths; + if (versionPaths) { + var packageDirectory = ts.getDirectoryPath(packageJsonPath); + var pathInPackage = absolutePath.slice(ts.ensureTrailingDirectorySeparator(packageDirectory).length); + if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, host, versionPaths)) { + // A true result means one of the `versionPaths` was matched, which will block relative resolution + // to files and folders from here. All reachable paths given the pattern match are already added. + return result; + } + } + } + } var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (!ts.tryDirectoryExists(host, baseDirectory)) return result; // Enumerate the available files if possible - var files = ts.tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + var files = ts.tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensionsOption === includeExtensionsOption.Exclude) so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - var foundFiles = new ts.Map(); // maps file to its extension for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { var filePath = files_1[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* Comparison.EqualTo */) { continue; } - var foundFileName = void 0; - var outputExtension = ts.moduleSpecifiers.tryGetJSExtensionForFile(filePath, host.getCompilationSettings()); - if (includeExtensionsOption === 0 /* IncludeExtensionsOption.Exclude */ && !ts.fileExtensionIsOneOf(filePath, [".json" /* Extension.Json */, ".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */])) { - foundFileName = ts.removeFileExtension(ts.getBaseFileName(filePath)); - foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); - } - else if ((ts.fileExtensionIsOneOf(filePath, [".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */]) || includeExtensionsOption === 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */) && outputExtension) { - foundFileName = ts.changeExtension(ts.getBaseFileName(filePath), outputExtension); - foundFiles.set(foundFileName, outputExtension); - } - else { - foundFileName = ts.getBaseFileName(filePath); - foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); - } + var _b = getFilenameWithExtensionOption(ts.getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions.includeExtensionsOption), name = _b.name, extension = _b.extension; + result.add(nameAndKind(name, "script" /* ScriptElementKind.scriptElement */, extension)); } - foundFiles.forEach(function (ext, foundFile) { - result.push(nameAndKind(foundFile, "script" /* ScriptElementKind.scriptElement */, ext)); - }); } // If possible, get folder completion as well var directories = ts.tryGetDirectories(host, baseDirectory); if (directories) { - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var directory = directories_1[_b]; + for (var _c = 0, directories_1 = directories; _c < directories_1.length; _c++) { + var directory = directories_1[_c]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); if (directoryName !== "@types") { - result.push(directoryResult(directoryName)); - } - } - } - // check for a version redirect - var packageJsonPath = ts.findPackageJson(baseDirectory, host); - if (packageJsonPath) { - var packageJson = ts.readJson(packageJsonPath, host); - var typesVersions = packageJson.typesVersions; - if (typeof typesVersions === "object") { - var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); - var versionPaths = versionResult && versionResult.paths; - var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); - if (versionPaths) { - addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + result.add(directoryResult(directoryName)); } } } return result; } - function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { - for (var path in paths) { - if (!ts.hasProperty(paths, path)) + function getFilenameWithExtensionOption(name, compilerOptions, includeExtensionsOption) { + var outputExtension = ts.moduleSpecifiers.tryGetJSExtensionForFile(name, compilerOptions); + if (includeExtensionsOption === 0 /* IncludeExtensionsOption.Exclude */ && !ts.fileExtensionIsOneOf(name, [".json" /* Extension.Json */, ".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */])) { + return { name: ts.removeFileExtension(name), extension: ts.tryGetExtensionFromPath(name) }; + } + else if ((ts.fileExtensionIsOneOf(name, [".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */]) || includeExtensionsOption === 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */) && outputExtension) { + return { name: ts.changeExtension(name, outputExtension), extension: outputExtension }; + } + else { + return { name: name, extension: ts.tryGetExtensionFromPath(name) }; + } + } + /** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */ + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, host, paths) { + var getPatternsForKey = function (key) { return paths[key]; }; + var comparePaths = function (a, b) { + var patternA = ts.tryParsePattern(a); + var patternB = ts.tryParsePattern(b); + var lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length; + var lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length; + return ts.compareValues(lengthB, lengthA); + }; + return addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, ts.getOwnKeys(paths), getPatternsForKey, comparePaths); + } + /** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */ + function addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, keys, getPatternsForKey, comparePaths) { + var pathResults = []; + var matchedPath; + for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { + var key = keys_1[_i]; + if (key === ".") continue; - var patterns = paths[path]; + var keyWithoutLeadingDotSlash = key.replace(/^\.\//, ""); // remove leading "./" + var patterns = getPatternsForKey(key); if (patterns) { - var _loop_3 = function (name, kind, extension) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind, extension)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_3(name, kind, extension); + var pathPattern = ts.tryParsePattern(keyWithoutLeadingDotSlash); + if (!pathPattern) + continue; + var isMatch = typeof pathPattern === "object" && ts.isPatternMatch(pathPattern, fragment); + var isLongestMatch = isMatch && (matchedPath === undefined || comparePaths(key, matchedPath) === -1 /* Comparison.LessThan */); + if (isLongestMatch) { + // If this is a higher priority match than anything we've seen so far, previous results from matches are invalid, e.g. + // for `import {} from "some-package/|"` with a typesVersions: + // { + // "bar/*": ["bar/*"], // <-- 1. We add 'bar', but 'bar/*' doesn't match yet. + // "*": ["dist/*"], // <-- 2. We match here and add files from dist. 'bar' is still ok because it didn't come from a match. + // "foo/*": ["foo/*"] // <-- 3. We matched '*' earlier and added results from dist, but if 'foo/*' also matched, + // } results in dist would not be visible. 'bar' still stands because it didn't come from a match. + // This is especially important if `dist/foo` is a folder, because if we fail to clear results + // added by the '*' match, after typing `"some-package/foo/|"` we would get file results from both + // ./dist/foo and ./foo, when only the latter will actually be resolvable. + // See pathCompletionsTypesVersionsWildcard6.ts. + matchedPath = key; + pathResults = pathResults.filter(function (r) { return !r.matchedPattern; }); + } + if (typeof pathPattern === "string" || matchedPath === undefined || comparePaths(key, matchedPath) !== 1 /* Comparison.GreaterThan */) { + pathResults.push({ + matchedPattern: isMatch, + results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host) + .map(function (_a) { + var name = _a.name, kind = _a.kind, extension = _a.extension; + return nameAndKind(name, kind, extension); + }), + }); } } } + pathResults.forEach(function (pathResult) { return pathResult.results.forEach(function (r) { return result.add(r); }); }); + return matchedPath !== undefined; } /** * Check all of the declared modules and those in node modules. Possible sources of modules: @@ -130984,22 +133299,22 @@ var ts; * Modules from node_modules (i.e. those listed in package.json) * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions */ - function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, compilerOptions, host, includeExtensionsOption, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; - var result = []; - var extensionOptions = getExtensionOptions(compilerOptions); + var result = createNameAndKindSet(); + var extensionOptions = getExtensionOptions(compilerOptions, includeExtensionsOption); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); if (paths) { - addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, host, paths); } } var fragmentDirectory = getFragmentDirectory(fragment); for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { var ambientName = _a[_i]; - result.push(nameAndKind(ambientName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); + result.add(nameAndKind(ambientName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (isEmitResolutionKindUsingNodeModules(compilerOptions)) { @@ -131007,15 +133322,13 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_4 = function (moduleName) { - if (!result.some(function (entry) { return entry.name === moduleName; })) { - foundGlobal = true; - result.push(nameAndKind(moduleName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); - } - }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_4(moduleName); + var moduleResult = nameAndKind(moduleName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined); + if (!result.has(moduleResult.name)) { + foundGlobal = true; + result.add(moduleResult); + } } } if (!foundGlobal) { @@ -131041,39 +133354,19 @@ var ts; } packagePath = ts.combinePaths(packagePath, subName); } - var packageFile = ts.combinePaths(ancestor, "node_modules", packagePath, "package.json"); + var packageDirectory = ts.combinePaths(ancestor, "node_modules", packagePath); + var packageFile = ts.combinePaths(packageDirectory, "package.json"); if (ts.tryFileExists(host, packageFile)) { var packageJson = ts.readJson(packageFile, host); - var exports = packageJson.exports; - if (exports) { - if (typeof exports !== "object" || exports === null) { // eslint-disable-line no-null/no-null + var exports_1 = packageJson.exports; + if (exports_1) { + if (typeof exports_1 !== "object" || exports_1 === null) { // eslint-disable-line no-null/no-null return; // null exports or entrypoint only, no sub-modules available } - var keys = ts.getOwnKeys(exports); - var fragmentSubpath_1 = components.join("/"); - var processedKeys = ts.mapDefined(keys, function (k) { - if (k === ".") - return undefined; - if (!ts.startsWith(k, "./")) - return undefined; - var subpath = k.substring(2); - if (!ts.startsWith(subpath, fragmentSubpath_1)) - return undefined; - // subpath is a valid export (barring conditions, which we don't currently check here) - if (!ts.stringContains(subpath, "*")) { - return subpath; - } - // pattern export - only return everything up to the `*`, so the user can autocomplete, then - // keep filling in the pattern (we could speculatively return a list of options by hitting disk, - // but conditions will make that somewhat awkward, as each condition may have a different set of possible - // options for the `*`. - return subpath.slice(0, subpath.indexOf("*")); - }); - ts.forEach(processedKeys, function (k) { - if (k) { - result.push(nameAndKind(k, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); - } - }); + var keys = ts.getOwnKeys(exports_1); + var fragmentSubpath = components.join("/") + (components.length && ts.hasTrailingDirectorySeparator(fragment) ? "/" : ""); + var conditions_1 = mode === ts.ModuleKind.ESNext ? ["node", "import", "types"] : ["node", "require", "types"]; + addCompletionEntriesFromPathsOrExports(result, fragmentSubpath, packageDirectory, extensionOptions, host, keys, function (key) { return ts.singleElementArray(getPatternFromFirstMatchingCondition(exports_1[key], conditions_1)); }, ts.comparePatternKeys); return; } } @@ -131083,26 +133376,44 @@ var ts; ts.forEachAncestorDirectory(scriptPath, ancestorLookup); } } - return result; + return ts.arrayFrom(result.values()); + } + function getPatternFromFirstMatchingCondition(target, conditions) { + if (typeof target === "string") { + return target; + } + if (target && typeof target === "object" && !ts.isArray(target)) { + for (var condition in target) { + if (condition === "default" || conditions.indexOf(condition) > -1 || ts.isApplicableVersionedTypesKey(conditions, condition)) { + var pattern = target[condition]; + return getPatternFromFirstMatchingCondition(pattern, conditions); + } + } + } } function getFragmentDirectory(fragment) { return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; } - function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; + return !ts.stringContains(path, "*") ? justPathMappingName(path, "script" /* ScriptElementKind.scriptElement */) : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); - return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { - return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); - }); - function justPathMappingName(name) { - return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; + if (remainingFragment === undefined) { + var starIsFullPathComponent = path[path.length - 2] === "/"; + return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* ScriptElementKind.directory */) : ts.flatMap(patterns, function (pattern) { var _a; return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)) === null || _a === void 0 ? void 0 : _a.map(function (_a) { + var name = _a.name, rest = __rest(_a, ["name"]); + return (__assign({ name: pathPrefix + name }, rest)); + }); }); + } + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host); }); + function justPathMappingName(name, kind) { + return ts.startsWith(name, fragment) ? [{ name: ts.removeTrailingDirectorySeparator(name), kind: kind, extension: undefined }] : ts.emptyArray; } } - function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, host) { if (!host.readDirectory) { return undefined; } @@ -131121,21 +133432,33 @@ var ts; var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". - var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var baseDirectory = ts.normalizePath(ts.combinePaths(packageDirectory, expandedPrefixDirectory)); var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { - var extension = ts.tryGetExtensionFromPath(match); - var name = trimPrefixAndSuffix(match); - return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* ScriptElementKind.scriptElement */, extension); - }); - var directories = ts.mapDefined(ts.tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { - var name = trimPrefixAndSuffix(dir); - return name === undefined ? undefined : directoryResult(name); + // If we have a suffix, then we read the directory all the way down to avoid returning completions for + // directories that don't contain files that would match the suffix. A previous comment here was concerned + // about the case where `normalizedSuffix` includes a `?` character, which should be interpreted literally, + // but will match any single character as part of the `include` pattern in `tryReadDirectory`. This is not + // a problem, because (in the extremely unusual circumstance where the suffix has a `?` in it) a `?` + // interpreted as "any character" can only return *too many* results as compared to the literal + // interpretation, so we can filter those superfluous results out via `trimPrefixAndSuffix` as we've always + // done. + var includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*"; + var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var trimmedWithPattern = trimPrefixAndSuffix(match); + if (trimmedWithPattern) { + if (containsSlash(trimmedWithPattern)) { + return directoryResult(ts.getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); + } + var _a = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions.includeExtensionsOption), name = _a.name, extension = _a.extension; + return nameAndKind(name, "script" /* ScriptElementKind.scriptElement */, extension); + } }); + // If we had a suffix, we already recursively searched for all possible files that could match + // it and returned the directories leading to those files. Otherwise, assume any directory could + // have something valid to import. + var directories = normalizedSuffix + ? ts.emptyArray + : ts.mapDefined(ts.tryGetDirectories(host, baseDirectory), function (dir) { return dir === "node_modules" ? undefined : directoryResult(dir); }); return __spreadArray(__spreadArray([], matches, true), directories, true); function trimPrefixAndSuffix(path) { var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); @@ -131178,10 +133501,10 @@ var ts; var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, 1 /* IncludeExtensionsOption.Include */), host, sourceFile.path) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) : ts.Debug.fail(); - return addReplacementSpans(toComplete, range.pos + prefix.length, names); + return addReplacementSpans(toComplete, range.pos + prefix.length, ts.arrayFrom(names.values())); } function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { - if (result === void 0) { result = []; } + if (result === void 0) { result = createNameAndKindSet(); } // Check for typings specified in compiler options var seen = new ts.Map(); var typeRoots = ts.tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; @@ -131206,7 +133529,7 @@ var ts; continue; if (fragmentDirectory === undefined) { if (!seen.has(packageName)) { - result.push(nameAndKind(packageName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); + result.add(nameAndKind(packageName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); seen.set(packageName, true); } } @@ -131402,10 +133725,9 @@ var ts; GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; })(GlobalsSearch || (GlobalsSearch = {})); - function resolvingModuleSpecifiers(logPrefix, host, program, sourceFile, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { + function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { var _a, _b, _c; var start = ts.timestamp(); - var packageJsonImportFilter = ts.createPackageJsonImportFilter(sourceFile, preferences, host); // Under `--moduleResolution nodenext`, we have to resolve module specifiers up front, because // package.json exports can mean we *can't* resolve a module specifier (that doesn't include a // relative path into node_modules), and we want to filter those completions out entirely. @@ -131430,7 +133752,7 @@ var ts; return result; function tryResolve(exportInfo, symbolName, isFromAmbientModule) { if (isFromAmbientModule) { - var result_1 = ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, sourceFile, program, host, preferences); + var result_1 = resolver.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite); if (result_1) { ambientCount++; } @@ -131439,7 +133761,7 @@ var ts; var shouldResolveModuleSpecifier = needsFullResolution || preferences.allowIncompleteCompletions && resolvedCount < Completions.moduleSpecifierResolutionLimit; var shouldGetModuleSpecifierFromCache = !shouldResolveModuleSpecifier && preferences.allowIncompleteCompletions && cacheAttemptCount < Completions.moduleSpecifierResolutionCacheAttemptLimit; var result = (shouldResolveModuleSpecifier || shouldGetModuleSpecifierFromCache) - ? ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, sourceFile, program, host, preferences, packageJsonImportFilter, shouldGetModuleSpecifierFromCache) + ? resolver.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, shouldGetModuleSpecifierFromCache) : undefined; if (!shouldResolveModuleSpecifier && !shouldGetModuleSpecifierFromCache || shouldGetModuleSpecifierFromCache && !result) { skippedAny = true; @@ -131543,8 +133865,8 @@ var ts; if (!previousResponse) return undefined; var lowerCaseTokenText = location.text.toLowerCase(); - var exportMap = ts.getExportInfoMap(file, host, program, cancellationToken); - var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, program, file, location.getStart(), preferences, + var exportMap = ts.getExportInfoMap(file, host, program, preferences, cancellationToken); + var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, ts.codefix.createImportSpecifierResolver(file, program, host, preferences), program, location.getStart(), preferences, /*isForImportStatementCompletion*/ false, ts.isValidTypeOnlyAliasUseSite(location), function (context) { var entries = ts.mapDefined(previousResponse.entries, function (entry) { var _a; @@ -131628,37 +133950,36 @@ var ts; } } var entries = ts.createSortedArray(); - if (isUncheckedFile(sourceFile, compilerOptions)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); - getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); - } - else { - if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* KeywordCompletionFilters.None */) { - return undefined; - } - getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); + var isChecked = isCheckedFile(sourceFile, compilerOptions); + if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* KeywordCompletionFilters.None */) { + return undefined; } + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); if (keywordFilters !== 0 /* KeywordCompletionFilters.None */) { - var entryNames_1 = new ts.Set(entries.map(function (e) { return e.name; })); for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; - if (isTypeOnlyLocation && ts.isTypeKeyword(ts.stringToToken(keywordEntry.name)) || !entryNames_1.has(keywordEntry.name)) { + if (isTypeOnlyLocation && ts.isTypeKeyword(ts.stringToToken(keywordEntry.name)) || !uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } } - var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); for (var _b = 0, _c = getContextualKeywords(contextToken, position); _b < _c.length; _b++) { var keywordEntry = _c[_b]; - if (!entryNames.has(keywordEntry.name)) { + if (!uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } for (var _d = 0, literals_1 = literals; _d < literals_1.length; _d++) { var literal = literals_1[_d]; - ts.insertSorted(entries, createCompletionEntryForLiteral(sourceFile, preferences, literal), compareCompletionEntries, /*allowDuplicates*/ true); + var literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal); + uniqueNames.add(literalEntry.name); + ts.insertSorted(entries, literalEntry, compareCompletionEntries, /*allowDuplicates*/ true); + } + if (!isChecked) { + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); } return { flags: completionData.flags, @@ -131670,8 +133991,8 @@ var ts; entries: entries, }; } - function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + function isCheckedFile(sourceFile, compilerOptions) { + return !ts.isSourceFileJS(sourceFile) || !!ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -132040,7 +134361,7 @@ var ts; span = ts.createTextSpanFromNode(contextToken); } if (ts.isPropertyDeclaration(contextToken.parent)) { - modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers); + modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers) & 125951 /* ModifierFlags.Modifier */; span = ts.createTextSpanFromNode(contextToken.parent); } return { modifiers: modifiers, span: span }; @@ -132100,7 +134421,7 @@ var ts; var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var quotePreference = ts.getQuotePreference(sourceFile, preferences); - var builderFlags = quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : undefined; + var builderFlags = 33554432 /* NodeBuilderFlags.OmitThisParameter */ | (quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : 0 /* NodeBuilderFlags.None */); switch (declaration.kind) { case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: @@ -132139,12 +134460,10 @@ var ts; } var parameters = typeNode.parameters.map(function (typedParam) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typedParam.dotDotDotToken, typedParam.name, typedParam.questionToken, /*type*/ undefined, typedParam.initializer); }); return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, @@ -132631,7 +134950,7 @@ var ts; } function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) { var typeChecker = program.getTypeChecker(); - var inUncheckedFile = isUncheckedFile(sourceFile, compilerOptions); + var inCheckedFile = isCheckedFile(sourceFile, compilerOptions); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -132875,6 +135194,7 @@ var ts; var hasUnresolvedAutoImports = false; // This also gets mutated in nested-functions after the return var symbols = []; + var importSpecifierResolver; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; var seenPropertySymbols = new ts.Map(); @@ -133046,15 +135366,7 @@ var ts; isNewIdentifierLocation = true; } var propertyAccess = node.kind === 200 /* SyntaxKind.ImportType */ ? node : node.parent; - if (inUncheckedFile) { - // In javascript files, for union types, we don't just get the members that - // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part - // of the individual types to a higher status since we know what they are. - symbols.push.apply(symbols, ts.filter(getPropertiesForCompletion(type, typeChecker), function (s) { return typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s); })); - } - else { + if (inCheckedFile) { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) { @@ -133062,6 +135374,14 @@ var ts; } } } + else { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + symbols.push.apply(symbols, ts.filter(getPropertiesForCompletion(type, typeChecker), function (s) { return typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s); })); + } if (insertAwait && preferences.includeCompletionsWithInsertText) { var promiseType = typeChecker.getPromisedTypeOfPromise(type); if (promiseType) { @@ -133096,14 +135416,14 @@ var ts; } else { var fileName = ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? (_a = ts.getSourceFileOfModule(moduleSymbol)) === null || _a === void 0 ? void 0 : _a.fileName : undefined; - var moduleSpecifier = (ts.codefix.getModuleSpecifierForBestExportInfo([{ + var moduleSpecifier = ((importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo([{ exportKind: 0 /* ExportKind.Named */, moduleFileName: fileName, isFromPackageJson: false, moduleSymbol: moduleSymbol, symbol: firstAccessibleSymbol, targetFlags: ts.skipAlias(firstAccessibleSymbol, typeChecker).flags, - }], firstAccessibleSymbol.name, position, ts.isValidTypeOnlyAliasUseSite(location), sourceFile, program, host, preferences) || {}).moduleSpecifier; + }], firstAccessibleSymbol.name, position, ts.isValidTypeOnlyAliasUseSite(location)) || {}).moduleSpecifier; if (moduleSpecifier) { var origin = { kind: getNullableSymbolOriginInfoKind(6 /* SymbolOriginInfoKind.SymbolMemberExport */), @@ -133253,7 +135573,7 @@ var ts; } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 305 /* SyntaxKind.SourceFile */) { - var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); + var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false, ts.isClassLike(scopeNode.parent) ? scopeNode : undefined); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { var symbol = _a[_i]; @@ -133356,10 +135676,10 @@ var ts; previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); - var exportInfo = ts.getExportInfoMap(sourceFile, host, program, cancellationToken); + var exportInfo = ts.getExportInfoMap(sourceFile, host, program, preferences, cancellationToken); var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); - resolvingModuleSpecifiers("collectAutoImports", host, program, sourceFile, position, preferences, !!importCompletionNode, ts.isValidTypeOnlyAliasUseSite(location), function (context) { + resolvingModuleSpecifiers("collectAutoImports", host, importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences)), program, position, preferences, !!importCompletionNode, ts.isValidTypeOnlyAliasUseSite(location), function (context) { exportInfo.search(sourceFile.path, /*preferCapitalized*/ isRightOfOpenTag, function (symbolName, targetFlags) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) @@ -134456,6 +136776,7 @@ var ts; return kind === 131 /* SyntaxKind.AsyncKeyword */ || kind === 132 /* SyntaxKind.AwaitKeyword */ || kind === 127 /* SyntaxKind.AsKeyword */ + || kind === 152 /* SyntaxKind.TypeKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { @@ -134555,6 +136876,10 @@ var ts; } break; case 79 /* SyntaxKind.Identifier */: { + var originalKeywordKind = location.originalKeywordKind; + if (originalKeywordKind && ts.isKeyword(originalKeywordKind)) { + return undefined; + } // class c { public prop = c| } if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) { return undefined; @@ -135342,60 +137667,64 @@ var ts; } return settingsOrHost; } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings)); - return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions); } - function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind, languageVersionOrOptions); } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings)); - return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions); } - function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { + return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind, languageVersionOrOptions); } function getDocumentRegistryEntry(bucketEntry, scriptKind) { var entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(ts.Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:".concat(scriptKind, " and sourceFile.scriptKind: ").concat(entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind, ", !entry: ").concat(!entry)); return entry; } - function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version, acquiring, scriptKind) { + function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version, acquiring, scriptKind, languageVersionOrOptions) { var _a, _b, _c, _d; scriptKind = ts.ensureScriptKind(fileName, scriptKind); var compilationSettings = getCompilationSettings(compilationSettingsOrHost); var host = compilationSettingsOrHost === compilationSettings ? undefined : compilationSettingsOrHost; var scriptTarget = scriptKind === 6 /* ScriptKind.JSON */ ? 100 /* ScriptTarget.JSON */ : ts.getEmitScriptTarget(compilationSettings); - var sourceFileOptions = { - languageVersion: scriptTarget, - impliedNodeFormat: host && ts.getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getModuleResolutionCache) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(compilationSettings) - }; + var sourceFileOptions = typeof languageVersionOrOptions === "object" ? + languageVersionOrOptions : + { + languageVersion: scriptTarget, + impliedNodeFormat: host && ts.getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getModuleResolutionCache) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), + setExternalModuleIndicator: ts.getSetExternalModuleIndicator(compilationSettings) + }; + sourceFileOptions.languageVersion = scriptTarget; var oldBucketCount = buckets.size; - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var keyWithMode = getDocumentRegistryBucketKeyWithMode(key, sourceFileOptions.impliedNodeFormat); + var bucket = ts.getOrUpdate(buckets, keyWithMode, function () { return new ts.Map(); }); if (ts.tracing) { if (buckets.size > oldBucketCount) { // It is interesting, but not definitively problematic if a build requires multiple document registry buckets - // perhaps they are for two projects that don't have any overlap. // Bonus: these events can help us interpret the more interesting event below. - ts.tracing.instant("session" /* tracing.Phase.Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: key }); + ts.tracing.instant("session" /* tracing.Phase.Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: keyWithMode }); } // It is fairly suspicious to have one path in two buckets - you'd expect dependencies to have similar configurations. // If this occurs unexpectedly, the fix is likely to synchronize the project settings. // Skip .d.ts files to reduce noise (should also cover most of node_modules). var otherBucketKey = !ts.isDeclarationFileName(path) && - ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== key && bucket.has(path) && bucketKey; }); + ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== keyWithMode && bucket.has(path) && bucketKey; }); if (otherBucketKey) { - ts.tracing.instant("session" /* tracing.Phase.Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: key }); + ts.tracing.instant("session" /* tracing.Phase.Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: keyWithMode }); } } var bucketEntry = bucket.get(path); var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { - var sourceFile = externalCache.getDocument(key, path); + var sourceFile = externalCache.getDocument(keyWithMode, path); if (sourceFile) { ts.Debug.assert(acquiring); entry = { @@ -135409,7 +137738,7 @@ var ts; // Have never seen this file with these settings. Create a new source file for it. var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, sourceFileOptions, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { - externalCache.setDocument(key, path, sourceFile); + externalCache.setDocument(keyWithMode, path, sourceFile); } entry = { sourceFile: sourceFile, @@ -135424,7 +137753,7 @@ var ts; if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 if (externalCache) { - externalCache.setDocument(key, path, entry.sourceFile); + externalCache.setDocument(keyWithMode, path, entry.sourceFile); } } // If we're acquiring, then this is the first time this LS is asking for this document. @@ -135453,13 +137782,13 @@ var ts; } } } - function releaseDocument(fileName, compilationSettings, scriptKind) { + function releaseDocument(fileName, compilationSettings, scriptKind, impliedNodeFormat) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key, scriptKind); + return releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat); } - function releaseDocumentWithKey(path, key, scriptKind) { - var bucket = ts.Debug.checkDefined(buckets.get(key)); + function releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat) { + var bucket = ts.Debug.checkDefined(buckets.get(getDocumentRegistryBucketKeyWithMode(key, impliedNodeFormat))); var bucketEntry = bucket.get(path); var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; @@ -135507,7 +137836,7 @@ var ts; } var str = "{"; for (var key in value) { - if (ts.hasOwnProperty.call(value, key)) { // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier + if (ts.hasProperty(value, key)) { str += "".concat(key, ": ").concat(compilerOptionValueToString(value[key])); } } @@ -135516,6 +137845,9 @@ var ts; function getKeyForCompilationSettings(settings) { return ts.sourceFileAffectingCompilerOptions.map(function (option) { return compilerOptionValueToString(ts.getCompilerOptionValue(settings, option)); }).join("|") + (settings.pathsBasePath ? "|".concat(settings.pathsBasePath) : undefined); } + function getDocumentRegistryBucketKeyWithMode(key, mode) { + return (mode ? "".concat(key, "|").concat(mode) : key); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -135648,7 +137980,7 @@ var ts; return ts.findAncestor(node, function (node) { if (stopAtAmbientModule && isAmbientModuleDeclaration(node)) return "quit"; - return ts.some(node.modifiers, function (mod) { return mod.kind === 93 /* SyntaxKind.ExportKeyword */; }); + return ts.canHaveModifiers(node) && ts.some(node.modifiers, ts.isExportModifier); }); } function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { @@ -136072,7 +138404,7 @@ var ts; ts.Debug.assert(parent.name === node); return true; case 203 /* SyntaxKind.BindingElement */: - return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent); + return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent.parent.parent); default: return false; } @@ -136331,18 +138663,18 @@ var ts; || node.kind === 106 /* SyntaxKind.SuperKeyword */) { referenceEntries = entries && __spreadArray([], entries, true); } - else { - var queue = entries && __spreadArray([], entries, true); + else if (entries) { + var queue = ts.createQueue(entries); var seenNodes = new ts.Map(); - while (queue && queue.length) { - var entry = queue.shift(); + while (!queue.isEmpty()) { + var entry = queue.dequeue(); if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) { continue; } referenceEntries = ts.append(referenceEntries, entry); var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); if (entries_1) { - queue.push.apply(queue, entries_1); + queue.enqueue.apply(queue, entries_1); } } } @@ -136598,6 +138930,7 @@ var ts; var commonjsSource = source && ts.isBinaryExpression(source) ? source.left : undefined; return !!(source && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === source || d === commonjsSource; }))); } + FindAllReferences.isDeclarationOfSymbol = isDeclarationOfSymbol; /** * True if 'decl' provides a value, as in `function f() {}`; * false if 'decl' is just a location for a future write, as in 'let x;' @@ -136804,7 +139137,7 @@ var ts; result = references; continue; } - var _loop_5 = function (entry) { + var _loop_3 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* DefinitionKind.Symbol */) { result.push(entry); return "continue"; @@ -136836,7 +139169,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_5(entry); + _loop_3(entry); } } return result; @@ -137537,7 +139870,7 @@ var ts; // Use the parent symbol if the location is commonjs require syntax on javascript files only. if (ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 203 /* SyntaxKind.BindingElement */ - && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent)) { + && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) { referenceSymbol = referenceLocation.parent.symbol; // The parent will not have a symbol if it's an ObjectBindingPattern (when destructuring is used). In // this case, just skip it, since the bound identifiers are not an alias of the import. @@ -138417,8 +140750,8 @@ var ts; var declarations; if (symbol && symbol.declarations) { var indices = ts.indicesOf(symbol.declarations); - var keys_1 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); }); - indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_1[a].file, keys_1[b].file) || keys_1[a].pos - keys_1[b].pos; }); + var keys_2 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); }); + indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_2[a].file, keys_2[b].file) || keys_2[a].pos - keys_2[b].pos; }); var sortedDeclarations = ts.map(indices, function (i) { return symbol.declarations[i]; }); var lastDecl = void 0; for (var _i = 0, sortedDeclarations_1 = sortedDeclarations; _i < sortedDeclarations_1.length; _i++) { @@ -138688,14 +141021,16 @@ var ts; collect(node.body); } function collectCallSitesOfClassLikeDeclaration(node, collect) { - ts.forEach(node.decorators, collect); + ts.forEach(node.modifiers, collect); var heritage = ts.getClassExtendsHeritageElement(node); if (heritage) { collect(heritage.expression); } for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - ts.forEach(member.decorators, collect); + if (ts.canHaveModifiers(member)) { + ts.forEach(member.modifiers, collect); + } if (ts.isPropertyDeclaration(member)) { collect(member.initializer); } @@ -138864,7 +141199,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_6 = function (sourceFile) { + var _loop_4 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -138896,7 +141231,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_6(sourceFile); + _loop_4(sourceFile); } } function combineNormal(pathA, pathB) { @@ -139538,11 +141873,12 @@ var ts; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var jsdoc = _a[_i]; + var inheritDoc = ts.isJSDoc(jsdoc) && jsdoc.tags && ts.find(jsdoc.tags, function (t) { return t.kind === 327 /* SyntaxKind.JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc"); }); // skip comments containing @typedefs since they're not associated with particular declarations // Exceptions: // - @typedefs are themselves declarations with associated comments // - @param or @return indicate that the author thinks of it as a 'local' @typedef that's part of the function documentation - if (jsdoc.comment === undefined + if (jsdoc.comment === undefined && !inheritDoc || ts.isJSDoc(jsdoc) && declaration.kind !== 345 /* SyntaxKind.JSDocTypedefTag */ && declaration.kind !== 338 /* SyntaxKind.JSDocCallbackTag */ && jsdoc.tags @@ -139550,7 +141886,10 @@ var ts; && !jsdoc.tags.some(function (t) { return t.kind === 340 /* SyntaxKind.JSDocParameterTag */ || t.kind === 341 /* SyntaxKind.JSDocReturnTag */; })) { continue; } - var newparts = getDisplayPartsFromComment(jsdoc.comment, checker); + var newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : []; + if (inheritDoc && inheritDoc.comment) { + newparts = newparts.concat(getDisplayPartsFromComment(inheritDoc.comment, checker)); + } if (!ts.contains(parts, newparts, isIdenticalListOfDisplayParts)) { parts.push(newparts); } @@ -139784,8 +142123,12 @@ var ts; return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters, hasReturn = commentOwnerInfo.hasReturn; - var commentOwnerJSDoc = ts.hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? ts.lastOrUndefined(commentOwner.jsDoc) : undefined; - if (commentOwner.getStart(sourceFile) < position || commentOwnerJSDoc && commentOwnerJSDoc !== existingDocComment) { + var commentOwnerJsDoc = ts.hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : undefined; + var lastJsDoc = ts.lastOrUndefined(commentOwnerJsDoc); + if (commentOwner.getStart(sourceFile) < position + || lastJsDoc + && existingDocComment + && lastJsDoc !== existingDocComment) { return undefined; } var indentationStr = getIndentationStringAtPosition(sourceFile, position); @@ -139802,7 +142145,9 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var openComment = "/**"; var closeComment = " */"; - if (tags) { + // If any of the existing jsDoc has tags, ignore adding new ones. + var hasTag = (commentOwnerJsDoc || []).some(function (jsDoc) { return !!jsDoc.tags; }); + if (tags && !hasTag) { var preamble = openComment + newLine + indentationStr + " * "; var endLine = tokenStart === position ? newLine + indentationStr : ""; var result = preamble + newLine + tags + indentationStr + closeComment + endLine; @@ -139916,7 +142261,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_7 = function (sourceFile) { + var _loop_5 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -139928,7 +142273,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_7(sourceFile); + _loop_5(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -140524,7 +142869,7 @@ var ts; isPossibleConstructor(b.node) ? b.node : undefined; if (ctorFunction !== undefined) { - var ctorNode = ts.setTextRange(ts.factory.createConstructorDeclaration(/* decorators */ undefined, /* modifiers */ undefined, [], /* body */ undefined), ctorFunction); + var ctorNode = ts.setTextRange(ts.factory.createConstructorDeclaration(/* modifiers */ undefined, [], /* body */ undefined), ctorFunction); var ctor = emptyNavigationBarNode(ctorNode); ctor.indent = a.indent + 1; ctor.children = a.node === ctorFunction ? a.children : b.children; @@ -140540,7 +142885,6 @@ var ts; } } lastANode = a.node = ts.setTextRange(ts.factory.createClassDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, a.name || ts.factory.createIdentifier("__class__"), /* typeParameters */ undefined, /* heritageClauses */ undefined, []), a.node); @@ -140565,7 +142909,6 @@ var ts; if (!a.additionalNodes) a.additionalNodes = []; a.additionalNodes.push(ts.setTextRange(ts.factory.createClassDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, a.name || ts.factory.createIdentifier("__class__"), /* typeParameters */ undefined, /* heritageClauses */ undefined, []), b.node)); @@ -141074,7 +143417,7 @@ var ts; else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) { // If we’re in a declaration file, it’s safe to remove the import clause from it if (sourceFile.isDeclarationFile) { - usedImports.push(ts.factory.createImportDeclaration(importDecl.decorators, importDecl.modifiers, + usedImports.push(ts.factory.createImportDeclaration(importDecl.modifiers, /*importClause*/ undefined, moduleSpecifier, /*assertClause*/ undefined)); } @@ -141240,7 +143583,7 @@ var ts; newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(exportGroup_1, function (i) { return i.exportClause && ts.isNamedExports(i.exportClause) ? i.exportClause.elements : ts.emptyArray; })); var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); var exportDecl = exportGroup_1[0]; - coalescedExports.push(ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ? + coalescedExports.push(ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ? ts.factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : ts.factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.assertClause)); } @@ -141277,7 +143620,7 @@ var ts; } OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 + return ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, ts.factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 importDeclaration.moduleSpecifier, importDeclaration.assertClause); } function sortSpecifiers(specifiers) { @@ -141993,13 +144336,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_8 = function (start) { + var _loop_6 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_8(start); + var state_3 = _loop_6(start); if (typeof state_3 === "object") return state_3.value; } @@ -142585,10 +144928,10 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(program, sourceFile, position, options) { + function getRenameInfo(program, sourceFile, position, preferences) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, preferences); if (renameInfo) { return renameInfo; } @@ -142596,7 +144939,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, preferences) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -142624,7 +144967,12 @@ var ts; return undefined; } if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { - return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + return preferences.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + } + // Disallow rename for elements that would rename across `*/node_modules/*` packages. + var wouldRenameNodeModules = wouldRenameInOtherNodeModules(sourceFile, symbol, typeChecker, preferences); + if (wouldRenameNodeModules) { + return getRenameInfoError(wouldRenameNodeModules); } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) @@ -142638,6 +144986,49 @@ var ts; var sourceFile = declaration.getSourceFile(); return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Extension.Dts */); } + function wouldRenameInOtherNodeModules(originalFile, symbol, checker, preferences) { + if (!preferences.providePrefixAndSuffixTextForRename && symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var importSpecifier = symbol.declarations && ts.find(symbol.declarations, function (decl) { return ts.isImportSpecifier(decl); }); + if (importSpecifier && !importSpecifier.propertyName) { + symbol = checker.getAliasedSymbol(symbol); + } + } + var declarations = symbol.declarations; + if (!declarations) { + return undefined; + } + var originalPackage = getPackagePathComponents(originalFile.path); + if (originalPackage === undefined) { // original source file is not in node_modules + if (ts.some(declarations, function (declaration) { return ts.isInsideNodeModules(declaration.getSourceFile().path); })) { + return ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder; + } + else { + return undefined; + } + } + // original source file is in node_modules + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + var declPackage = getPackagePathComponents(declaration.getSourceFile().path); + if (declPackage) { + var length_2 = Math.min(originalPackage.length, declPackage.length); + for (var i = 0; i <= length_2; i++) { + if (ts.compareStringsCaseSensitive(originalPackage[i], declPackage[i]) !== 0 /* Comparison.EqualTo */) { + return ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder; + } + } + } + } + return undefined; + } + function getPackagePathComponents(filePath) { + var components = ts.getPathComponents(filePath); + var nodeModulesIdx = components.lastIndexOf("node_modules"); + if (nodeModulesIdx === -1) { + return undefined; + } + return components.slice(0, nodeModulesIdx + 2); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); @@ -142708,7 +145099,7 @@ var ts; var SmartSelectionRange; (function (SmartSelectionRange) { function getSmartSelectionRange(pos, sourceFile) { - var _a; + var _a, _b; var selectionRange = { textSpan: ts.createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd()) }; @@ -142760,6 +145151,17 @@ var ts; if (ts.hasJSDocNodes(node) && ((_a = node.jsDoc) === null || _a === void 0 ? void 0 : _a.length)) { pushSelectionRange(ts.first(node.jsDoc).getStart(), end); } + // (#39618 & #49807) + // When the node is a SyntaxList and its first child has a JSDoc comment, then the node's + // `start` (which usually is the result of calling `node.getStart()`) points to the first + // token after the JSDoc comment. So, we have to make sure we'd pushed the selection + // covering the JSDoc comment before diving further. + if (ts.isSyntaxList(node)) { + var firstChild = node.getChildren()[0]; + if (firstChild && ts.hasJSDocNodes(firstChild) && ((_b = firstChild.jsDoc) === null || _b === void 0 ? void 0 : _b.length) && firstChild.getStart() !== node.pos) { + start = Math.min(start, ts.first(firstChild.jsDoc).getStart()); + } + } pushSelectionRange(start, end); // String literals should have a stop both inside and outside their quotes. if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) { @@ -142833,6 +145235,7 @@ var ts; * other as well as of other top-level statements and declarations. */ function getSelectionChildren(node) { + var _a; // Group top-level imports if (ts.isSourceFile(node)) { return groupChildren(node.getChildAt(0).getChildren(), isImport); @@ -142848,7 +145251,7 @@ var ts; // because it allows the mapped type to become an object type with a // few keystrokes. if (ts.isMappedTypeNode(node)) { - var _a = node.getChildren(), openBraceToken = _a[0], children = _a.slice(1); + var _b = node.getChildren(), openBraceToken = _b[0], children = _b.slice(1); var closeBraceToken = ts.Debug.checkDefined(children.pop()); ts.Debug.assertEqual(openBraceToken.kind, 18 /* SyntaxKind.OpenBraceToken */); ts.Debug.assertEqual(closeBraceToken.kind, 19 /* SyntaxKind.CloseBraceToken */); @@ -142879,10 +145282,13 @@ var ts; var children = groupChildren(node.getChildren(), function (child) { return child === node.name || ts.contains(node.modifiers, child); }); - return splitChildren(children, function (_a) { + var firstJSDocChild = ((_a = children[0]) === null || _a === void 0 ? void 0 : _a.kind) === 320 /* SyntaxKind.JSDoc */ ? children[0] : undefined; + var withJSDocSeparated = firstJSDocChild ? children.slice(1) : children; + var splittedChildren = splitChildren(withJSDocSeparated, function (_a) { var kind = _a.kind; return kind === 58 /* SyntaxKind.ColonToken */; }); + return firstJSDocChild ? [firstJSDocChild, createSyntaxList(splittedChildren)] : splittedChildren; } // Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`. if (ts.isParameter(node)) { @@ -143418,7 +145824,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_9 = function (n) { + var _loop_7 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: ".concat(ts.Debug.formatSyntaxKind(n.kind), ", parent: ").concat(ts.Debug.formatSyntaxKind(n.parent.kind)); }); @@ -143428,7 +145834,7 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_4 = _loop_9(n); + var state_4 = _loop_7(n); if (typeof state_4 === "object") return state_4.value; } @@ -143627,7 +146033,7 @@ var ts; if (!ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { return; } - if (ts.isTypeNode(node)) { + if (ts.isTypeNode(node) && !ts.isExpressionWithTypeArguments(node)) { return; } if (preferences.includeInlayVariableTypeHints && ts.isVariableDeclaration(node)) { @@ -143692,7 +146098,7 @@ var ts; return type.symbol && (type.symbol.flags & 1536 /* SymbolFlags.Module */); } function visitVariableLikeDeclaration(decl) { - if (!decl.initializer || ts.isBindingPattern(decl.name)) { + if (!decl.initializer || ts.isBindingPattern(decl.name) || ts.isVariableDeclaration(decl) && !isHintableDeclaration(decl)) { return; } var effectiveTypeAnnotation = ts.getEffectiveTypeAnnotationNode(decl); @@ -143705,6 +146111,10 @@ var ts; } var typeDisplayString = printTypeInSingleLine(declarationType); if (typeDisplayString) { + var isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && ts.equateStringsCaseInsensitive(decl.name.getText(), typeDisplayString); + if (isVariableNameMatchesType) { + return; + } addTypeHints(typeDisplayString, decl.name.end); } } @@ -143816,6 +146226,9 @@ var ts; } for (var i = 0; i < node.parameters.length && i < signature.parameters.length; ++i) { var param = node.parameters[i]; + if (!isHintableDeclaration(param)) { + continue; + } var effectiveTypeAnnotation = ts.getEffectiveTypeAnnotationNode(param); if (effectiveTypeAnnotation) { continue; @@ -143857,6 +146270,13 @@ var ts; function isUndefined(name) { return name === "undefined"; } + function isHintableDeclaration(node) { + if ((ts.isParameterDeclaration(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) && node.initializer) { + var initializer = ts.skipParentheses(node.initializer); + return !(isHintableLiteral(initializer) || ts.isNewExpression(initializer) || ts.isObjectLiteralExpression(initializer) || ts.isAssertionExpression(initializer)); + } + return true; + } } InlayHints.provideInlayHints = provideInlayHints; })(InlayHints = ts.InlayHints || (ts.InlayHints = {})); @@ -145027,7 +147447,7 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_10 = function (opt) { + var _loop_8 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -145046,7 +147466,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_10(opt); + _loop_8(opt); } return options; } @@ -145996,7 +148416,7 @@ var ts; } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - !!context.contextNode.decorators && + ts.hasDecorators(context.contextNode) && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -146561,6 +148981,7 @@ var ts; var options = _a.options, getRules = _a.getRules, host = _a.host; // formatting context is used by rules provider var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); + var previousRangeTriviaEnd; var previousRange; var previousParent; var previousRangeStartLine; @@ -146571,7 +148992,7 @@ var ts; if (formattingScanner.isOnToken()) { var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; var undecoratedStartLine = startLine; - if (enclosingNode.decorators) { + if (ts.hasDecorators(enclosingNode)) { undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; } processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); @@ -146589,10 +149010,30 @@ var ts; } } if (previousRange && formattingScanner.getStartPos() >= originalRange.end) { + // Formatting edits happen by looking at pairs of contiguous tokens (see `processPair`), + // typically inserting or deleting whitespace between them. The recursive `processNode` + // logic above bails out as soon as it encounters a token that is beyond the end of the + // range we're supposed to format (or if we reach the end of the file). But this potentially + // leaves out an edit that would occur *inside* the requested range but cannot be discovered + // without looking at one token *beyond* the end of the range: consider the line `x = { }` + // with a selection from the beginning of the line to the space inside the curly braces, + // inclusive. We would expect a format-selection would delete the space (if rules apply), + // but in order to do that, we need to process the pair ["{", "}"], but we stopped processing + // just before getting there. This block handles this trailing edit. var tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : undefined; - if (tokenInfo) { + if (tokenInfo && tokenInfo.pos === previousRangeTriviaEnd) { + // We need to check that tokenInfo and previousRange are contiguous: the `originalRange` + // may have ended in the middle of a token, which means we will have stopped formatting + // on that token, leaving `previousRange` pointing to the token before it, but already + // having moved the formatting scanner (where we just got `tokenInfo`) to the next token. + // If this happens, our supposed pair [previousRange, tokenInfo] actually straddles the + // token that intersects the end of the range we're supposed to format, so the pair will + // produce bogus edits if we try to `processPair`. Recall that the point of this logic is + // to perform a trailing edit at the end of the selection range: but there can be no valid + // edit in the middle of a token where the range ended, so if we have a non-contiguous + // pair here, we're already done and we can ignore it. var parent = ((_b = ts.findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)) === null || _b === void 0 ? void 0 : _b.parent) || previousParent; processPair(tokenInfo, sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line, parent, previousRange, previousRangeStartLine, previousParent, parent, /*dynamicIndentation*/ undefined); @@ -146658,8 +149099,10 @@ var ts; } } function getFirstNonDecoratorTokenOfNode(node) { - if (node.modifiers && node.modifiers.length) { - return node.modifiers[0].kind; + if (ts.canHaveModifiers(node)) { + var modifier = ts.find(node.modifiers, ts.isModifier, ts.findIndex(node.modifiers, ts.isDecorator)); + if (modifier) + return modifier.kind; } switch (node.kind) { case 257 /* SyntaxKind.ClassDeclaration */: return 84 /* SyntaxKind.ClassKeyword */; @@ -146734,7 +149177,6 @@ var ts; case 280 /* SyntaxKind.JsxOpeningElement */: case 281 /* SyntaxKind.JsxClosingElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: return false; } break; @@ -146748,7 +149190,7 @@ var ts; // if token line equals to the line of containing node (this is a first token in the node) - use node indentation return nodeStartLine !== line // if this token is the first token following the list of decorators, we do not need to indent - && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + && !(ts.hasDecorators(node) && kind === getFirstNonDecoratorTokenOfNode(node)); } function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node @@ -146788,13 +149230,14 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { + ts.Debug.assert(!ts.nodeIsSynthesized(child)); if (ts.nodeIsMissing(child)) { return inheritedIndentation; } var childStartPos = child.getStart(sourceFile); var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; var undecoratedChildStartLine = childStartLine; - if (child.decorators) { + if (ts.hasDecorators(child)) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } // if child is a list item - try to get its indentation, only if parent is within the original range. @@ -146854,6 +149297,7 @@ var ts; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); + ts.Debug.assert(!ts.nodeIsSynthesized(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; @@ -146904,12 +149348,10 @@ var ts; var listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== 0 /* SyntaxKind.Unknown */ && formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(parent); - if (tokenInfo.token.kind === 27 /* SyntaxKind.CommaToken */ && ts.isCallLikeExpression(parent)) { - var commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - if (startLine !== commaTokenLine) { - formattingScanner.advance(); - tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; - } + if (tokenInfo.token.kind === 27 /* SyntaxKind.CommaToken */) { + // consume the comma + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one @@ -146949,6 +149391,7 @@ var ts; } } if (currentTokenInfo.trailingTrivia) { + previousRangeTriviaEnd = ts.last(currentTokenInfo.trailingTrivia).end; processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); } if (indentToken) { @@ -147019,6 +149462,7 @@ var ts; } } previousRange = range; + previousRangeTriviaEnd = range.end; previousParent = parent; previousRangeStartLine = rangeStart.line; return lineAction; @@ -147310,6 +149754,12 @@ var ts; case 169 /* SyntaxKind.MethodDeclaration */: case 168 /* SyntaxKind.MethodSignature */: case 214 /* SyntaxKind.ArrowFunction */: + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: if (node.typeParameters === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -147326,7 +149776,19 @@ var ts; return 20 /* SyntaxKind.OpenParenToken */; } break; + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 258 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.TypeAliasDeclaration */: + if (node.typeParameters === list) { + return 29 /* SyntaxKind.LessThanToken */; + } + break; case 178 /* SyntaxKind.TypeReference */: + case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 181 /* SyntaxKind.TypeQuery */: + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 200 /* SyntaxKind.ImportType */: if (node.typeArguments === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -148590,7 +151052,7 @@ var ts; return { indentation: indentation, prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter, - suffix: insertTrailingComma ? "," : "" + suffix: insertTrailingComma ? "," : ts.isInterfaceDeclaration(node) && isEmpty ? ";" : "" }; }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -148794,7 +151256,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_11 = function (sourceFile, node) { + var _loop_9 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -148807,7 +151269,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_11(sourceFile, node); + _loop_9(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -148895,14 +151357,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_12 = function (i) { + var _loop_10 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return "".concat(JSON.stringify(normalized[i].range), " and ").concat(JSON.stringify(normalized[i + 1].range)); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_12(i); + _loop_10(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -149613,7 +152075,6 @@ var ts; var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { var exportDeclaration = ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([]), /*moduleSpecifier*/ undefined); @@ -149811,7 +152272,7 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_13 = function (identifier) { + var _loop_11 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; @@ -149844,7 +152305,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_13(identifier); + _loop_11(identifier); } return initializers && { initializers: initializers, @@ -150143,8 +152604,7 @@ var ts; ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); var typeNode = ts.factory.createTypeReferenceNode(param.name, /*typeArguments*/ undefined); - var replacement = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); + var replacement = ts.factory.createParameterDeclaration(param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); changeTracker.replaceNode(sourceFile, param, replacement); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -150369,7 +152829,7 @@ var ts; var isRest = node.type.kind === 318 /* SyntaxKind.JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : node.dotDotDotToken; - return ts.factory.createParameterDeclaration(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + return ts.factory.createParameterDeclaration(node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); } function transformJSDocTypeReference(node) { var name = node.typeName; @@ -150404,12 +152864,11 @@ var ts; } function transformJSDocIndexSignature(node) { var index = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "n" : "s", /*questionToken*/ undefined, ts.factory.createTypeReferenceNode(node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "number" : "string", []), /*initializer*/ undefined); - var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*modifiers*/ undefined, [index], node.typeArguments[1])]); ts.setEmitFlags(indexSignature, 1 /* EmitFlags.SingleLine */); return indexSignature; } @@ -150551,7 +153010,7 @@ var ts; ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { - members.push(ts.factory.createPropertyDeclaration([], modifiers, symbol.name, /*questionToken*/ undefined, + members.push(ts.factory.createPropertyDeclaration(modifiers, symbol.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); return; } @@ -150587,7 +153046,7 @@ var ts; return; if (!ts.isPropertyAccessExpression(memberDeclaration)) return; - var prop = ts.factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); + var prop = ts.factory.createPropertyDeclaration(modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); members.push(prop); return; @@ -150600,7 +153059,7 @@ var ts; } function createFunctionExpressionMember(members, functionExpression, name) { var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 131 /* SyntaxKind.AsyncKeyword */)); - var method = ts.factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); @@ -150618,7 +153077,7 @@ var ts; bodyBlock = ts.factory.createBlock([ts.factory.createReturnStatement(arrowFunctionBody)]); } var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 131 /* SyntaxKind.AsyncKeyword */)); - var method = ts.factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); @@ -150632,10 +153091,10 @@ var ts; } var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { - memberElements.unshift(ts.factory.createConstructorDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, initializer.parameters, initializer.body)); } var modifiers = getModifierKindFromSource(node.parent.parent, 93 /* SyntaxKind.ExportKeyword */); - var cls = ts.factory.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + var cls = ts.factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; @@ -150643,17 +153102,17 @@ var ts; function createClassFromFunctionDeclaration(node) { var memberElements = createClassElementsFromSymbol(ctorSymbol); if (node.body) { - memberElements.unshift(ts.factory.createConstructorDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, node.parameters, node.body)); } var modifiers = getModifierKindFromSource(node, 93 /* SyntaxKind.ExportKeyword */); - var cls = ts.factory.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + var cls = ts.factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } } function getModifierKindFromSource(source, kind) { - return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + return ts.canHaveModifiers(source) ? ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }) : undefined; } function isConstructorAssignment(x) { if (!x.name) @@ -150729,12 +153188,9 @@ var ts; if (!returnStatements.length) { return; } - var pos = functionToConvert.modifiers ? functionToConvert.modifiers.end : - functionToConvert.decorators ? ts.skipTrivia(sourceFile.text, functionToConvert.decorators.end) : - functionToConvert.getStart(sourceFile); - var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; - changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, options); - var _loop_14 = function (returnStatement) { + var pos = ts.skipTrivia(sourceFile.text, ts.moveRangePastModifiers(functionToConvert).pos); + changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, { suffix: " " }); + var _loop_12 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); @@ -150756,7 +153212,7 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - var state_5 = _loop_14(returnStatement); + var state_5 = _loop_12(returnStatement); if (typeof state_5 === "object") return state_5.value; } @@ -151859,12 +154315,10 @@ var ts; } // Node helpers function functionExpressionToDeclaration(name, additionalModifiers, fn, useSitesToUnqualify) { - return ts.factory.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); + return ts.factory.createFunctionDeclaration(ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); } function classExpressionToDeclaration(name, additionalModifiers, cls, useSitesToUnqualify) { - return ts.factory.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); + return ts.factory.createClassDeclaration(ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); } function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" @@ -151879,7 +154333,6 @@ var ts; } function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { return ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, exportSpecifiers && ts.factory.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.factory.createStringLiteral(moduleSpecifier)); } @@ -151968,11 +154421,10 @@ var ts; changes.insertModifierBefore(context.sourceFile, 152 /* SyntaxKind.TypeKeyword */, exportClause); } else { - var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.decorators, exportDeclaration.modifiers, + var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, /*isTypeOnly*/ false, ts.factory.updateNamedExports(exportClause, ts.filter(exportClause.elements, function (e) { return !ts.contains(typeExportSpecifiers, e); })), exportDeclaration.moduleSpecifier, /*assertClause*/ undefined); var typeExportDeclaration = ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ true, ts.factory.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, /*assertClause*/ undefined); @@ -152036,7 +154488,6 @@ var ts; if (importClause.name && importClause.namedBindings) { changes.deleteNodeRangeExcludingEnd(context.sourceFile, importClause.name, importDeclaration.importClause.namedBindings); changes.insertNodeBefore(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ true, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, @@ -152390,6 +154841,18 @@ var ts; return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0; } } + function createImportSpecifierResolver(importingFile, program, host, preferences) { + var packageJsonImportFilter = ts.createPackageJsonImportFilter(importingFile, preferences, host); + var importMap = createExistingImportMap(program.getTypeChecker(), importingFile, program.getCompilerOptions()); + return { getModuleSpecifierForBestExportInfo: getModuleSpecifierForBestExportInfo }; + function getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, fromCacheOnly) { + var _a = getImportFixes(exportInfo, { symbolName: symbolName, position: position }, isValidTypeOnlyUseSite, + /*useRequire*/ false, program, importingFile, host, preferences, importMap, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount; + var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host); + return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount }); + } + } + codefix.createImportSpecifierResolver = createImportSpecifierResolver; // Sorted with the preferred fix coming first. var ImportFixKind; (function (ImportFixKind) { @@ -152467,7 +154930,7 @@ var ts; var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); }); - ts.forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { + ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(importingFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { @@ -152490,18 +154953,12 @@ var ts; return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, preferences, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); } } - function getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, importingFile, program, host, preferences, packageJsonImportFilter, fromCacheOnly) { - var _a = getImportFixes(exportInfo, { symbolName: symbolName, position: position }, isValidTypeOnlyUseSite, - /*useRequire*/ false, program, importingFile, host, preferences, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount; - var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter || ts.createPackageJsonImportFilter(importingFile, preferences, host), host); - return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount }); - } - codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo; function getImportFixes(exportInfos, useNamespaceInfo, /** undefined only for missing JSX namespace */ - isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, fromCacheOnly) { + isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap, fromCacheOnly) { + if (importMap === void 0) { importMap = createExistingImportMap(program.getTypeChecker(), sourceFile, program.getCompilerOptions()); } var checker = program.getTypeChecker(); - var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile, program.getCompilerOptions()); }); + var existingImports = ts.flatMap(exportInfos, importMap.getImportsForExportInfo); var useNamespace = useNamespaceInfo && tryUseExistingNamespaceImport(existingImports, useNamespaceInfo.symbolName, useNamespaceInfo.position, checker); var addToExisting = tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, program.getCompilerOptions()); if (addToExisting) { @@ -152629,21 +155086,37 @@ var ts; }; }); } - function getExistingImportDeclarations(_a, checker, importingFile, compilerOptions) { - var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, targetFlags = _a.targetFlags, symbol = _a.symbol; - // Can't use an es6 import for a type in JS. - if (!(targetFlags & 111551 /* SymbolFlags.Value */) && ts.isSourceFileJS(importingFile)) - return ts.emptyArray; - var importKind = getImportKind(importingFile, exportKind, compilerOptions); - return ts.mapDefined(importingFile.imports, function (moduleSpecifier) { + function createExistingImportMap(checker, importingFile, compilerOptions) { + var importMap; + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; var i = ts.importFromModuleSpecifier(moduleSpecifier); if (ts.isVariableDeclarationInitializedToRequire(i.parent)) { - return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind, symbol: symbol, targetFlags: targetFlags } : undefined; + var moduleSymbol = checker.resolveExternalModuleName(moduleSpecifier); + if (moduleSymbol) { + (importMap || (importMap = ts.createMultiMap())).add(ts.getSymbolId(moduleSymbol), i.parent); + } } - if (i.kind === 266 /* SyntaxKind.ImportDeclaration */ || i.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { - return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind, symbol: symbol, targetFlags: targetFlags } : undefined; + else if (i.kind === 266 /* SyntaxKind.ImportDeclaration */ || i.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol) { + (importMap || (importMap = ts.createMultiMap())).add(ts.getSymbolId(moduleSymbol), i); + } } - }); + } + return { + getImportsForExportInfo: function (_a) { + var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, targetFlags = _a.targetFlags, symbol = _a.symbol; + // Can't use an es6 import for a type in JS. + if (!(targetFlags & 111551 /* SymbolFlags.Value */) && ts.isSourceFileJS(importingFile)) + return ts.emptyArray; + var matchingDeclarations = importMap === null || importMap === void 0 ? void 0 : importMap.get(ts.getSymbolId(moduleSymbol)); + if (!matchingDeclarations) + return ts.emptyArray; + var importKind = getImportKind(importingFile, exportKind, compilerOptions); + return matchingDeclarations.map(function (declaration) { return ({ declaration: declaration, importKind: importKind, symbol: symbol, targetFlags: targetFlags }); }); + } + }; } function shouldUseRequire(sourceFile, program) { // 1. TypeScript files don't use require variable declarations @@ -152926,7 +155399,7 @@ var ts; originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol: moduleSymbol, moduleFileName: toFile === null || toFile === void 0 ? void 0 : toFile.fileName, exportKind: exportKind, targetFlags: ts.skipAlias(exportedSymbol, checker).flags, isFromPackageJson: isFromPackageJson }); } } - ts.forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { + ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); @@ -153186,10 +155659,8 @@ var ts; if (namespaceLikeImport) { var declaration = namespaceLikeImport.importKind === 3 /* ImportKind.CommonJS */ ? ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, needsTypeOnly(namespaceLikeImport), ts.factory.createIdentifier(namespaceLikeImport.name), ts.factory.createExternalModuleReference(quotedModuleSpecifier)) : ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(needsTypeOnly(namespaceLikeImport), /*name*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier, /*assertClause*/ undefined); @@ -153269,6 +155740,113 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingConstraint"; + var errorCodes = [ + // We want errors this could be attached to: + // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint + ts.Diagnostics.Type_0_is_not_comparable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + ts.Diagnostics.Property_0_is_incompatible_with_index_signature.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program, preferences = context.preferences, host = context.host; + var info = getInfo(program, sourceFile, span); + if (info === undefined) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingConstraint(t, program, preferences, host, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_extends_constraint, fixId, ts.Diagnostics.Add_extends_constraint_to_all_type_parameters)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var program = context.program, preferences = context.preferences, host = context.host; + var seen = new ts.Map(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(program, diag.file, ts.createTextSpan(diag.start, diag.length)); + if (info) { + if (ts.addToSeen(seen, ts.getNodeId(info.declaration))) { + return addMissingConstraint(changes, program, preferences, host, diag.file, info); + } + } + return undefined; + }); + })); + } + }); + function getInfo(program, sourceFile, span) { + var diag = ts.find(program.getSemanticDiagnostics(sourceFile), function (diag) { return diag.start === span.start && diag.length === span.length; }); + if (diag === undefined || diag.relatedInformation === undefined) + return; + var related = ts.find(diag.relatedInformation, function (related) { return related.code === ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code; }); + if (related === undefined || related.file === undefined || related.start === undefined || related.length === undefined) + return; + var declaration = findAncestorMatchingSpan(related.file, ts.createTextSpan(related.start, related.length)); + if (declaration === undefined) + return; + if (ts.isIdentifier(declaration) && ts.isTypeParameterDeclaration(declaration.parent)) { + declaration = declaration.parent; + } + if (ts.isTypeParameterDeclaration(declaration)) { + // should only issue fix on type parameters written using `extends` + if (ts.isMappedTypeNode(declaration.parent)) + return; + var token = ts.getTokenAtPosition(sourceFile, span.start); + var checker = program.getTypeChecker(); + var constraint = tryGetConstraintType(checker, token) || tryGetConstraintFromDiagnosticMessage(related.messageText); + return { constraint: constraint, declaration: declaration, token: token }; + } + return undefined; + } + function addMissingConstraint(changes, program, preferences, host, sourceFile, info) { + var declaration = info.declaration, constraint = info.constraint; + var checker = program.getTypeChecker(); + if (ts.isString(constraint)) { + changes.insertText(sourceFile, declaration.name.end, " extends ".concat(constraint)); + } + else { + var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions()); + var tracker = codefix.getNoopSymbolTrackerWithResolver({ program: program, host: host }); + var importAdder = codefix.createImportAdder(sourceFile, program, preferences, host); + var typeNode = codefix.typeToAutoImportableTypeNode(checker, importAdder, constraint, /*contextNode*/ undefined, scriptTarget, /*flags*/ undefined, tracker); + if (typeNode) { + changes.replaceNode(sourceFile, declaration, ts.factory.updateTypeParameterDeclaration(declaration, /*modifiers*/ undefined, declaration.name, typeNode, declaration.default)); + importAdder.writeFixes(changes); + } + } + } + function findAncestorMatchingSpan(sourceFile, span) { + var end = ts.textSpanEnd(span); + var token = ts.getTokenAtPosition(sourceFile, span.start); + while (token.end < end) { + token = token.parent; + } + return token; + } + function tryGetConstraintFromDiagnosticMessage(messageText) { + var _a = ts.flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || [], _ = _a[0], constraint = _a[1]; + return constraint; + } + function tryGetConstraintType(checker, node) { + if (ts.isTypeNode(node.parent)) { + return checker.getTypeArgumentConstraint(node.parent); + } + var contextualType = ts.isExpression(node) ? checker.getContextualType(node) : undefined; + return contextualType || checker.getTypeAtLocation(node); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -153391,10 +155969,11 @@ var ts; var staticModifier = ts.find(modifiers, ts.isStaticModifier); var abstractModifier = ts.find(modifiers, ts.isAbstractModifier); var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var lastDecorator = ts.findLast(modifiers, ts.isDecorator); var modifierPos = abstractModifier ? abstractModifier.end : staticModifier ? staticModifier.end : accessibilityModifier ? accessibilityModifier.end : - classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + lastDecorator ? ts.skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile); var options = accessibilityModifier || staticModifier || abstractModifier ? { prefix: " " } : { suffix: " " }; changeTracker.insertModifierAt(sourceFile, modifierPos, 159 /* SyntaxKind.OverrideKeyword */, options); } @@ -153404,7 +155983,7 @@ var ts; changeTracker.filterJSDocTags(sourceFile, classElement, ts.not(ts.isJSDocOverrideTag)); return; } - var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 159 /* SyntaxKind.OverrideKeyword */; }); + var overrideModifier = ts.find(classElement.modifiers, ts.isOverrideModifier); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); } @@ -154004,7 +156583,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, declaration) { var supers = ts.isTypeLiteralNode(declaration) ? undefined : codefix.getAllSupers(declaration, checker); - var _loop_15 = function (info) { + var _loop_13 = function (info) { // If some superclass added this property, don't add it again. if (supers === null || supers === void 0 ? void 0 : supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -154031,7 +156610,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_15(info); + _loop_13(info); } }); })); @@ -154083,7 +156662,7 @@ var ts; return undefined; return { kind: 4 /* InfoKind.JsxAttributes */, token: token, attributes: attributes, parentDeclaration: token.parent }; } - if (ts.isIdentifier(token) && ts.isCallExpression(parent)) { + if (ts.isIdentifier(token) && ts.isCallExpression(parent) && parent.expression === token) { return { kind: 2 /* InfoKind.Function */, token: token, call: parent, sourceFile: sourceFile, modifierFlags: 0 /* ModifierFlags.None */, parentDeclaration: sourceFile }; } if (!ts.isPropertyAccessExpression(parent)) @@ -154160,7 +156739,6 @@ var ts; } else if (ts.isPrivateIdentifier(token)) { var property = ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, tokenName, /*questionToken*/ undefined, /*type*/ undefined, @@ -154218,7 +156796,7 @@ var ts; function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) { var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var property = ts.isClassLike(node) - ? ts.factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined) + ? ts.factory.createPropertyDeclaration(modifiers, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined) : ts.factory.createPropertySignature(/*modifiers*/ undefined, tokenName, /*questionToken*/ undefined, typeNode); var lastProp = getNodeToInsertPropertyAfter(node); if (lastProp) { @@ -154243,13 +156821,11 @@ var ts; // Index signatures cannot have the static modifier. var stringTypeNode = ts.factory.createKeywordTypeNode(150 /* SyntaxKind.StringKeyword */); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); var indexSignature = ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertMemberAtStart(sourceFile, node, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. @@ -154297,7 +156873,7 @@ var ts; return !!(type && type.flags & 402653316 /* TypeFlags.StringLike */); }); var enumMember = ts.factory.createEnumMember(token, hasStringInitializer ? ts.factory.createStringLiteral(token.text) : undefined); - changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.decorators, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), { + changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude }); @@ -154306,6 +156882,7 @@ var ts; var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(256 /* SyntaxKind.FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration); changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); + importAdder.writeFixes(changes); } function addJsxAttributes(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); @@ -154314,7 +156891,7 @@ var ts; var jsxAttributesNode = info.parentDeclaration.attributes; var hasSpreadAttribute = ts.some(jsxAttributesNode.properties, ts.isJsxSpreadAttribute); var attrs = ts.map(info.attributes, function (attr) { - var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr)); + var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr), info.parentDeclaration); var name = ts.factory.createIdentifier(attr.name); var jsxAttribute = ts.factory.createJsxAttribute(name, ts.factory.createJsxExpression(/*dotDotDotToken*/ undefined, value)); // formattingScanner requires the Identifier to have a context for scanning attributes with "-" (data-foo). @@ -154324,6 +156901,7 @@ var ts; var jsxAttributes = ts.factory.createJsxAttributes(hasSpreadAttribute ? __spreadArray(__spreadArray([], attrs, true), jsxAttributesNode.properties, true) : __spreadArray(__spreadArray([], jsxAttributesNode.properties, true), attrs, true)); var options = { prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : undefined }; changes.replaceNode(context.sourceFile, jsxAttributesNode, jsxAttributes, options); + importAdder.writeFixes(changes); } function addObjectLiteralProperties(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); @@ -154331,8 +156909,8 @@ var ts; var target = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var props = ts.map(info.properties, function (prop) { - var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop)); - return ts.factory.createPropertyAssignment(ts.createPropertyNameNodeForIdentifierOrLiteral(prop.name, target, quotePreference === 0 /* QuotePreference.Single */), initializer); + var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), info.parentDeclaration); + return ts.factory.createPropertyAssignment(createPropertyNameFromSymbol(prop, target, quotePreference, checker), initializer); }); var options = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, @@ -154340,8 +156918,9 @@ var ts; indentation: info.indentation }; changes.replaceNode(context.sourceFile, info.parentDeclaration, ts.factory.createObjectLiteralExpression(__spreadArray(__spreadArray([], info.parentDeclaration.properties, true), props, true), /*multiLine*/ true), options); + importAdder.writeFixes(changes); } - function tryGetValueFromType(context, checker, importAdder, quotePreference, type) { + function tryGetValueFromType(context, checker, importAdder, quotePreference, type, enclosingDeclaration) { if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { return createUndefined(); } @@ -154378,7 +156957,7 @@ var ts; return ts.factory.createNull(); } if (type.flags & 1048576 /* TypeFlags.Union */) { - var expression = ts.firstDefined(type.types, function (t) { return tryGetValueFromType(context, checker, importAdder, quotePreference, t); }); + var expression = ts.firstDefined(type.types, function (t) { return tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration); }); return expression !== null && expression !== void 0 ? expression : createUndefined(); } if (checker.isArrayLikeType(type)) { @@ -154386,7 +156965,7 @@ var ts; } if (isObjectLiteralType(type)) { var props = ts.map(checker.getPropertiesOfType(type), function (prop) { - var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration)) : createUndefined(); + var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration), enclosingDeclaration) : createUndefined(); return ts.factory.createPropertyAssignment(prop.name, initializer); }); return ts.factory.createObjectLiteralExpression(props, /*multiLine*/ true); @@ -154398,7 +156977,7 @@ var ts; var signature = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (signature === undefined) return createUndefined(); - var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ undefined, importAdder); + var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ enclosingDeclaration, importAdder); return func !== null && func !== void 0 ? func : createUndefined(); } if (ts.getObjectFlags(type) & 1 /* ObjectFlags.Class */) { @@ -154451,6 +157030,15 @@ var ts; var declaration = ts.findAncestor(callExpression, function (n) { return ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n); }); return declaration && declaration.parent === node ? declaration : undefined; } + function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) { + if (ts.isTransientSymbol(symbol) && symbol.nameType && symbol.nameType.flags & 8192 /* TypeFlags.UniqueESSymbol */) { + var expression = checker.symbolToExpression(symbol.nameType.symbol, 111551 /* SymbolFlags.Value */, symbol.valueDeclaration, 1048576 /* NodeBuilderFlags.AllowUniqueESSymbolType */); + if (expression) { + return ts.factory.createComputedPropertyName(expression); + } + } + return ts.createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* QuotePreference.Single */); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -155376,7 +157964,12 @@ var ts; if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) { if (parameter.modifiers && parameter.modifiers.length > 0 && (!ts.isIdentifier(parameter.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) { - parameter.modifiers.forEach(function (modifier) { return changes.deleteModifier(sourceFile, modifier); }); + for (var _i = 0, _a = parameter.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isModifier(modifier)) { + changes.deleteModifier(sourceFile, modifier); + } + } } else if (!parameter.initializer && isNotProvidedArguments(parameter, checker, sourceFiles)) { changes.delete(sourceFile, parameter); @@ -156791,7 +159384,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_16 = function (i) { + var _loop_14 = function (i) { var symbol = checker.createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg".concat(i))); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -156800,7 +159393,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_16(i); + _loop_14(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* SignatureFlags.None */); @@ -156990,8 +159583,7 @@ var ts; importSymbols(importAdder, importableReference.symbols); } } - addClassElement(ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, + addClassElement(ts.factory.createPropertyDeclaration(modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; case 172 /* SyntaxKind.GetAccessor */: @@ -157011,15 +159603,13 @@ var ts; for (var _i = 0, orderedAccessors_1 = orderedAccessors; _i < orderedAccessors_1.length; _i++) { var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { - addClassElement(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createGetAccessorDeclaration(modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; - addClassElement(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createSetAccessorDeclaration(modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } } break; @@ -157033,7 +159623,7 @@ var ts; // If there is more than one overload but no implementation signature // (eg: an abstract method or interface declaration), there is a 1-1 // correspondence of declarations and signatures. - var signatures = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); + var signatures = type.isUnion() ? ts.flatMap(type.types, function (t) { return t.getCallSignatures(); }) : type.getCallSignatures(); if (!ts.some(signatures)) { break; } @@ -157114,7 +159704,7 @@ var ts; type = importableReference.typeNode; importSymbols(importAdder, importableReference.symbols); } - return ts.factory.updateParameterDeclaration(parameterDecl, parameterDecl.decorators, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, parameterDecl.questionToken, type, parameterDecl.initializer); + return ts.factory.updateParameterDeclaration(parameterDecl, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, parameterDecl.questionToken, type, parameterDecl.initializer); }); if (parameters !== newParameters) { parameters = ts.setTextRange(ts.factory.createNodeArray(newParameters, parameters.hasTrailingComma), parameters); @@ -157136,7 +159726,7 @@ var ts; return ts.factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body !== null && body !== void 0 ? body : signatureDeclaration.body); } if (ts.isMethodDeclaration(signatureDeclaration)) { - return ts.factory.updateMethodDeclaration(signatureDeclaration, /* decorators */ undefined, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); + return ts.factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); } return undefined; } @@ -157152,40 +159742,50 @@ var ts; var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined; }); - var types = isJs ? [] : ts.map(args, function (arg) { - return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker); - }); + var instanceTypes = isJs ? [] : ts.map(args, function (arg) { return checker.getTypeAtLocation(arg); }); + var _a = getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, /*flags*/ undefined, tracker), argumentTypeNodes = _a.argumentTypeNodes, argumentTypeParameters = _a.argumentTypeParameters; var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var asteriskToken = ts.isYieldExpression(parent) ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined; - var typeParameters = isJs || typeArguments === undefined - ? undefined - : ts.map(typeArguments, function (_, i) { - return ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, 84 /* CharacterCodes.T */ + typeArguments.length - 1 <= 90 /* CharacterCodes.Z */ ? String.fromCharCode(84 /* CharacterCodes.T */ + i) : "T".concat(i)); - }); - var parameters = createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, isJs); + var typeParameters = isJs ? undefined : createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments); + var parameters = createDummyParameters(args.length, names, argumentTypeNodes, /*minArgumentCount*/ undefined, isJs); var type = isJs || contextualType === undefined ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); switch (kind) { case 169 /* SyntaxKind.MethodDeclaration */: - return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers, asteriskToken, name, + return ts.factory.createMethodDeclaration(modifiers, asteriskToken, name, /*questionToken*/ undefined, typeParameters, parameters, type, createStubbedMethodBody(quotePreference)); case 168 /* SyntaxKind.MethodSignature */: return ts.factory.createMethodSignature(modifiers, name, - /*questionToken*/ undefined, typeParameters, parameters, type); + /*questionToken*/ undefined, typeParameters, parameters, type === undefined ? ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */) : type); case 256 /* SyntaxKind.FunctionDeclaration */: - return ts.factory.createFunctionDeclaration( - /*decorators*/ undefined, modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); + return ts.factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); default: ts.Debug.fail("Unexpected kind"); } } codefix.createSignatureDeclarationFromCallExpression = createSignatureDeclarationFromCallExpression; + function createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments) { + var usedNames = new ts.Set(argumentTypeParameters.map(function (pair) { return pair[0]; })); + var constraintsByName = new ts.Map(argumentTypeParameters); + if (typeArguments) { + var typeArgumentsWithNewTypes = typeArguments.filter(function (typeArgument) { return !argumentTypeParameters.some(function (pair) { var _a; return checker.getTypeAtLocation(typeArgument) === ((_a = pair[1]) === null || _a === void 0 ? void 0 : _a.argumentType); }); }); + var targetSize = usedNames.size + typeArgumentsWithNewTypes.length; + for (var i = 0; usedNames.size < targetSize; i += 1) { + usedNames.add(createTypeParameterName(i)); + } + } + return ts.map(ts.arrayFrom(usedNames.values()), function (usedName) { var _a; return ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, usedName, (_a = constraintsByName.get(usedName)) === null || _a === void 0 ? void 0 : _a.constraint); }); + } + function createTypeParameterName(index) { + return 84 /* CharacterCodes.T */ + index <= 90 /* CharacterCodes.Z */ + ? String.fromCharCode(84 /* CharacterCodes.T */ + index) + : "T".concat(index); + } function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); if (typeNode && ts.isImportTypeNode(typeNode)) { @@ -157199,16 +159799,107 @@ var ts; return ts.getSynthesizedDeepClone(typeNode); } codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode; + function typeContainsTypeParameter(type) { + if (type.isUnionOrIntersection()) { + return type.types.some(typeContainsTypeParameter); + } + return type.flags & 262144 /* TypeFlags.TypeParameter */; + } + function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, tracker) { + // Types to be used as the types of the parameters in the new function + // E.g. from this source: + // added("", 0) + // The value will look like: + // [{ typeName: { text: "string" } }, { typeName: { text: "number" }] + // And in the output function will generate: + // function added(a: string, b: number) { ... } + var argumentTypeNodes = []; + // Names of type parameters provided as arguments to the call + // E.g. from this source: + // added(value); + // The value will look like: + // [ + // ["T", { argumentType: { typeName: { text: "T" } } } ], + // ["U", { argumentType: { typeName: { text: "U" } } } ], + // ] + // And in the output function will generate: + // function added() { ... } + var argumentTypeParameters = new ts.Map(); + for (var i = 0; i < instanceTypes.length; i += 1) { + var instanceType = instanceTypes[i]; + // If the instance type contains a deep reference to an existing type parameter, + // instead of copying the full union or intersection, create a new type parameter + // E.g. from this source: + // function existing(value: T | U & string) { + // added/*1*/(value); + // We don't want to output this: + // function added(value: T | U & string) { ... } + // We instead want to output: + // function added(value: T) { ... } + if (instanceType.isUnionOrIntersection() && instanceType.types.some(typeContainsTypeParameter)) { + var synthesizedTypeParameterName = createTypeParameterName(i); + argumentTypeNodes.push(ts.factory.createTypeReferenceNode(synthesizedTypeParameterName)); + argumentTypeParameters.set(synthesizedTypeParameterName, undefined); + continue; + } + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + var widenedInstanceType = checker.getBaseTypeOfLiteralType(instanceType); + var argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, tracker); + if (!argumentTypeNode) { + continue; + } + argumentTypeNodes.push(argumentTypeNode); + var argumentTypeParameter = getFirstTypeParameterName(instanceType); + // If the instance type is a type parameter with a constraint (other than an anonymous object), + // remember that constraint for when we create the new type parameter + // E.g. from this source: + // function existing(value: T) { + // added/*1*/(value); + // We don't want to output this: + // function added(value: T) { ... } + // We instead want to output: + // function added(value: T) { ... } + var instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) + ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, tracker) + : undefined; + if (argumentTypeParameter) { + argumentTypeParameters.set(argumentTypeParameter, { argumentType: instanceType, constraint: instanceTypeConstraint }); + } + } + return { argumentTypeNodes: argumentTypeNodes, argumentTypeParameters: ts.arrayFrom(argumentTypeParameters.entries()) }; + } + codefix.getArgumentTypesAndTypeParameters = getArgumentTypesAndTypeParameters; + function isAnonymousObjectConstraintType(type) { + return (type.flags & 524288 /* TypeFlags.Object */) && type.objectFlags === 16 /* ObjectFlags.Anonymous */; + } + function getFirstTypeParameterName(type) { + var _a; + if (type.flags & (1048576 /* TypeFlags.Union */ | 2097152 /* TypeFlags.Intersection */)) { + for (var _i = 0, _b = type.types; _i < _b.length; _i++) { + var subType = _b[_i]; + var subTypeName = getFirstTypeParameterName(subType); + if (subTypeName) { + return subTypeName; + } + } + } + return type.flags & 262144 /* TypeFlags.TypeParameter */ + ? (_a = type.getSymbol()) === null || _a === void 0 ? void 0 : _a.getName() + : undefined; + } function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; + var parameterNameCounts = new ts.Map(); for (var i = 0; i < argCount; i++) { + var parameterName = (names === null || names === void 0 ? void 0 : names[i]) || "arg".concat(i); + var parameterNameCount = parameterNameCounts.get(parameterName); + parameterNameCounts.set(parameterName, (parameterNameCount || 0) + 1); var newParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - /*name*/ names && names[i] || "arg".concat(i), + /*name*/ parameterName + (parameterNameCount || ""), /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, - /*type*/ inJs ? undefined : types && types[i] || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), + /*type*/ inJs ? undefined : (types === null || types === void 0 ? void 0 : types[i]) || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -157237,7 +159928,6 @@ var ts; var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var restParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, ts.factory.createArrayTypeNode(ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */)), /*initializer*/ undefined); @@ -157253,8 +159943,7 @@ var ts; } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { - return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers, + return ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } function createStubbedMethodBody(quotePreference) { @@ -157385,6 +160074,9 @@ var ts; accessorModifiers = ts.createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); fieldModifiers = ts.createModifiers(prepareModifierFlagsForField(modifierFlags)); } + if (ts.canHaveDecorators(declaration)) { + fieldModifiers = ts.concatenate(ts.getDecorators(declaration), fieldModifiers); + } } updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); @@ -157449,7 +160141,7 @@ var ts; error: ts.getLocaleSpecificMessage(ts.Diagnostics.Name_is_not_valid) }; } - if ((ts.getEffectiveModifierFlags(declaration) | meaning) !== meaning) { + if (((ts.getEffectiveModifierFlags(declaration) & 125951 /* ModifierFlags.Modifier */) | meaning) !== meaning) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_property_with_modifier) }; @@ -157472,17 +160164,14 @@ var ts; } codefix.getAccessorConvertiblePropertyAtPosition = getAccessorConvertiblePropertyAtPosition; function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { - return ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, accessorName, + return ts.factory.createGetAccessorDeclaration(modifiers, accessorName, /*parameters*/ undefined, // TODO: GH#18217 type, ts.factory.createBlock([ ts.factory.createReturnStatement(createAccessorAccessExpression(fieldName, isStatic, container)) ], /*multiLine*/ true)); } function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { - return ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, accessorName, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createSetAccessorDeclaration(modifiers, accessorName, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.factory.createIdentifier("value"), /*questionToken*/ undefined, type)], ts.factory.createBlock([ @@ -157490,7 +160179,7 @@ var ts; ], /*multiLine*/ true)); } function updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) { - var property = ts.factory.updatePropertyDeclaration(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); + var property = ts.factory.updatePropertyDeclaration(declaration, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); changeTracker.replaceNode(file, declaration, property); } function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { @@ -157505,7 +160194,7 @@ var ts; updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - changeTracker.replaceNode(file, declaration, ts.factory.updateParameterDeclaration(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + changeTracker.replaceNode(file, declaration, ts.factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } function insertAccessor(changeTracker, file, accessor, declaration, container) { @@ -157579,7 +160268,6 @@ var ts; if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, namespace.name, ts.factory.createExternalModuleReference(node.moduleSpecifier)))); } @@ -157716,7 +160404,7 @@ var ts; } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { ts.suppressLeadingAndTrailingTrivia(propertyDeclaration); - var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* SyntaxKind.ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* SyntaxKind.ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, info) { @@ -157746,7 +160434,7 @@ var ts; } function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { ts.suppressLeadingAndTrailingTrivia(propertyDeclaration); - var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { @@ -157812,8 +160500,8 @@ var ts; function doChange(changes, sourceFile, info) { var allowSyntheticDefaults = info.allowSyntheticDefaults, defaultImportName = info.defaultImportName, namedImports = info.namedImports, statement = info.statement, required = info.required; changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults - ? ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required)) - : ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); + ? ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required)) + : ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); } function getInfo(sourceFile, program, pos) { var parent = ts.getTokenAtPosition(sourceFile, pos).parent; @@ -157951,7 +160639,7 @@ var ts; return token.parent; } function doChange(changes, sourceFile, importType) { - var newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + var newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.assertions, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); changes.replaceNode(sourceFile, importType, newTypeNode); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -158068,7 +160756,7 @@ var ts; return { indexSignature: indexSignature, container: container }; } function createTypeAliasFromInterface(declaration, type) { - return ts.factory.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + return ts.factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); } function doChange(changes, sourceFile, _a) { var indexSignature = _a.indexSignature, container = _a.container; @@ -158184,9 +160872,8 @@ var ts; return; } var importClause = ts.Debug.checkDefined(importDeclaration.importClause); - changes.replaceNode(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); + changes.replaceNode(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); changes.insertNodeAfter(context.sourceFile, importDeclaration, ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ undefined, importClause.namedBindings), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -158408,14 +161095,14 @@ var ts; if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_export_statement) }; } - var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var checker = program.getTypeChecker(); + var exportingModuleSymbol = getExportingModuleSymbol(exportNode, checker); var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ModifierFlags.ExportDefault */ : 0 /* ModifierFlags.None */); var wasDefault = !!(flags & 512 /* ModifierFlags.Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* ModifierFlags.Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* InternalSymbolName.Default */)) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.This_file_already_has_a_default_export) }; } - var checker = program.getTypeChecker(); var noSymbolError = function (id) { return (ts.isIdentifier(id) && checker.getSymbolAtLocation(id)) ? undefined : { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_named_export) }; @@ -158467,7 +161154,7 @@ var ts; if (ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) { var exp = exportNode.expression; var spec = makeExportSpecifier(exp.text, exp.text); - changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); + changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); } else { changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 88 /* SyntaxKind.DefaultKeyword */), "Should find a default keyword in modifier list")); @@ -158507,6 +161194,8 @@ var ts; var checker = program.getTypeChecker(); var exportSymbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + if (exportName === ref) + return; var importingSourceFile = ref.getSourceFile(); if (wasDefault) { changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); @@ -158555,7 +161244,7 @@ var ts; } case 200 /* SyntaxKind.ImportType */: var importTypeNode = parent; - changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); + changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); break; default: ts.Debug.failBadSyntaxKind(parent); @@ -158599,6 +161288,17 @@ var ts; function makeExportSpecifier(propertyName, name) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, propertyName === name ? undefined : ts.factory.createIdentifier(propertyName), ts.factory.createIdentifier(name)); } + function getExportingModuleSymbol(node, checker) { + var parent = node.parent; + if (ts.isSourceFile(parent)) { + return parent.symbol; + } + var symbol = parent.parent.symbol; + if (symbol.valueDeclaration && ts.isExternalModuleAugmentation(symbol.valueDeclaration)) { + return checker.getMergedSymbol(symbol); + } + return symbol; + } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ @@ -158773,7 +161473,7 @@ var ts; // Imports that need to be kept as named imports in the refactored code, to avoid changing the semantics. // More specifically, those are named imports that appear in named exports in the original code, e.g. `a` in `import { a } from "m"; export { a }`. var neededNamedImports = new ts.Set(); - var _loop_17 = function (element) { + var _loop_15 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -158790,7 +161490,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_17(element); + _loop_15(element); } changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? ts.factory.createIdentifier(namespaceImportName) @@ -158811,7 +161511,7 @@ var ts; return externalModule !== exportEquals; } function updateImport(old, defaultImportName, elements) { - return ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); + return ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); @@ -159125,7 +161825,7 @@ var ts; break; } case 169 /* SyntaxKind.MethodDeclaration */: { - updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } case 174 /* SyntaxKind.CallSignature */: { @@ -159133,7 +161833,7 @@ var ts; break; } case 171 /* SyntaxKind.Constructor */: { - updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); + updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); break; } case 175 /* SyntaxKind.ConstructSignature */: { @@ -159141,7 +161841,7 @@ var ts; break; } case 256 /* SyntaxKind.FunctionDeclaration */: { - updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } default: return ts.Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); @@ -159161,7 +161861,6 @@ var ts; } return ts.factory.createNodeArray([ ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), "args", /*questionToken*/ undefined, ts.factory.createUnionTypeNode(ts.map(signatureDeclarations, convertSignatureParametersToTuple))) ]); @@ -159208,6 +161907,9 @@ var ts; if (!containingDecl) { return; } + if (ts.isFunctionLikeDeclaration(containingDecl) && containingDecl.body && ts.rangeContainsPosition(containingDecl.body, startPosition)) { + return; + } var checker = program.getTypeChecker(); var signatureSymbol = containingDecl.symbol; if (!signatureSymbol) { @@ -159228,7 +161930,7 @@ var ts; return; } var signatureDecls = decls; - if (ts.some(signatureDecls, function (d) { return !!d.typeParameters || ts.some(d.parameters, function (p) { return !!p.decorators || !!p.modifiers || !ts.isIdentifier(p.name); }); })) { + if (ts.some(signatureDecls, function (d) { return !!d.typeParameters || ts.some(d.parameters, function (p) { return !!p.modifiers || !ts.isIdentifier(p.name); }); })) { return; } var signatures = ts.mapDefined(signatureDecls, function (d) { return checker.getSignatureFromDeclaration(d); }); @@ -159558,11 +162260,11 @@ var ts; } } else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { - var declarations_5 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; + var declarations_6 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, declarations_4 = declarations_5; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + for (var _i = 0, declarations_5 = declarations_6; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; if (declaration.initializer) { numInitializers++; lastInitializer = declaration.initializer; @@ -159721,7 +162423,7 @@ var ts; var savedPermittedJumps = permittedJumps; switch (node.kind) { case 239 /* SyntaxKind.IfStatement */: - permittedJumps = 0 /* PermittedJumps.None */; + permittedJumps &= ~4 /* PermittedJumps.Return */; break; case 252 /* SyntaxKind.TryStatement */: // forbid all jumps inside try blocks @@ -160013,7 +162715,6 @@ var ts; typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NodeBuilderFlags.NoTruncation */); } var paramDecl = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ name, @@ -160053,22 +162754,19 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { modifiers.push(ts.factory.createModifier(131 /* SyntaxKind.AsyncKeyword */)); } - newFunction = ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, + newFunction = ts.factory.createMethodDeclaration(modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { if (callThis) { parameters.unshift(ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ "this", /*questionToken*/ undefined, checker.typeToTypeNode(checker.getTypeAtLocation(range.thisNode), scope, 1 /* NodeBuilderFlags.NoTruncation */), /*initializer*/ undefined)); } - newFunction = ts.factory.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + newFunction = ts.factory.createFunctionDeclaration(range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; @@ -160250,8 +162948,7 @@ var ts; modifiers.push(ts.factory.createModifier(124 /* SyntaxKind.StaticKeyword */)); } modifiers.push(ts.factory.createModifier(145 /* SyntaxKind.ReadonlyKeyword */)); - var newVariable = ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, localNameText, + var newVariable = ts.factory.createPropertyDeclaration(modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.factory.createPropertyAccessExpression(rangeFacts & RangeFacts.InStaticRegion ? ts.factory.createIdentifier(scope.name.getText()) // TODO: GH#18217 @@ -160346,7 +163043,7 @@ var ts; var paramType = checker.getTypeAtLocation(p); if (paramType === checker.getAnyType()) hasAny = true; - parameters.push(ts.factory.updateParameterDeclaration(p, p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NodeBuilderFlags.NoTruncation */), p.initializer)); + parameters.push(ts.factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NodeBuilderFlags.NoTruncation */), p.initializer)); } } // If a parameter was inferred as any we skip adding function parameters at all. @@ -160356,7 +163053,7 @@ var ts; return { variableType: variableType, initializer: initializer }; variableType = undefined; if (ts.isArrowFunction(initializer)) { - initializer = ts.factory.updateArrowFunction(initializer, node.modifiers, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.equalsGreaterThanToken, initializer.body); + initializer = ts.factory.updateArrowFunction(initializer, ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.equalsGreaterThanToken, initializer.body); } else { if (functionSignature && !!functionSignature.thisParameter) { @@ -160366,13 +163063,12 @@ var ts; if ((!firstParameter || (ts.isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this"))) { var thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); parameters.splice(0, 0, ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, checker.typeToTypeNode(thisType, scope, 1 /* NodeBuilderFlags.NoTruncation */))); } } - initializer = ts.factory.updateFunctionExpression(initializer, node.modifiers, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.body); + initializer = ts.factory.updateFunctionExpression(initializer, ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.body); } return { variableType: variableType, initializer: initializer }; } @@ -160688,7 +163384,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_18 = function (i) { + var _loop_16 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -160731,7 +163427,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_18(i); + _loop_16(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -161167,7 +163863,6 @@ var ts; function doTypeAliasChange(changes, file, name, info) { var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters; var newTypeNode = ts.factory.createTypeAliasDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters.map(function (id) { return ts.factory.updateTypeParameterDeclaration(id, id.modifiers, id.name, id.constraint, /* defaultType */ undefined); }), selection); changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true); changes.replaceNode(file, selection, ts.factory.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.factory.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.ExcludeWhitespace }); @@ -161176,7 +163871,6 @@ var ts; var _a; var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters, typeElements = info.typeElements; var newTypeNode = ts.factory.createInterfaceDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters, /* heritageClauses */ undefined, typeElements); ts.setTextRange(newTypeNode, (_a = typeElements[0]) === null || _a === void 0 ? void 0 : _a.parent); @@ -161340,7 +164034,7 @@ var ts; var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); var extension = ts.extensionFromPath(oldFile.fileName); - var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.oldFileImportsFromNewFile, usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); @@ -161434,10 +164128,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_19 = function (sourceFile) { + var _loop_17 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_20 = function (statement) { + var _loop_18 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -161459,12 +164153,12 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_20(statement); + _loop_18(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_19(sourceFile); + _loop_17(sourceFile); } } function getNamespaceLikeImport(node) { @@ -161507,10 +164201,10 @@ var ts; switch (node.kind) { case 266 /* SyntaxKind.ImportDeclaration */: return ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, + /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, /*assertClause*/ undefined); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); + return ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); case 254 /* SyntaxKind.VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: @@ -161704,8 +164398,8 @@ var ts; newModuleName = "".concat(moduleName, ".").concat(i); } } - function getNewModuleName(movedSymbols) { - return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + function getNewModuleName(importsFromNewFile, movedSymbols) { + return importsFromNewFile.forEachEntry(ts.symbolNameNoDefault) || movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; } function getUsageInfo(oldFile, toMove, checker) { var movedSymbols = new SymbolSet(); @@ -161798,7 +164492,7 @@ var ts; var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); return defaultImport || namedBindings - ? ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) + ? ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) : undefined; } case 265 /* SyntaxKind.ImportEqualsDeclaration */: @@ -161963,24 +164657,25 @@ var ts; return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); } function addEs6Export(d) { - var modifiers = ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], d.modifiers); + var modifiers = ts.canHaveModifiers(d) ? ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], ts.getModifiers(d)) : undefined; switch (d.kind) { case 256 /* SyntaxKind.FunctionDeclaration */: - return ts.factory.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + return ts.factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); case 257 /* SyntaxKind.ClassDeclaration */: - return ts.factory.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + var decorators = ts.canHaveDecorators(d) ? ts.getDecorators(d) : undefined; + return ts.factory.updateClassDeclaration(d, ts.concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); case 237 /* SyntaxKind.VariableStatement */: return ts.factory.updateVariableStatement(d, modifiers, d.declarationList); case 261 /* SyntaxKind.ModuleDeclaration */: - return ts.factory.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + return ts.factory.updateModuleDeclaration(d, modifiers, d.name, d.body); case 260 /* SyntaxKind.EnumDeclaration */: - return ts.factory.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + return ts.factory.updateEnumDeclaration(d, modifiers, d.name, d.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return ts.factory.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + return ts.factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); case 258 /* SyntaxKind.InterfaceDeclaration */: - return ts.factory.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + return ts.factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.isTypeOnly, d.name, d.moduleReference); + return ts.factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); case 238 /* SyntaxKind.ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: @@ -162477,7 +165172,7 @@ var ts; if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false; } - return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name); + return !parameterDeclaration.modifiers && ts.isIdentifier(parameterDeclaration.name); } function isValidVariableDeclaration(node) { return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113 @@ -162536,14 +165231,12 @@ var ts; objectInitializer = ts.factory.createObjectLiteralExpression(); } var objectParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, objectParameterName, /*questionToken*/ undefined, objectParameterType, objectInitializer); if (hasThisParameter(functionDeclaration.parameters)) { var thisParameter = functionDeclaration.parameters[0]; var newThisParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, thisParameter.type); @@ -162828,7 +165521,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText, rawHeadText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_21 = function (i) { + var _loop_19 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], rawSubsequentText = _c[2], stringIndexes = _c[3]; @@ -162857,7 +165550,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_21(i); + _loop_19(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -163064,7 +165757,7 @@ var ts; ts.suppressLeadingTrivia(statement); var modifiersFlags = (ts.getCombinedModifierFlags(variableDeclaration) & 1 /* ModifierFlags.Export */) | ts.getEffectiveModifierFlags(func); var modifiers = ts.factory.createModifiersFromModifierFlags(modifiersFlags); - var newNode = ts.factory.createFunctionDeclaration(func.decorators, ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + var newNode = ts.factory.createFunctionDeclaration(ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, statement, newNode); }); } @@ -163469,20 +166162,25 @@ var ts; return this.documentationComment; }; SymbolObject.prototype.getContextualDocumentationComment = function (context, checker) { - switch (context === null || context === void 0 ? void 0 : context.kind) { - case 172 /* SyntaxKind.GetAccessor */: + if (context) { + if (ts.isGetAccessor(context)) { if (!this.contextualGetAccessorDocumentationComment) { this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } - return this.contextualGetAccessorDocumentationComment; - case 173 /* SyntaxKind.SetAccessor */: + if (ts.length(this.contextualGetAccessorDocumentationComment)) { + return this.contextualGetAccessorDocumentationComment; + } + } + if (ts.isSetAccessor(context)) { if (!this.contextualSetAccessorDocumentationComment) { this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); } - return this.contextualSetAccessorDocumentationComment; - default: - return this.getDocumentationComment(checker); + if (ts.length(this.contextualSetAccessorDocumentationComment)) { + return this.contextualSetAccessorDocumentationComment; + } + } } + return this.getDocumentationComment(checker); }; SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { @@ -163491,20 +166189,25 @@ var ts; return this.tags; }; SymbolObject.prototype.getContextualJsDocTags = function (context, checker) { - switch (context === null || context === void 0 ? void 0 : context.kind) { - case 172 /* SyntaxKind.GetAccessor */: + if (context) { + if (ts.isGetAccessor(context)) { if (!this.contextualGetAccessorTags) { this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isGetAccessor), checker); } - return this.contextualGetAccessorTags; - case 173 /* SyntaxKind.SetAccessor */: + if (ts.length(this.contextualGetAccessorTags)) { + return this.contextualGetAccessorTags; + } + } + if (ts.isSetAccessor(context)) { if (!this.contextualSetAccessorTags) { this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isSetAccessor), checker); } - return this.contextualSetAccessorTags; - default: - return this.getJsDocTags(checker); + if (ts.length(this.contextualSetAccessorTags)) { + return this.contextualSetAccessorTags; + } + } } + return this.getJsDocTags(checker); }; return SymbolObject; }()); @@ -163685,7 +166388,7 @@ var ts; * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. */ function hasJSDocInheritDocTag(node) { - return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc"; }); } function getJsDocTagsOfDeclarations(declarations, checker) { if (!declarations) @@ -163693,7 +166396,7 @@ var ts; var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations, checker); if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) { var seenSymbols_1 = new ts.Set(); - var _loop_22 = function (declaration) { + var _loop_20 = function (declaration) { var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; if (!seenSymbols_1.has(symbol)) { @@ -163708,9 +166411,9 @@ var ts; tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); } }; - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - _loop_22(declaration); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + _loop_20(declaration); } } return tags; @@ -163721,7 +166424,7 @@ var ts; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { var seenSymbols_2 = new ts.Set(); - var _loop_23 = function (declaration) { + var _loop_21 = function (declaration) { var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { if (!seenSymbols_2.has(symbol)) { seenSymbols_2.add(symbol); @@ -163735,22 +166438,23 @@ var ts; if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); }; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - _loop_23(declaration); + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + _loop_21(declaration); } } return doc; } function findBaseOfDeclaration(checker, declaration, cb) { var _a; - if (ts.hasStaticModifier(declaration)) - return; var classOrInterfaceDeclaration = ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.kind) === 171 /* SyntaxKind.Constructor */ ? declaration.parent.parent : declaration.parent; if (!classOrInterfaceDeclaration) return; + var isStaticMember = ts.hasStaticModifier(declaration); return ts.firstDefined(ts.getAllSuperTypeNodes(classOrInterfaceDeclaration), function (superTypeNode) { - var symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name); + var baseType = checker.getTypeAtLocation(superTypeNode); + var type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType; + var symbol = checker.getPropertyOfType(type, declaration.symbol.name); return symbol ? cb(symbol) : undefined; }); } @@ -163993,70 +166697,6 @@ var ts; return ts.codefix.getSupportedErrorCodes(); } ts.getSupportedCodeFixes = getSupportedCodeFixes; - // Cache host information about script Should be refreshed - // at each language service public entry point, since we don't know when - // the set of scripts handled by the host changes. - var HostCache = /** @class */ (function () { - function HostCache(host, getCanonicalFileName) { - this.host = host; - // script id => script index - this.currentDirectory = host.getCurrentDirectory(); - this.fileNameToEntry = new ts.Map(); - // Initialize the list with the root file names - var rootFileNames = host.getScriptFileNames(); - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* tracing.Phase.Session */, "initializeHostCache", { count: rootFileNames.length }); - for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { - var fileName = rootFileNames_1[_i]; - this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); - } - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); - } - HostCache.prototype.createEntry = function (fileName, path) { - var entry; - var scriptSnapshot = this.host.getScriptSnapshot(fileName); - if (scriptSnapshot) { - entry = { - hostFileName: fileName, - version: this.host.getScriptVersion(fileName), - scriptSnapshot: scriptSnapshot, - scriptKind: ts.getScriptKind(fileName, this.host) - }; - } - else { - entry = fileName; - } - this.fileNameToEntry.set(path, entry); - return entry; - }; - HostCache.prototype.getEntryByPath = function (path) { - return this.fileNameToEntry.get(path); - }; - HostCache.prototype.getHostFileInformation = function (path) { - var entry = this.fileNameToEntry.get(path); - return !ts.isString(entry) ? entry : undefined; - }; - HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - var info = this.getEntryByPath(path) || this.createEntry(fileName, path); - return ts.isString(info) ? undefined : info; // TODO: GH#18217 - }; - HostCache.prototype.getRootFileNames = function () { - var names = []; - this.fileNameToEntry.forEach(function (entry) { - if (ts.isString(entry)) { - names.push(entry); - } - else { - names.push(entry.hostFileName); - } - }); - return names; - }; - HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getHostFileInformation(path); - return (file && file.scriptSnapshot); // TODO: GH#18217 - }; - return HostCache; - }()); var SyntaxTreeCache = /** @class */ (function () { function SyntaxTreeCache(host) { this.host = host; @@ -164318,32 +166958,16 @@ var ts; program = undefined; // TODO: GH#18217 lastTypesRootVersion = typeRootsVersion; } + // This array is retained by the program and will be used to determine if the program is up to date, + // so we need to make a copy in case the host mutates the underlying array - otherwise it would look + // like every program always has the host's current list of root files. + var rootFileNames = host.getScriptFileNames().slice(); // Get a fresh cache of the host information - var hostCache = new HostCache(host, getCanonicalFileName); - var rootFileNames = hostCache.getRootFileNames(); var newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; var hasChangedAutomaticTypeDirectiveNames = ts.maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); var projectReferences = (_b = host.getProjectReferences) === null || _b === void 0 ? void 0 : _b.call(host); var parsedCommandLines; - var parseConfigHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - fileExists: fileExists, - readFile: readFile, - readDirectory: readDirectory, - trace: ts.maybeBind(host, host.trace), - getCurrentDirectory: function () { return currentDirectory; }, - onUnRecoverableConfigFileDiagnostic: ts.noop, - }; - // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { - return; - } - // IMPORTANT - It is critical from this moment onward that we do not check - // cancellation tokens. We are about to mutate source files from a previous program - // instance. If we cancel midway through, we may end up in an inconsistent state where - // the program points to old source files that have been invalidated because of - // incremental parsing. // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -164355,8 +166979,8 @@ var ts; getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, - fileExists: fileExists, - readFile: readFile, + fileExists: function (fileName) { return host.fileExists(fileName); }, + readFile: function (fileName) { return host.readFile && host.readFile(fileName); }, getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache), realpath: ts.maybeBind(host, host.realpath), directoryExists: function (directoryName) { @@ -164365,19 +166989,56 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, - readDirectory: readDirectory, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, onReleaseParsedCommandLine: onReleaseParsedCommandLine, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, - trace: parseConfigHost.trace, + trace: ts.maybeBind(host, host.trace), resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), getModuleResolutionCache: ts.maybeBind(host, host.getModuleResolutionCache), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine: getParsedCommandLine, }; + var originalGetSourceFile = compilerHost.getSourceFile; + var getSourceFileWithCache = ts.changeCompilerHostLikeToUseCache(compilerHost, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args, false)); + }).getSourceFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; (_c = host.setCompilerHost) === null || _c === void 0 ? void 0 : _c.call(host, compilerHost); + var parseConfigHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, + readFile: function (fileName) { return compilerHost.readFile(fileName); }, + readDirectory: function () { + var _a; + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return (_a = compilerHost).readDirectory.apply(_a, args); + }, + trace: compilerHost.trace, + getCurrentDirectory: compilerHost.getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: ts.noop, + }; + // If the program is already up-to-date, we can reuse it + if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, function (fileName) { return compilerHost.fileExists(fileName); }, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + return; + } + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, @@ -164387,9 +167048,9 @@ var ts; projectReferences: projectReferences }; program = ts.createProgram(options); - // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. - // It needs to be cleared to allow all collected snapshots to be released - hostCache = undefined; + // 'getOrCreateSourceFile' depends on caching but should be used past this point. + // After this point, the cache needs to be cleared to allow all collected snapshots to be released + compilerHost = undefined; parsedCommandLines = undefined; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during @@ -164429,44 +167090,26 @@ var ts; onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); } } - function fileExists(fileName) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - return entry ? - !ts.isString(entry) : - (!!host.fileExists && host.fileExists(fileName)); - } - function readFile(fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - if (entry) { - return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); - } - return host.readFile && host.readFile(fileName); - } - function readDirectory(path, extensions, exclude, include, depth) { - ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(path, extensions, exclude, include, depth); - } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } - function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { - return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); + function getOrCreateSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersionOrOptions, onError, shouldCreateNewSourceFile); } - function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { - ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); + function getOrCreateSourceFileByPath(fileName, path, languageVersionOrOptions, _onError, shouldCreateNewSourceFile) { + ts.Debug.assert(compilerHost, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. - var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); - if (!hostFileInformation) { + var scriptSnapshot = host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { return undefined; } + var scriptKind = ts.getScriptKind(fileName, host); + var scriptVersion = host.getScriptVersion(fileName); // Check if the language version has changed since we last created a program; if they are the same, // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. @@ -164498,18 +167141,18 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { - return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } else { // Release old source file and fall through to aquire new file with new script kind - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } } // We didn't already have the file. Fall through and acquire it from the registry. } // Could not find this file in the old program, create a new SourceFile for it. - return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } } // TODO: GH#18217 frequently asserted as defined @@ -164525,6 +167168,61 @@ var ts; var _a; return (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); } + function updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans) { + var checker = program.getTypeChecker(); + var symbol = getSymbolForProgram(); + if (!symbol) + return false; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + var refNode = getNodeForSpan(ref); + ts.Debug.assertIsDefined(refNode); + if (knownSymbolSpans.has(ref) || ts.FindAllReferences.isDeclarationOfSymbol(refNode, symbol)) { + knownSymbolSpans.add(ref); + ref.isDefinition = true; + var mappedSpan = ts.getMappedDocumentSpan(ref, sourceMapper, ts.maybeBind(host, host.fileExists)); + if (mappedSpan) { + knownSymbolSpans.add(mappedSpan); + } + } + else { + ref.isDefinition = false; + } + } + } + return true; + function getSymbolForProgram() { + for (var _i = 0, referencedSymbols_2 = referencedSymbols; _i < referencedSymbols_2.length; _i++) { + var referencedSymbol = referencedSymbols_2[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + if (knownSymbolSpans.has(ref)) { + var refNode = getNodeForSpan(ref); + ts.Debug.assertIsDefined(refNode); + return checker.getSymbolAtLocation(refNode); + } + var mappedSpan = ts.getMappedDocumentSpan(ref, sourceMapper, ts.maybeBind(host, host.fileExists)); + if (mappedSpan && knownSymbolSpans.has(mappedSpan)) { + var refNode = getNodeForSpan(mappedSpan); + if (refNode) { + return checker.getSymbolAtLocation(refNode); + } + } + } + } + return undefined; + } + function getNodeForSpan(docSpan) { + var sourceFile = program.getSourceFile(docSpan.fileName); + if (!sourceFile) + return undefined; + var rawNode = ts.getTouchingPropertyName(sourceFile, docSpan.textSpan.start); + var adjustedNode = ts.FindAllReferences.Core.getAdjustedNode(rawNode, { use: 1 /* FindAllReferences.FindReferencesUse.References */ }); + return adjustedNode; + } + } function cleanupSemanticCache() { program = undefined; // TODO: GH#18217 } @@ -164533,7 +167231,7 @@ var ts; // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); ts.forEach(program.getSourceFiles(), function (f) { - return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind, f.impliedNodeFormat); }); program = undefined; // TODO: GH#18217 } @@ -165321,9 +168019,9 @@ var ts; return ts.stringContains(path, "/node_modules/"); } } - function getRenameInfo(fileName, position, options) { + function getRenameInfo(fileName, position, preferences) { synchronizeHostData(); - return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, preferences || {}); } function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason, kind) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; @@ -165450,7 +168148,9 @@ var ts; getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getProgram: getProgram, + getCurrentProgram: function () { return program; }, getAutoImportProvider: getAutoImportProvider, + updateIsDefinitionOfReferencedSymbols: updateIsDefinitionOfReferencedSymbols, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, toLineColumnOffset: toLineColumnOffset, @@ -165602,7 +168302,7 @@ var ts; function getDefaultLibFilePath(options) { // Check __dirname is defined and that we are on a node.js system. if (typeof __dirname !== "undefined") { - return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); + return ts.combinePaths(__dirname, ts.getDefaultLibFileName(options)); } throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); } @@ -165644,8 +168344,9 @@ var ts; // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - var start = startNode.decorators ? - ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + var lastDecorator = ts.canHaveDecorators(startNode) ? ts.findLast(startNode.modifiers, ts.isDecorator) : undefined; + var start = lastDecorator ? + ts.skipTrivia(sourceFile.text, lastDecorator.end) : startNode.getStart(sourceFile); return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } @@ -165658,8 +168359,20 @@ var ts; } return spanInNode(otherwiseOnNode); } - function spanInNodeArray(nodeArray) { - return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + function spanInNodeArray(nodeArray, node, match) { + if (nodeArray) { + var index = nodeArray.indexOf(node); + if (index >= 0) { + var start = index; + var end = index + 1; + while (start > 0 && match(nodeArray[start - 1])) + start--; + while (end < nodeArray.length && match(nodeArray[end])) + end++; + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray[start].pos), nodeArray[end - 1].end); + } + } + return textSpan(node); } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); @@ -165772,7 +168485,7 @@ var ts; // span in statement return spanInNode(node.statement); case 165 /* SyntaxKind.Decorator */: - return spanInNodeArray(parent.decorators); + return spanInNodeArray(parent.modifiers, node, ts.isDecorator); case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: return spanInBindingPattern(node); @@ -165935,7 +168648,7 @@ var ts; } // Breakpoint is possible in variableDeclaration only if there is initialization // or its declaration from 'for of' - if (variableDeclaration.initializer || + if ((ts.hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer) || ts.hasSyntacticModifier(variableDeclaration, 1 /* ModifierFlags.Export */) || parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); @@ -166675,9 +169388,9 @@ var ts; var _this = this; return this.forwardJSONCall("getImplementationAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, options); }); + return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, preferences); }); }; LanguageServiceShimObject.prototype.getSmartSelectionRange = function (fileName, position) { var _this = this; @@ -166902,7 +169615,8 @@ var ts; } return { resolvedFileName: resolvedFileName, - failedLookupLocations: result.failedLookupLocations + failedLookupLocations: result.failedLookupLocations, + affectingLocations: result.affectingLocations, }; }); }; @@ -166981,7 +169695,7 @@ var ts; if (_this.safeList === undefined) { _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); } - return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry); + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry, ts.emptyOptions); }); }; return CoreServicesShimObject; @@ -167250,7 +169964,7 @@ var ts; * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ - function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry, compilerOptions) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } @@ -167268,12 +169982,14 @@ var ts; addInferredTypings(typeAcquisition.include, "Explicitly included types"); var exclude = typeAcquisition.exclude || []; // Directories to search for package.json, bower.json and other typing information - var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); - possibleSearchDirs.add(projectRootPath); - possibleSearchDirs.forEach(function (searchDir) { - getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); - getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); - }); + if (!compilerOptions.types) { + var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); + possibleSearchDirs.add(projectRootPath); + possibleSearchDirs.forEach(function (searchDir) { + getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); + getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); + }); + } if (!typeAcquisition.disableFilenameBasedTypeAcquisition) { getTypingNamesFromSourceFileNames(fileNames); } @@ -167731,16 +170447,6 @@ var ts; server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - ts.WatchType.ClosedScriptInfo = "Closed Script info"; - ts.WatchType.ConfigFileForInferredRoot = "Config file for the inferred project root"; - ts.WatchType.NodeModules = "node_modules for closed script infos and package.jsons affecting module specifier cache"; - ts.WatchType.MissingSourceMapFile = "Missing source map file"; - ts.WatchType.NoopConfigFileForInferredRoot = "Noop Config file for the inferred project root"; - ts.WatchType.MissingGeneratedFile = "Missing generated file"; -})(ts || (ts = {})); /* eslint-disable @typescript-eslint/no-unnecessary-qualifier */ /** * Declaration module describing the TypeScript Server protocol @@ -168901,6 +171607,38 @@ var ts; } return result.module; }; + /*@internal*/ + Project.importServicePluginAsync = function (moduleName, initialDir, host, log, logErrors) { + return __awaiter(this, void 0, void 0, function () { + var resolvedPath, result, e_1, err; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + ts.Debug.assertIsDefined(host.importServicePlugin); + resolvedPath = ts.combinePaths(initialDir, "node_modules"); + log("Dynamically importing ".concat(moduleName, " from ").concat(initialDir, " (resolved to ").concat(resolvedPath, ")")); + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, host.importServicePlugin(resolvedPath, moduleName)]; + case 2: + result = _a.sent(); + return [3 /*break*/, 4]; + case 3: + e_1 = _a.sent(); + result = { module: undefined, error: e_1 }; + return [3 /*break*/, 4]; + case 4: + if (result.error) { + err = result.error.stack || result.error.message || JSON.stringify(result.error); + (logErrors || log)("Failed to dynamically import module '".concat(moduleName, "' from ").concat(resolvedPath, ": ").concat(err)); + return [2 /*return*/, undefined]; + } + return [2 /*return*/, result.module]; + } + }); + }); + }; Project.prototype.isKnownTypesPackageName = function (name) { return this.typingsCache.isKnownTypesPackageName(name); }; @@ -169046,6 +171784,10 @@ var ts; return this.projectService.watchFactory.watchDirectory(directory, cb, flags, this.projectService.getWatchOptions(this), ts.WatchType.FailedLookupLocations, this); }; /*@internal*/ + Project.prototype.watchAffectingFileLocation = function (file, cb) { + return this.projectService.watchFactory.watchFile(file, cb, ts.PollingInterval.High, this.projectService.getWatchOptions(this), ts.WatchType.AffectingFileLocation, this); + }; + /*@internal*/ Project.prototype.clearInvalidateResolutionOfFailedLookupTimer = function () { return this.projectService.throttledOperations.cancel("".concat(this.getProjectName(), "FailedLookupInvalidation")); }; @@ -169156,7 +171898,7 @@ var ts; } server.updateProjectIfDirty(this); this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState, /*disableUseFileVersionAsSignature*/ true); - return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, ts.maybeBind(this.projectService.host, this.projectService.host.createHash)), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, ts.maybeBind(this.projectService.host, this.projectService.host.createHash), this.getCanonicalFileName), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; /** * Returns true if emit was conducted @@ -169580,7 +172322,7 @@ var ts; }; Project.prototype.updateGraphWorker = function () { var _this = this; - var oldProgram = this.program; + var oldProgram = this.languageService.getCurrentProgram(); ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); this.writeLog("Starting updateGraphWorker: Project: ".concat(this.getProjectName())); var start = ts.timestamp(); @@ -169589,7 +172331,7 @@ var ts; this.program = this.languageService.getProgram(); // TODO: GH#18217 this.dirty = false; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* tracing.Phase.Session */, "finishCachingPerDirectoryResolution"); - this.resolutionCache.finishCachingPerDirectoryResolution(); + this.resolutionCache.finishCachingPerDirectoryResolution(this.program, oldProgram); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); ts.Debug.assert(oldProgram === undefined || this.program !== undefined); // bump up the version if @@ -169957,7 +172699,7 @@ var ts; }; Project.prototype.enableGlobalPlugins = function (options, pluginConfigOverrides) { var host = this.projectService.host; - if (!host.require) { + if (!host.require && !host.importServicePlugin) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } @@ -169986,21 +172728,66 @@ var ts; } } }; - Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { + /** + * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin synchronously using 'require'. + */ + /*@internal*/ + Project.prototype.beginEnablePluginSync = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { var _this = this; - this.projectService.logger.info("Enabling plugin ".concat(pluginConfigEntry.name, " from candidate paths: ").concat(searchPaths.join(","))); - if (!pluginConfigEntry.name || ts.parsePackageName(pluginConfigEntry.name).rest) { - this.projectService.logger.info("Skipped loading plugin ".concat(pluginConfigEntry.name || JSON.stringify(pluginConfigEntry), " because only package name is allowed plugin name")); - return; - } - var log = function (message) { return _this.projectService.logger.info(message); }; + ts.Debug.assertIsDefined(this.projectService.host.require); var errorLogs; + var log = function (message) { return _this.projectService.logger.info(message); }; var logError = function (message) { - (errorLogs || (errorLogs = [])).push(message); + (errorLogs !== null && errorLogs !== void 0 ? errorLogs : (errorLogs = [])).push(message); }; var resolvedModule = ts.firstDefined(searchPaths, function (searchPath) { return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log, logError); }); + return { pluginConfigEntry: pluginConfigEntry, pluginConfigOverrides: pluginConfigOverrides, resolvedModule: resolvedModule, errorLogs: errorLogs }; + }; + /** + * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin asynchronously using dynamic `import`. + */ + /*@internal*/ + Project.prototype.beginEnablePluginAsync = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { + return __awaiter(this, void 0, void 0, function () { + var errorLogs, log, logError, resolvedModule, _i, searchPaths_1, searchPath; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + ts.Debug.assertIsDefined(this.projectService.host.importServicePlugin); + log = function (message) { return _this.projectService.logger.info(message); }; + logError = function (message) { + (errorLogs !== null && errorLogs !== void 0 ? errorLogs : (errorLogs = [])).push(message); + }; + _i = 0, searchPaths_1 = searchPaths; + _a.label = 1; + case 1: + if (!(_i < searchPaths_1.length)) return [3 /*break*/, 4]; + searchPath = searchPaths_1[_i]; + return [4 /*yield*/, Project.importServicePluginAsync(pluginConfigEntry.name, searchPath, this.projectService.host, log, logError)]; + case 2: + resolvedModule = (_a.sent()); + if (resolvedModule !== undefined) { + return [3 /*break*/, 4]; + } + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/, { pluginConfigEntry: pluginConfigEntry, pluginConfigOverrides: pluginConfigOverrides, resolvedModule: resolvedModule, errorLogs: errorLogs }]; + } + }); + }); + }; + /** + * Performs the remaining steps of enabling a plugin after its module has been instantiated. + */ + /*@internal*/ + Project.prototype.endEnablePlugin = function (_a) { + var _this = this; + var pluginConfigEntry = _a.pluginConfigEntry, pluginConfigOverrides = _a.pluginConfigOverrides, resolvedModule = _a.resolvedModule, errorLogs = _a.errorLogs; if (resolvedModule) { var configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name); if (configurationOverride) { @@ -170012,10 +172799,13 @@ var ts; this.enableProxy(resolvedModule, pluginConfigEntry); } else { - ts.forEach(errorLogs, log); + ts.forEach(errorLogs, function (message) { return _this.projectService.logger.info(message); }); this.projectService.logger.info("Couldn't find ".concat(pluginConfigEntry.name)); } }; + Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { + this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths, pluginConfigOverrides); + }; Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) { try { if (typeof pluginModuleFactory !== "function") { @@ -170667,7 +173457,7 @@ var ts; /*@internal*/ ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) { var host = this.projectService.host; - if (!host.require) { + if (!host.require && !host.importServicePlugin) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } @@ -170686,7 +173476,7 @@ var ts; this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); } } - this.enableGlobalPlugins(options, pluginConfigOverrides); + return this.enableGlobalPlugins(options, pluginConfigOverrides); }; /** * Get the errors that dont have any file name associated @@ -171999,7 +174789,7 @@ var ts; // created when any of the script infos are added as root of inferred project if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { // If we cannot watch config file existence without configured project, close the configured file watcher - if (!ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath))) { + if (!ts.canWatchDirectoryOrFile(ts.getDirectoryPath(canonicalConfigFilePath))) { configFileExistenceInfo.watcher.close(); configFileExistenceInfo.watcher = noopConfigFileWatcher; } @@ -172079,7 +174869,7 @@ var ts; // Set this file as the root of inferred project (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = new ts.Map())).set(info.path, true); // If there is no configured project for this config file, add the file watcher - configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath)) ? + configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = ts.canWatchDirectoryOrFile(ts.getDirectoryPath(canonicalConfigFilePath)) ? _this.watchFactory.watchFile(configFileName, function (_filename, eventKind) { return _this.onConfigFileChanged(canonicalConfigFilePath, eventKind); }, ts.PollingInterval.High, _this.hostConfiguration.watchOptions, ts.WatchType.ConfigFileForInferredRoot) : noopConfigFileWatcher); }); @@ -174108,6 +176898,147 @@ var ts; } return false; }; + /*@internal*/ + ProjectService.prototype.requestEnablePlugin = function (project, pluginConfigEntry, searchPaths, pluginConfigOverrides) { + var _a; + if (!this.host.importServicePlugin && !this.host.require) { + this.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + this.logger.info("Enabling plugin ".concat(pluginConfigEntry.name, " from candidate paths: ").concat(searchPaths.join(","))); + if (!pluginConfigEntry.name || ts.parsePackageName(pluginConfigEntry.name).rest) { + this.logger.info("Skipped loading plugin ".concat(pluginConfigEntry.name || JSON.stringify(pluginConfigEntry), " because only package name is allowed plugin name")); + return; + } + // If the host supports dynamic import, begin enabling the plugin asynchronously. + if (this.host.importServicePlugin) { + var importPromise = project.beginEnablePluginAsync(pluginConfigEntry, searchPaths, pluginConfigOverrides); + (_a = this.pendingPluginEnablements) !== null && _a !== void 0 ? _a : (this.pendingPluginEnablements = new ts.Map()); + var promises = this.pendingPluginEnablements.get(project); + if (!promises) + this.pendingPluginEnablements.set(project, promises = []); + promises.push(importPromise); + return; + } + // Otherwise, load the plugin using `require` + project.endEnablePlugin(project.beginEnablePluginSync(pluginConfigEntry, searchPaths, pluginConfigOverrides)); + }; + /* @internal */ + ProjectService.prototype.hasNewPluginEnablementRequests = function () { + return !!this.pendingPluginEnablements; + }; + /* @internal */ + ProjectService.prototype.hasPendingPluginEnablements = function () { + return !!this.currentPluginEnablementPromise; + }; + /** + * Waits for any ongoing plugin enablement requests to complete. + */ + /* @internal */ + ProjectService.prototype.waitForPendingPlugins = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!this.currentPluginEnablementPromise) return [3 /*break*/, 2]; + return [4 /*yield*/, this.currentPluginEnablementPromise]; + case 1: + _a.sent(); + return [3 /*break*/, 0]; + case 2: return [2 /*return*/]; + } + }); + }); + }; + /** + * Starts enabling any requested plugins without waiting for the result. + */ + /* @internal */ + ProjectService.prototype.enableRequestedPlugins = function () { + if (this.pendingPluginEnablements) { + void this.enableRequestedPluginsAsync(); + } + }; + ProjectService.prototype.enableRequestedPluginsAsync = function () { + return __awaiter(this, void 0, void 0, function () { + var entries; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!this.currentPluginEnablementPromise) return [3 /*break*/, 2]; + // If we're already enabling plugins, wait for any existing operations to complete + return [4 /*yield*/, this.waitForPendingPlugins()]; + case 1: + // If we're already enabling plugins, wait for any existing operations to complete + _a.sent(); + _a.label = 2; + case 2: + // Skip if there are no new plugin enablement requests + if (!this.pendingPluginEnablements) { + return [2 /*return*/]; + } + entries = ts.arrayFrom(this.pendingPluginEnablements.entries()); + this.pendingPluginEnablements = undefined; + // Start processing the requests, keeping track of the promise for the operation so that + // project consumers can potentially wait for the plugins to load. + this.currentPluginEnablementPromise = this.enableRequestedPluginsWorker(entries); + return [4 /*yield*/, this.currentPluginEnablementPromise]; + case 3: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }; + ProjectService.prototype.enableRequestedPluginsWorker = function (pendingPlugins) { + return __awaiter(this, void 0, void 0, function () { + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + // This should only be called from `enableRequestedPluginsAsync`, which ensures this precondition is met. + ts.Debug.assert(this.currentPluginEnablementPromise === undefined); + // Process all pending plugins, partitioned by project. This way a project with few plugins doesn't need to wait + // on a project with many plugins. + return [4 /*yield*/, Promise.all(ts.map(pendingPlugins, function (_a) { + var project = _a[0], promises = _a[1]; + return _this.enableRequestedPluginsForProjectAsync(project, promises); + }))]; + case 1: + // Process all pending plugins, partitioned by project. This way a project with few plugins doesn't need to wait + // on a project with many plugins. + _a.sent(); + // Clear the pending operation and notify the client that projects have been updated. + this.currentPluginEnablementPromise = undefined; + this.sendProjectsUpdatedInBackgroundEvent(); + return [2 /*return*/]; + } + }); + }); + }; + ProjectService.prototype.enableRequestedPluginsForProjectAsync = function (project, promises) { + return __awaiter(this, void 0, void 0, function () { + var results, _i, results_1, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.all(promises)]; + case 1: + results = _a.sent(); + if (project.isClosed()) { + // project is not alive, so don't enable plugins. + return [2 /*return*/]; + } + for (_i = 0, results_1 = results; _i < results_1.length; _i++) { + result = results_1[_i]; + project.endEnablePlugin(result); + } + // Plugins may have modified external files, so mark the project as dirty. + this.delayUpdateProjectGraph(project); + return [2 /*return*/]; + } + }); + }); + }; ProjectService.prototype.configurePlugin = function (args) { // For any projects that already have the plugin loaded, configure the plugin this.forEachEnabledProject(function (project) { return project.onPluginConfigurationChanged(args.pluginName, args.configuration); }); @@ -174601,66 +177532,145 @@ var ts; return textSpan.start + 100003 * textSpan.length; }, ts.documentSpansEqual); } - function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments, _a) { + function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, _a) { var providePrefixAndSuffixTextForRename = _a.providePrefixAndSuffixTextForRename; - var outputs = []; + var perProjectResults = getPerProjectReferences(projects, defaultProject, initialLocation, + /*isForRename*/ true, function (project, position) { return project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, providePrefixAndSuffixTextForRename); }, function (renameLocation, cb) { return cb(documentSpanLocation(renameLocation)); }); + // No filtering or dedup'ing is required if there's exactly one project + if (ts.isArray(perProjectResults)) { + return perProjectResults; + } + var results = []; var seen = createDocumentSpanSet(); - combineProjectOutputWorker(projects, defaultProject, initialLocation, - /*isForRename*/ true, function (project, location, tryAddToTodo) { - var projectOutputs = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, providePrefixAndSuffixTextForRename); - if (projectOutputs) { - for (var _i = 0, projectOutputs_1 = projectOutputs; _i < projectOutputs_1.length; _i++) { - var output = projectOutputs_1[_i]; - if (!seen.has(output) && !tryAddToTodo(project, documentSpanLocation(output))) { - seen.add(output); - outputs.push(output); - } + perProjectResults.forEach(function (projectResults, project) { + for (var _i = 0, projectResults_1 = projectResults; _i < projectResults_1.length; _i++) { + var result = projectResults_1[_i]; + // If there's a mapped location, it'll appear in the results for another project + if (!seen.has(result) && !getMappedLocationForProject(documentSpanLocation(result), project)) { + results.push(result); + seen.add(result); } } }); - return outputs; + return results; } function getDefinitionLocation(defaultProject, initialLocation, isForRename) { - var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos, /*searchOtherFilesOnly*/ false, isForRename); + var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos, /*searchOtherFilesOnly*/ false, /*stopAtAlias*/ isForRename); var info = infos && ts.firstOrUndefined(infos); + // Note that the value of `isLocal` may depend on whether or not the checker has run on the containing file + // (implying that FAR cascading behavior may depend on request order) return info && !info.isLocal ? { fileName: info.fileName, pos: info.textSpan.start } : undefined; } - function combineProjectOutputForReferences(projects, defaultProject, initialLocation, logger) { - var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, - /*isForRename*/ false, function (project, location, getMappedLocation) { - var _a, _b; - logger.info("Finding references to ".concat(location.fileName, " position ").concat(location.pos, " in project ").concat(project.getProjectName())); - var projectOutputs = project.getLanguageService().findReferences(location.fileName, location.pos); - if (projectOutputs) { - var clearIsDefinition = ((_b = (_a = projectOutputs[0]) === null || _a === void 0 ? void 0 : _a.references[0]) === null || _b === void 0 ? void 0 : _b.isDefinition) === undefined; - var _loop_9 = function (referencedSymbol) { - var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(referencedSymbol.definition)); - var definition = mappedDefinitionFile === undefined ? - referencedSymbol.definition : __assign(__assign({}, referencedSymbol.definition), { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, referencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName, contextSpan: getMappedContextSpan(referencedSymbol.definition, project) }); - var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); - if (!symbolToAddTo) { - symbolToAddTo = { definition: definition, references: [] }; - outputs.push(symbolToAddTo); - } - for (var _c = 0, _d = referencedSymbol.references; _c < _d.length; _c++) { - var ref = _d[_c]; - // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. - if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { - if (clearIsDefinition) { - delete ref.isDefinition; - } - symbolToAddTo.references.push(ref); - } + function getReferencesWorker(projects, defaultProject, initialLocation, logger) { + var _a, _b; + var perProjectResults = getPerProjectReferences(projects, defaultProject, initialLocation, + /*isForRename*/ false, function (project, position) { + logger.info("Finding references to ".concat(position.fileName, " position ").concat(position.pos, " in project ").concat(project.getProjectName())); + return project.getLanguageService().findReferences(position.fileName, position.pos); + }, function (referencedSymbol, cb) { + cb(documentSpanLocation(referencedSymbol.definition)); + for (var _i = 0, _a = referencedSymbol.references; _i < _a.length; _i++) { + var ref = _a[_i]; + cb(documentSpanLocation(ref)); + } + }); + // No re-mapping or isDefinition updatses are required if there's exactly one project + if (ts.isArray(perProjectResults)) { + return perProjectResults; + } + // `isDefinition` is only (definitely) correct in `defaultProject` because we might + // have started the other project searches from related symbols. Propagate the + // correct results to all other projects. + var defaultProjectResults = perProjectResults.get(defaultProject); + if (((_b = (_a = defaultProjectResults === null || defaultProjectResults === void 0 ? void 0 : defaultProjectResults[0]) === null || _a === void 0 ? void 0 : _a.references[0]) === null || _b === void 0 ? void 0 : _b.isDefinition) === undefined) { + // Clear all isDefinition properties + perProjectResults.forEach(function (projectResults) { + for (var _i = 0, projectResults_2 = projectResults; _i < projectResults_2.length; _i++) { + var referencedSymbol = projectResults_2[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + delete ref.isDefinition; + } + } + }); + } + else { + // Correct isDefinition properties from projects other than defaultProject + var knownSymbolSpans_1 = createDocumentSpanSet(); + for (var _i = 0, defaultProjectResults_1 = defaultProjectResults; _i < defaultProjectResults_1.length; _i++) { + var referencedSymbol = defaultProjectResults_1[_i]; + for (var _c = 0, _d = referencedSymbol.references; _c < _d.length; _c++) { + var ref = _d[_c]; + if (ref.isDefinition) { + knownSymbolSpans_1.add(ref); + // One is enough - updateIsDefinitionOfReferencedSymbols will fill out the set based on symbols + break; + } + } + } + var updatedProjects_1 = new ts.Set(); + var _loop_9 = function () { + var progress = false; + perProjectResults.forEach(function (referencedSymbols, project) { + if (updatedProjects_1.has(project)) + return; + var updated = project.getLanguageService().updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans_1); + if (updated) { + updatedProjects_1.add(project); + progress = true; + } + }); + if (!progress) + return "break"; + }; + while (true) { + var state_2 = _loop_9(); + if (state_2 === "break") + break; + } + perProjectResults.forEach(function (referencedSymbols, project) { + if (updatedProjects_1.has(project)) + return; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + ref.isDefinition = false; + } + } + }); + } + // We need to de-duplicate and aggregate the results by choosing an authoritative version + // of each definition and merging references from all the projects where they appear. + var results = []; + var seenRefs = createDocumentSpanSet(); // It doesn't make sense to have a reference in two definition lists, so we de-dup globally + // TODO: We might end up with a more logical allocation of refs to defs if we pre-sorted the defs by descending ref-count. + // Otherwise, it just ends up attached to the first corresponding def we happen to process. The others may or may not be + // dropped later when we check for defs with ref-count 0. + perProjectResults.forEach(function (projectResults, project) { + var _loop_10 = function (referencedSymbol) { + var mappedDefinitionFile = getMappedLocationForProject(documentSpanLocation(referencedSymbol.definition), project); + var definition = mappedDefinitionFile === undefined ? + referencedSymbol.definition : __assign(__assign({}, referencedSymbol.definition), { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, referencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName, contextSpan: getMappedContextSpanForProject(referencedSymbol.definition, project) }); + var symbolToAddTo = ts.find(results, function (o) { return ts.documentSpansEqual(o.definition, definition); }); + if (!symbolToAddTo) { + symbolToAddTo = { definition: definition, references: [] }; + results.push(symbolToAddTo); + } + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + if (!seenRefs.has(ref) && !getMappedLocationForProject(documentSpanLocation(ref), project)) { + seenRefs.add(ref); + symbolToAddTo.references.push(ref); } - }; - for (var _i = 0, projectOutputs_2 = projectOutputs; _i < projectOutputs_2.length; _i++) { - var referencedSymbol = projectOutputs_2[_i]; - _loop_9(referencedSymbol); } + }; + for (var _i = 0, projectResults_3 = projectResults; _i < projectResults_3.length; _i++) { + var referencedSymbol = projectResults_3[_i]; + _loop_10(referencedSymbol); } }); - return outputs.filter(function (o) { return o.references.length !== 0; }); + return results.filter(function (o) { return o.references.length !== 0; }); } function forEachProjectInProjects(projects, path, cb) { for (var _i = 0, _a = ts.isArray(projects) ? projects : projects.projects; _i < _a.length; _i++) { @@ -174676,40 +177686,114 @@ var ts; }); } } - function combineProjectOutputWorker(projects, defaultProject, initialLocation, isForRename, cb) { - var projectService = defaultProject.projectService; - var toDo; - var seenProjects = new ts.Set(); - forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) { - // TLocation should be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. - var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined); - toDo = callbackProjectAndLocation(project, location, projectService, toDo, seenProjects, cb); + /** + * @param projects Projects initially known to contain {@link initialLocation} + * @param defaultProject The default project containing {@link initialLocation} + * @param initialLocation Where the search operation was triggered + * @param getResultsForPosition This is where you plug in `findReferences`, `renameLocation`, etc + * @param forPositionInResult Given an item returned by {@link getResultsForPosition} enumerate the positions referred to by that result + * @returns In the common case where there's only one project, returns an array of results from {@link getResultsForPosition}. + * If multiple projects were searched - even if they didn't return results - the result will be a map from project to per-project results. + */ + function getPerProjectReferences(projects, defaultProject, initialLocation, isForRename, getResultsForPosition, forPositionInResult) { + // If `getResultsForPosition` returns results for a project, they go in here + var resultsMap = new ts.Map(); + var queue = ts.createQueue(); + // In order to get accurate isDefinition values for `defaultProject`, + // we need to ensure that it is searched from `initialLocation`. + // The easiest way to do this is to search it first. + queue.enqueue({ project: defaultProject, location: initialLocation }); + // This will queue `defaultProject` a second time, but it will be dropped + // as a dup when it is dequeued. + forEachProjectInProjects(projects, initialLocation.fileName, function (project, path) { + var location = { fileName: path, pos: initialLocation.pos }; + queue.enqueue({ project: project, location: location }); }); - // After initial references are collected, go over every other project and see if it has a reference for the symbol definition. - if (initialLocation) { - var defaultDefinition_1 = getDefinitionLocation(defaultProject, initialLocation, isForRename); - if (defaultDefinition_1) { - var getGeneratedDefinition_1 = ts.memoize(function () { return defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition_1.fileName) ? - defaultDefinition_1 : - defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition_1); }); - var getSourceDefinition_1 = ts.memoize(function () { return defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition_1.fileName) ? - defaultDefinition_1 : - defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition_1); }); - projectService.loadAncestorProjectTree(seenProjects); + var projectService = defaultProject.projectService; + var cancellationToken = defaultProject.getCancellationToken(); + var defaultDefinition = getDefinitionLocation(defaultProject, initialLocation, isForRename); + // Don't call these unless !!defaultDefinition + var getGeneratedDefinition = ts.memoize(function () { return defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? + defaultDefinition : + defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition); }); + var getSourceDefinition = ts.memoize(function () { return defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? + defaultDefinition : + defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition); }); + // The keys of resultsMap allow us to check which projects have already been searched, but we also + // maintain a set of strings because that's what `loadAncestorProjectTree` wants. + var searchedProjectKeys = new ts.Set(); + onCancellation: while (!queue.isEmpty()) { + while (!queue.isEmpty()) { + if (cancellationToken.isCancellationRequested()) + break onCancellation; + var _a = queue.dequeue(), project = _a.project, location = _a.location; + if (resultsMap.has(project)) + continue; + if (isLocationProjectReferenceRedirect(project, location)) + continue; + var projectResults = searchPosition(project, location); + resultsMap.set(project, projectResults !== null && projectResults !== void 0 ? projectResults : server.emptyArray); + searchedProjectKeys.add(getProjectKey(project)); + } + // At this point, we know about all projects passed in as arguments and any projects in which + // `getResultsForPosition` has returned results. We expand that set to include any projects + // downstream from any of these and then queue new initial-position searches for any new project + // containing `initialLocation`. + if (defaultDefinition) { + // This seems to mean "load all projects downstream from any member of `seenProjects`". + projectService.loadAncestorProjectTree(searchedProjectKeys); projectService.forEachEnabledProject(function (project) { - if (!addToSeen(seenProjects, project)) - return; - var definition = mapDefinitionInProject(defaultDefinition_1, project, getGeneratedDefinition_1, getSourceDefinition_1); - if (definition) { - toDo = callbackProjectAndLocation(project, definition, projectService, toDo, seenProjects, cb); + if (cancellationToken.isCancellationRequested()) + return; // There's no mechanism for skipping the remaining projects + if (resultsMap.has(project)) + return; // Can loop forever without this (enqueue here, dequeue above, repeat) + var location = mapDefinitionInProject(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition); + if (location) { + queue.enqueue({ project: project, location: location }); } }); } } - while (toDo && toDo.length) { - var next = toDo.pop(); - ts.Debug.assertIsDefined(next); - toDo = callbackProjectAndLocation(next.project, next.location, projectService, toDo, seenProjects, cb); + // In the common case where there's only one project, return a simpler result to make + // it easier for the caller to skip post-processing. + if (resultsMap.size === 1) { + var it = resultsMap.values().next(); + ts.Debug.assert(!it.done); + return it.value; + } + return resultsMap; + function searchPosition(project, location) { + var projectResults = getResultsForPosition(project, location); + if (!projectResults) + return undefined; + for (var _i = 0, projectResults_4 = projectResults; _i < projectResults_4.length; _i++) { + var result = projectResults_4[_i]; + forPositionInResult(result, function (position) { + // This may trigger a search for a tsconfig, but there are several layers of caching that make it inexpensive + var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, position); + if (!originalLocation) + return; + var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); + for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { + var project_1 = _a[_i]; + if (!project_1.isOrphan() && !resultsMap.has(project_1)) { // Optimization: don't enqueue if will be discarded + queue.enqueue({ project: project_1, location: originalLocation }); + } + } + var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); + if (symlinkedProjectsMap) { + symlinkedProjectsMap.forEach(function (symlinkedProjects, symlinkedPath) { + for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) { + var symlinkedProject = symlinkedProjects_2[_i]; + if (!symlinkedProject.isOrphan() && !resultsMap.has(symlinkedProject)) { // Optimization: don't enqueue if will be discarded + queue.enqueue({ project: symlinkedProject, location: { fileName: symlinkedPath, pos: originalLocation.pos } }); + } + } + }); + } + }); + } + return projectResults; } } function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) { @@ -174740,43 +177824,6 @@ var ts; sourceFile.resolvedPath !== sourceFile.path && sourceFile.resolvedPath !== project.toPath(location.fileName); } - function callbackProjectAndLocation(project, location, projectService, toDo, seenProjects, cb) { - if (project.getCancellationToken().isCancellationRequested()) - return undefined; // Skip rest of toDo if cancelled - // If this is not the file we were actually looking, return rest of the toDo - if (isLocationProjectReferenceRedirect(project, location)) - return toDo; - cb(project, location, function (innerProject, location) { - addToSeen(seenProjects, project); - var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(innerProject, location); - if (!originalLocation) - return undefined; - var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); - toDo = toDo || []; - for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { - var project_1 = _a[_i]; - addToTodo(project_1, originalLocation, toDo, seenProjects); - } - var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); - if (symlinkedProjectsMap) { - symlinkedProjectsMap.forEach(function (symlinkedProjects, symlinkedPath) { - for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) { - var symlinkedProject = symlinkedProjects_2[_i]; - addToTodo(symlinkedProject, { fileName: symlinkedPath, pos: originalLocation.pos }, toDo, seenProjects); - } - }); - } - return originalLocation === location ? undefined : originalLocation; - }); - return toDo; - } - function addToTodo(project, location, toDo, seenProjects) { - if (!project.isOrphan() && addToSeen(seenProjects, project)) - toDo.push({ project: project, location: location }); - } - function addToSeen(seenProjects, project) { - return ts.tryAddToSet(seenProjects, getProjectKey(project)); - } function getProjectKey(project) { return server.isConfiguredProject(project) ? project.canonicalConfigFilePath : project.getProjectName(); } @@ -174784,32 +177831,14 @@ var ts; var fileName = _a.fileName, textSpan = _a.textSpan; return { fileName: fileName, pos: textSpan.start }; } - function getMappedLocation(location, project) { - var mapsTo = project.getSourceMapper().tryGetSourcePosition(location); - return mapsTo && project.projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined; + function getMappedLocationForProject(location, project) { + return ts.getMappedLocation(location, project.getSourceMapper(), function (p) { return project.projectService.fileExists(p); }); } - function getMappedDocumentSpan(documentSpan, project) { - var newPosition = getMappedLocation(documentSpanLocation(documentSpan), project); - if (!newPosition) - return undefined; - return { - fileName: newPosition.fileName, - textSpan: { - start: newPosition.pos, - length: documentSpan.textSpan.length - }, - originalFileName: documentSpan.fileName, - originalTextSpan: documentSpan.textSpan, - contextSpan: getMappedContextSpan(documentSpan, project), - originalContextSpan: documentSpan.contextSpan - }; + function getMappedDocumentSpanForProject(documentSpan, project) { + return ts.getMappedDocumentSpan(documentSpan, project.getSourceMapper(), function (p) { return project.projectService.fileExists(p); }); } - function getMappedContextSpan(documentSpan, project) { - var contextSpanStart = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, project); - var contextSpanEnd = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length }, project); - return contextSpanStart && contextSpanEnd ? - { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : - undefined; + function getMappedContextSpanForProject(documentSpan, project) { + return ts.getMappedContextSpan(documentSpan, project.getSourceMapper(), function (p) { return project.projectService.fileExists(p); }); } var invalidPartialSemanticModeCommands = [ server.CommandNames.OpenExternalProject, @@ -174839,7 +177868,6 @@ var ts; server.CommandNames.OrganizeImportsFull, server.CommandNames.GetEditsForFileRename, server.CommandNames.GetEditsForFileRenameFull, - server.CommandNames.ConfigurePlugin, server.CommandNames.PrepareCallHierarchy, server.CommandNames.ProvideCallHierarchyIncomingCalls, server.CommandNames.ProvideCallHierarchyOutgoingCalls, @@ -175702,7 +178730,7 @@ var ts; }; Session.prototype.mapDefinitionInfoLocations = function (definitions, project) { return definitions.map(function (info) { - var newDocumentSpan = getMappedDocumentSpan(info, project); + var newDocumentSpan = getMappedDocumentSpanForProject(info, project); return !newDocumentSpan ? info : __assign(__assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name, failedAliasResolution: info.failedAliasResolution }), info.unverified && { unverified: info.unverified }); }); }; @@ -175788,7 +178816,7 @@ var ts; var packageDirectory = fileName.substring(0, nodeModulesPathParts.packageRootIndex); var packageJsonCache = (_a = project.getModuleResolutionCache()) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfoCache(); var compilerOptions = project.getCompilationSettings(); - var packageJson = ts.getPackageScopeForPath(project.toPath(packageDirectory + "/package.json"), packageJsonCache, project, compilerOptions); + var packageJson = ts.getPackageScopeForPath(project.toPath(packageDirectory + "/package.json"), ts.getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions)); if (!packageJson) return undefined; // Use fake options instead of actual compiler options to avoid following export map if the project uses node16 or nodenext - @@ -175947,7 +178975,7 @@ var ts; }; Session.prototype.mapImplementationLocations = function (implementations, project) { return implementations.map(function (info) { - var newDocumentSpan = getMappedDocumentSpan(info, project); + var newDocumentSpan = getMappedDocumentSpanForProject(info, project); return !newDocumentSpan ? info : __assign(__assign({}, newDocumentSpan), { kind: info.kind, displayParts: info.displayParts }); }); }; @@ -176050,7 +179078,8 @@ var ts; Session.prototype.getRenameInfo = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }); + var preferences = this.getPreferences(file); + return project.getLanguageService().getRenameInfo(file, position, preferences); }; Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { var _a; @@ -176101,10 +179130,11 @@ var ts; var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); var defaultProject = this.getDefaultProject(args); - var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), ts.Debug.checkDefined(this.projectService.getScriptInfo(file))); + var preferences = this.getPreferences(file); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, preferences), ts.Debug.checkDefined(this.projectService.getScriptInfo(file))); if (!renameInfo.canRename) return simplifiedResult ? { info: renameInfo, locs: [] } : []; - var locations = combineProjectOutputForRenameLocations(projects, defaultProject, { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getPreferences(file)); + var locations = getRenameLocationsWorker(projects, defaultProject, { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, preferences); if (!simplifiedResult) return locations; return { info: renameInfo, locs: this.toSpanGroups(locations) }; @@ -176136,7 +179166,7 @@ var ts; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); var position = this.getPositionInFile(args, file); - var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, this.logger); + var references = getReferencesWorker(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, this.logger); if (!simplifiedResult) return references; var defaultProject = this.getDefaultProject(args); @@ -176162,8 +179192,8 @@ var ts; return; var projectOutputs = project.getLanguageService().getFileReferences(fileName); if (projectOutputs) { - for (var _i = 0, projectOutputs_3 = projectOutputs; _i < projectOutputs_3.length; _i++) { - var referenceEntry = projectOutputs_3[_i]; + for (var _i = 0, projectOutputs_1 = projectOutputs; _i < projectOutputs_1.length; _i++) { + var referenceEntry = projectOutputs_1[_i]; if (!seen.has(referenceEntry)) { references.push(referenceEntry); seen.add(referenceEntry); @@ -176628,7 +179658,8 @@ var ts; // `name` is a very cheap hash function, but we could incorporate other properties to reduce collisions. var seenItems = new ts.Map(); // name to items with that name if (!args.file && !projectFileName) { - // VS Code's `Go to symbol in workspaces` sends request like this + // VS Code's `Go to symbol in workspaces` sends request like this by default. + // There's a setting to have it send a file name (reverting to older behavior). // TODO (https://github.com/microsoft/TypeScript/issues/47839) // This appears to have been intended to search all projects but, in practice, it seems to only search // those that are downstream from already-loaded projects. @@ -176649,7 +179680,7 @@ var ts; // Mutates `outputs` function addItemsForProject(project) { var projectItems = project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*filename*/ undefined, /*excludeDts*/ project.isNonTsProject()); - var unseenItems = ts.filter(projectItems, function (item) { return tryAddSeenItem(item) && !getMappedLocation(documentSpanLocation(item), project); }); + var unseenItems = ts.filter(projectItems, function (item) { return tryAddSeenItem(item) && !getMappedLocationForProject(documentSpanLocation(item), project); }); if (unseenItems.length) { outputs.push({ project: project, navigateToItems: unseenItems }); } @@ -177106,7 +180137,9 @@ var ts; Session.prototype.executeCommand = function (request) { var handler = this.handlers.get(request.command); if (handler) { - return this.executeWithRequestId(request.seq, function () { return handler(request); }); + var response = this.executeWithRequestId(request.seq, function () { return handler(request); }); + this.projectService.enableRequestedPlugins(); + return response; } else { this.logger.msg("Unrecognized JSON command:".concat(server.stringifyIndented(request)), server.Msg.Err); @@ -178020,6 +181053,8 @@ var ts; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); /*@internal*/ +/// +/// var ts; (function (ts) { var server; @@ -178125,11 +181160,31 @@ var ts; return MainProcessLogger; }(BaseLogger)); server.MainProcessLogger = MainProcessLogger; + // Attempt to load `dynamicImport` + if (typeof importScripts === "function") { + try { + // NOTE: importScripts is synchronous + importScripts("dynamicImportCompat.js"); + } + catch (_a) { + // ignored + } + } function createWebSystem(host, args, getExecutingFilePath) { + var _this = this; var returnEmptyString = function () { return ""; }; var getExecutingDirectoryPath = ts.memoize(function () { return ts.memoize(function () { return ts.ensureTrailingDirectorySeparator(ts.getDirectoryPath(getExecutingFilePath())); }); }); // Later we could map ^memfs:/ to do something special if we want to enable more functionality like module resolution or something like that var getWebPath = function (path) { return ts.startsWith(path, ts.directorySeparator) ? path.replace(ts.directorySeparator, getExecutingDirectoryPath()) : undefined; }; + var dynamicImport = function (id) { return __awaiter(_this, void 0, void 0, function () { + return __generator(this, function (_a) { + // Use syntactic dynamic import first, if available + if (server.dynamicImport) { + return [2 /*return*/, server.dynamicImport(id)]; + } + throw new Error("Dynamic import not implemented"); + }); + }); }; return { args: args, newLine: "\r\n", @@ -178155,7 +181210,45 @@ var ts; setImmediate: function (x) { return setTimeout(x, 0); }, clearImmediate: function (handle) { return clearTimeout(handle); }, /* eslint-enable no-restricted-globals */ - require: function () { return ({ module: undefined, error: new Error("Not implemented") }); }, + importServicePlugin: function (initialDir, moduleName) { return __awaiter(_this, void 0, void 0, function () { + var packageRoot, packageJson, packageJsonResponse, e_1, browser, scriptPath, module_1, e_2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + packageRoot = ts.combinePaths(initialDir, moduleName); + _a.label = 1; + case 1: + _a.trys.push([1, 4, , 5]); + return [4 /*yield*/, fetch(ts.combinePaths(packageRoot, "package.json"))]; + case 2: + packageJsonResponse = _a.sent(); + return [4 /*yield*/, packageJsonResponse.json()]; + case 3: + packageJson = _a.sent(); + return [3 /*break*/, 5]; + case 4: + e_1 = _a.sent(); + return [2 /*return*/, { module: undefined, error: new Error("Could not load plugin. Could not load 'package.json'.") }]; + case 5: + browser = packageJson.browser; + if (!browser) { + return [2 /*return*/, { module: undefined, error: new Error("Could not load plugin. No 'browser' field found in package.json.") }]; + } + scriptPath = ts.combinePaths(packageRoot, browser); + _a.label = 6; + case 6: + _a.trys.push([6, 8, , 9]); + return [4 /*yield*/, dynamicImport(scriptPath)]; + case 7: + module_1 = (_a.sent()).default; + return [2 /*return*/, { module: module_1, error: undefined }]; + case 8: + e_2 = _a.sent(); + return [2 /*return*/, { module: undefined, error: e_2 }]; + case 9: return [2 /*return*/]; + } + }); + }); }, exit: ts.notImplemented, // Debugging related getEnvironmentVariable: returnEmptyString, @@ -178213,23 +181306,80 @@ var ts; server.WorkerSession = WorkerSession; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +// The following are deprecations for the public API. Deprecated exports are removed from the compiler itself +// and compatible implementations are added here, along with an appropriate deprecation warning using +// the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. +// +// Deprecations fall into one of three categories: +// +// - "soft" - Soft deprecations are indicated with the `@deprecated` JSDoc Tag. +// - "warn" - Warning deprecations are indicated with the `@deprecated` JSDoc Tag and a diagnostic message (assuming a compatible host). +// - "error" - Error deprecations are either indicated with the `@deprecated` JSDoc tag and will throw a `TypeError` when invoked, or removed from the API entirely. +// +// Once we have determined enough time has passed after a deprecation has been marked as `"warn"` or `"error"`, it will be removed from the public API. +/* @internal */ +var ts; +(function (ts) { + function createOverload(name, overloads, binder, deprecations) { + Object.defineProperty(call, "name", __assign(__assign({}, Object.getOwnPropertyDescriptor(call, "name")), { value: name })); + if (deprecations) { + for (var _i = 0, _a = Object.keys(deprecations); _i < _a.length; _i++) { + var key = _a[_i]; + var index = +key; + if (!isNaN(index) && ts.hasProperty(overloads, "".concat(index))) { + overloads[index] = ts.Debug.deprecate(overloads[index], __assign(__assign({}, deprecations[index]), { name: name })); + } + } + } + var bind = createBinder(overloads, binder); + return call; + function call() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var index = bind(args); + var fn = index !== undefined ? overloads[index] : undefined; + if (typeof fn === "function") { + return fn.apply(void 0, args); + } + throw new TypeError("Invalid arguments"); + } + } + ts.createOverload = createOverload; + function createBinder(overloads, binder) { + return function (args) { + for (var i = 0; ts.hasProperty(overloads, "".concat(i)) && ts.hasProperty(binder, "".concat(i)); i++) { + var fn = binder[i]; + if (fn(args)) { + return i; + } + } + }; + } + // NOTE: We only use this "builder" because we don't infer correctly when calling `createOverload` directly in < TS 4.7, + // but lib is currently at TS 4.4. We can switch to directly calling `createOverload` when we update LKG in main. + function buildOverload(name) { + return { + overload: function (overloads) { return ({ + bind: function (binder) { return ({ + finish: function () { return createOverload(name, overloads, binder); }, + deprecate: function (deprecations) { return ({ + finish: function () { return createOverload(name, overloads, binder, deprecations); } + }); } + }); } + }); } + }; + } + ts.buildOverload = buildOverload; +})(ts || (ts = {})); +// DEPRECATION: Node factory top-level exports +// DEPRECATION PLAN: +// - soft: 4.0 +// - warn: 4.1 +// - error: 5.0 var ts; (function (ts) { - // The following are deprecations for the public API. Deprecated exports are removed from the compiler itself - // and compatible implementations are added here, along with an appropriate deprecation warning using - // the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. - // - // Deprecations fall into one of three categories: - // - // * "soft" - Soft deprecations are indicated with the `@deprecated` JSDoc Tag. - // * "warn" - Warning deprecations are indicated with the `@deprecated` JSDoc Tag and a diagnostic message (assuming a compatible host) - // * "error" - Error deprecations are indicated with the `@deprecated` JSDoc tag and will throw a `TypeError` when invoked. - // DEPRECATION: Node factory top-level exports - // DEPRECATION PLAN: - // - soft: 4.0 - // - warn: 4.1 - // - error: TBD - // #region Node factory top-level exports // NOTE: These exports are deprecated in favor of using a `NodeFactory` instance and exist here purely for backwards compatibility reasons. var factoryDeprecation = { since: "4.0", warnAfter: "4.1", message: "Use the appropriate method on 'ts.factory' or the 'factory' supplied by your transformation context instead." }; /** @deprecated Use `factory.createNodeArray` or the factory supplied by your transformation context instead. */ @@ -179099,13 +182249,14 @@ var ts; ts.setParent(clone, node.parent); return clone; }, { since: "4.0", warnAfter: "4.1", message: "Use an appropriate `factory.update...` method instead, use `setCommentRange` or `setSourceMapRange`, and avoid setting `parent`." }); - // #endregion Node Factory top-level exports - // DEPRECATION: Renamed node tests - // DEPRECATION PLAN: - // - soft: 4.0 - // - warn: 4.1 - // - error: TBD - // #region Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Renamed node tests +// DEPRECATION PLAN: +// - soft: 4.0 +// - warn: 4.1 +// - error: TBD +var ts; +(function (ts) { /** @deprecated Use `isTypeAssertionExpression` instead. */ ts.isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node) { return node.kind === 211 /* SyntaxKind.TypeAssertionExpression */; @@ -179114,13 +182265,14 @@ var ts; warnAfter: "4.1", message: "Use `isTypeAssertionExpression` instead." }); - // #endregion - // DEPRECATION: Renamed node tests - // DEPRECATION PLAN: - // - soft: 4.2 - // - warn: 4.3 - // - error: TBD - // #region Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Renamed node tests +// DEPRECATION PLAN: +// - soft: 4.2 +// - warn: 4.3 +// - error: 5.0 +var ts; +(function (ts) { /** * @deprecated Use `isMemberName` instead. */ @@ -179131,7 +182283,1406 @@ var ts; warnAfter: "4.3", message: "Use `isMemberName` instead." }); - // #endregion Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Overloads for createConstructorTypeNode/updateConstructorTypeNode that do not accept 'modifiers' +// DEPRECATION PLAN: +// - soft: 4.2 +// - warn: 4.3 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createConstructorTypeNode = factory.createConstructorTypeNode, updateConstructorTypeNode = factory.updateConstructorTypeNode; + factory.createConstructorTypeNode = ts.buildOverload("createConstructorTypeNode") + .overload({ + 0: function (modifiers, typeParameters, parameters, type) { + return createConstructorTypeNode(modifiers, typeParameters, parameters, type); + }, + 1: function (typeParameters, parameters, type) { + return createConstructorTypeNode(/*modifiers*/ undefined, typeParameters, parameters, type); + }, + }) + .bind({ + 0: function (args) { return args.length === 4; }, + 1: function (args) { return args.length === 3; }, + }) + .deprecate({ + 1: { since: "4.2", warnAfter: "4.3", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + factory.updateConstructorTypeNode = ts.buildOverload("updateConstructorTypeNode") + .overload({ + 0: function (node, modifiers, typeParameters, parameters, type) { + return updateConstructorTypeNode(node, modifiers, typeParameters, parameters, type); + }, + 1: function (node, typeParameters, parameters, type) { + return updateConstructorTypeNode(node, node.modifiers, typeParameters, parameters, type); + } + }) + .bind({ + 0: function (args) { return args.length === 5; }, + 1: function (args) { return args.length === 4; }, + }) + .deprecate({ + 1: { since: "4.2", warnAfter: "4.3", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Overloads to createImportTypeNode/updateImportTypeNode that do not accept `assertions` +// DEPRECATION PLAN: +// - soft: 4.6 +// - warn: 4.7 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createImportTypeNode = factory.createImportTypeNode, updateImportTypeNode = factory.updateImportTypeNode; + factory.createImportTypeNode = ts.buildOverload("createImportTypeNode") + .overload({ + 0: function (argument, assertions, qualifier, typeArguments, isTypeOf) { + return createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf); + }, + 1: function (argument, qualifier, typeArguments, isTypeOf) { + return createImportTypeNode(argument, /*assertions*/ undefined, qualifier, typeArguments, isTypeOf); + }, + }) + .bind({ + 0: function (_a) { + var assertions = _a[1], qualifier = _a[2], typeArguments = _a[3], isTypeOf = _a[4]; + return (assertions === undefined || ts.isImportTypeAssertionContainer(assertions)) && + (qualifier === undefined || !ts.isArray(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + 1: function (_a) { + var qualifier = _a[1], typeArguments = _a[2], isTypeOf = _a[3], other = _a[4]; + return (other === undefined) && + (qualifier === undefined || ts.isEntityName(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + }) + .deprecate({ + 1: { since: "4.6", warnAfter: "4.7", message: "Use the overload that accepts 'assertions'" } + }) + .finish(); + factory.updateImportTypeNode = ts.buildOverload("updateImportTypeNode") + .overload({ + 0: function (node, argument, assertions, qualifier, typeArguments, isTypeOf) { + return updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf); + }, + 1: function (node, argument, qualifier, typeArguments, isTypeOf) { + return updateImportTypeNode(node, argument, node.assertions, qualifier, typeArguments, isTypeOf); + }, + }) + .bind({ + 0: function (_a) { + var assertions = _a[2], qualifier = _a[3], typeArguments = _a[4], isTypeOf = _a[5]; + return (assertions === undefined || ts.isImportTypeAssertionContainer(assertions)) && + (qualifier === undefined || !ts.isArray(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + 1: function (_a) { + var qualifier = _a[2], typeArguments = _a[3], isTypeOf = _a[4], other = _a[5]; + return (other === undefined) && + (qualifier === undefined || ts.isEntityName(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + }). + deprecate({ + 1: { since: "4.6", warnAfter: "4.7", message: "Use the overload that accepts 'assertions'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Overloads to createTypeParameter/updateTypeParameter that does not accept `modifiers` +// DEPRECATION PLAN: +// - soft: 4.7 +// - warn: 4.8 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createTypeParameterDeclaration = factory.createTypeParameterDeclaration, updateTypeParameterDeclaration = factory.updateTypeParameterDeclaration; + factory.createTypeParameterDeclaration = ts.buildOverload("createTypeParameterDeclaration") + .overload({ + 0: function (modifiers, name, constraint, defaultType) { + return createTypeParameterDeclaration(modifiers, name, constraint, defaultType); + }, + 1: function (name, constraint, defaultType) { + return createTypeParameterDeclaration(/*modifiers*/ undefined, name, constraint, defaultType); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0]; + return (modifiers === undefined || ts.isArray(modifiers)); + }, + 1: function (_a) { + var name = _a[0]; + return (name !== undefined && !ts.isArray(name)); + }, + }) + .deprecate({ + 1: { since: "4.7", warnAfter: "4.8", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + factory.updateTypeParameterDeclaration = ts.buildOverload("updateTypeParameterDeclaration") + .overload({ + 0: function (node, modifiers, name, constraint, defaultType) { + return updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType); + }, + 1: function (node, name, constraint, defaultType) { + return updateTypeParameterDeclaration(node, node.modifiers, name, constraint, defaultType); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1]; + return (modifiers === undefined || ts.isArray(modifiers)); + }, + 1: function (_a) { + var name = _a[1]; + return (name !== undefined && !ts.isArray(name)); + }, + }) + .deprecate({ + 1: { since: "4.7", warnAfter: "4.8", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Deprecate passing `decorators` separate from `modifiers` +// DEPRECATION PLAN: +// - soft: 4.8 +// - warn: 4.9 +// - error: 5.0 +var ts; +(function (ts) { + var MUST_MERGE = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators have been combined with modifiers. Callers should switch to an overload that does not accept a 'decorators' parameter." }; + var DISALLOW_DECORATORS = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators are no longer supported for this function. Callers should switch to an overload that does not accept a 'decorators' parameter." }; + var DISALLOW_DECORATORS_AND_MODIFIERS = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators and modifiers are no longer supported for this function. Callers should switch to an overload that does not accept the 'decorators' and 'modifiers' parameters." }; + function patchNodeFactory(factory) { + var createParameterDeclaration = factory.createParameterDeclaration, updateParameterDeclaration = factory.updateParameterDeclaration, createPropertyDeclaration = factory.createPropertyDeclaration, updatePropertyDeclaration = factory.updatePropertyDeclaration, createMethodDeclaration = factory.createMethodDeclaration, updateMethodDeclaration = factory.updateMethodDeclaration, createConstructorDeclaration = factory.createConstructorDeclaration, updateConstructorDeclaration = factory.updateConstructorDeclaration, createGetAccessorDeclaration = factory.createGetAccessorDeclaration, updateGetAccessorDeclaration = factory.updateGetAccessorDeclaration, createSetAccessorDeclaration = factory.createSetAccessorDeclaration, updateSetAccessorDeclaration = factory.updateSetAccessorDeclaration, createIndexSignature = factory.createIndexSignature, updateIndexSignature = factory.updateIndexSignature, createClassStaticBlockDeclaration = factory.createClassStaticBlockDeclaration, updateClassStaticBlockDeclaration = factory.updateClassStaticBlockDeclaration, createClassExpression = factory.createClassExpression, updateClassExpression = factory.updateClassExpression, createFunctionDeclaration = factory.createFunctionDeclaration, updateFunctionDeclaration = factory.updateFunctionDeclaration, createClassDeclaration = factory.createClassDeclaration, updateClassDeclaration = factory.updateClassDeclaration, createInterfaceDeclaration = factory.createInterfaceDeclaration, updateInterfaceDeclaration = factory.updateInterfaceDeclaration, createTypeAliasDeclaration = factory.createTypeAliasDeclaration, updateTypeAliasDeclaration = factory.updateTypeAliasDeclaration, createEnumDeclaration = factory.createEnumDeclaration, updateEnumDeclaration = factory.updateEnumDeclaration, createModuleDeclaration = factory.createModuleDeclaration, updateModuleDeclaration = factory.updateModuleDeclaration, createImportEqualsDeclaration = factory.createImportEqualsDeclaration, updateImportEqualsDeclaration = factory.updateImportEqualsDeclaration, createImportDeclaration = factory.createImportDeclaration, updateImportDeclaration = factory.updateImportDeclaration, createExportAssignment = factory.createExportAssignment, updateExportAssignment = factory.updateExportAssignment, createExportDeclaration = factory.createExportDeclaration, updateExportDeclaration = factory.updateExportDeclaration; + factory.createParameterDeclaration = ts.buildOverload("createParameterDeclaration") + .overload({ + 0: function (modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer); + }, + 1: function (decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return createParameterDeclaration(ts.concatenate(decorators, modifiers), dotDotDotToken, name, questionToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var dotDotDotToken = _a[1], name = _a[2], questionToken = _a[3], type = _a[4], initializer = _a[5], other = _a[6]; + return (other === undefined) && + (dotDotDotToken === undefined || !ts.isArray(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[1], dotDotDotToken = _a[2], name = _a[3], questionToken = _a[4], type = _a[5], initializer = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (dotDotDotToken === undefined || typeof dotDotDotToken === "object" && ts.isDotDotDotToken(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateParameterDeclaration = ts.buildOverload("updateParameterDeclaration") + .overload({ + 0: function (node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer); + }, + 1: function (node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return updateParameterDeclaration(node, ts.concatenate(decorators, modifiers), dotDotDotToken, name, questionToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var dotDotDotToken = _a[2], name = _a[3], questionToken = _a[4], type = _a[5], initializer = _a[6], other = _a[7]; + return (other === undefined) && + (dotDotDotToken === undefined || !ts.isArray(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[2], dotDotDotToken = _a[3], name = _a[4], questionToken = _a[5], type = _a[6], initializer = _a[7]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (dotDotDotToken === undefined || typeof dotDotDotToken === "object" && ts.isDotDotDotToken(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createPropertyDeclaration = ts.buildOverload("createPropertyDeclaration") + .overload({ + 0: function (modifiers, name, questionOrExclamationToken, type, initializer) { + return createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer); + }, + 1: function (decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return createPropertyDeclaration(ts.concatenate(decorators, modifiers), name, questionOrExclamationToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], questionOrExclamationToken = _a[2], type = _a[3], initializer = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (questionOrExclamationToken === undefined || typeof questionOrExclamationToken === "object" && ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], questionOrExclamationToken = _a[3], type = _a[4], initializer = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionOrExclamationToken === undefined || ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updatePropertyDeclaration = ts.buildOverload("updatePropertyDeclaration") + .overload({ + 0: function (node, modifiers, name, questionOrExclamationToken, type, initializer) { + return updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer); + }, + 1: function (node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return updatePropertyDeclaration(node, ts.concatenate(decorators, modifiers), name, questionOrExclamationToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], questionOrExclamationToken = _a[3], type = _a[4], initializer = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (questionOrExclamationToken === undefined || typeof questionOrExclamationToken === "object" && ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], questionOrExclamationToken = _a[4], type = _a[5], initializer = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionOrExclamationToken === undefined || ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createMethodDeclaration = ts.buildOverload("createMethodDeclaration") + .overload({ + 0: function (modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + 1: function (decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return createMethodDeclaration(ts.concatenate(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[1], name = _a[2], questionToken = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7], other = _a[8]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || !ts.some(parameters, ts.isTypeParameterDeclaration)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], asteriskToken = _a[2], name = _a[3], questionToken = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken === "object" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || !ts.isArray(questionToken)) && + (typeParameters === undefined || !ts.some(typeParameters, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateMethodDeclaration = ts.buildOverload("updateMethodDeclaration") + .overload({ + 0: function (node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + 1: function (node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return updateMethodDeclaration(node, ts.concatenate(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[2], name = _a[3], questionToken = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8], other = _a[9]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || !ts.some(parameters, ts.isTypeParameterDeclaration)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], asteriskToken = _a[3], name = _a[4], questionToken = _a[5], typeParameters = _a[6], parameters = _a[7], type = _a[8], body = _a[9]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken === "object" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || !ts.isArray(questionToken)) && + (typeParameters === undefined || !ts.some(typeParameters, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createConstructorDeclaration = ts.buildOverload("createConstructorDeclaration") + .overload({ + 0: function (modifiers, parameters, body) { + return createConstructorDeclaration(modifiers, parameters, body); + }, + 1: function (_decorators, modifiers, parameters, body) { + return createConstructorDeclaration(modifiers, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], parameters = _a[1], body = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || !ts.some(modifiers, ts.isDecorator)) && + (parameters === undefined || !ts.some(parameters, ts.isModifier)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], parameters = _a[2], body = _a[3]; + return (decorators === undefined || !ts.some(decorators, ts.isModifier)) && + (modifiers === undefined || !ts.some(modifiers, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateConstructorDeclaration = ts.buildOverload("updateConstructorDeclaration") + .overload({ + 0: function (node, modifiers, parameters, body) { + return updateConstructorDeclaration(node, modifiers, parameters, body); + }, + 1: function (node, _decorators, modifiers, parameters, body) { + return updateConstructorDeclaration(node, modifiers, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], parameters = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || !ts.some(modifiers, ts.isDecorator)) && + (parameters === undefined || !ts.some(parameters, ts.isModifier)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], parameters = _a[3], body = _a[4]; + return (decorators === undefined || !ts.some(decorators, ts.isModifier)) && + (modifiers === undefined || !ts.some(modifiers, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createGetAccessorDeclaration = ts.buildOverload("createGetAccessorDeclaration") + .overload({ + 0: function (modifiers, name, parameters, type, body) { + return createGetAccessorDeclaration(modifiers, name, parameters, type, body); + }, + 1: function (decorators, modifiers, name, parameters, type, body) { + return createGetAccessorDeclaration(ts.concatenate(decorators, modifiers), name, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], parameters = _a[2], type = _a[3], body = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], parameters = _a[3], type = _a[4], body = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateGetAccessorDeclaration = ts.buildOverload("updateGetAccessorDeclaration") + .overload({ + 0: function (node, modifiers, name, parameters, type, body) { + return updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body); + }, + 1: function (node, decorators, modifiers, name, parameters, type, body) { + return updateGetAccessorDeclaration(node, ts.concatenate(decorators, modifiers), name, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], parameters = _a[3], type = _a[4], body = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], parameters = _a[4], type = _a[5], body = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createSetAccessorDeclaration = ts.buildOverload("createSetAccessorDeclaration") + .overload({ + 0: function (modifiers, name, parameters, body) { + return createSetAccessorDeclaration(modifiers, name, parameters, body); + }, + 1: function (decorators, modifiers, name, parameters, body) { + return createSetAccessorDeclaration(ts.concatenate(decorators, modifiers), name, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], parameters = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], parameters = _a[3], body = _a[4]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateSetAccessorDeclaration = ts.buildOverload("updateSetAccessorDeclaration") + .overload({ + 0: function (node, modifiers, name, parameters, body) { + return updateSetAccessorDeclaration(node, modifiers, name, parameters, body); + }, + 1: function (node, decorators, modifiers, name, parameters, body) { + return updateSetAccessorDeclaration(node, ts.concatenate(decorators, modifiers), name, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], parameters = _a[3], body = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], parameters = _a[4], body = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createIndexSignature = ts.buildOverload("createIndexSignature") + .overload({ + 0: function (modifiers, parameters, type) { + return createIndexSignature(modifiers, parameters, type); + }, + 1: function (_decorators, modifiers, parameters, type) { + return createIndexSignature(modifiers, parameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], parameters = _a[1], type = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], parameters = _a[2], type = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateIndexSignature = ts.buildOverload("updateIndexSignature") + .overload({ + 0: function (node, modifiers, parameters, type) { + return updateIndexSignature(node, modifiers, parameters, type); + }, + 1: function (node, _decorators, modifiers, parameters, type) { + return updateIndexSignature(node, modifiers, parameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], parameters = _a[2], type = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], parameters = _a[3], type = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createClassStaticBlockDeclaration = ts.buildOverload("createClassStaticBlockDeclaration") + .overload({ + 0: function (body) { + return createClassStaticBlockDeclaration(body); + }, + 1: function (_decorators, _modifiers, body) { + return createClassStaticBlockDeclaration(body); + }, + }) + .bind({ + 0: function (_a) { + var body = _a[0], other1 = _a[1], other2 = _a[2]; + return (other1 === undefined) && + (other2 === undefined) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], body = _a[2]; + return (decorators === undefined || ts.isArray(decorators)) && + (modifiers === undefined || ts.isArray(decorators)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS_AND_MODIFIERS + }) + .finish(); + factory.updateClassStaticBlockDeclaration = ts.buildOverload("updateClassStaticBlockDeclaration") + .overload({ + 0: function (node, body) { + return updateClassStaticBlockDeclaration(node, body); + }, + 1: function (node, _decorators, _modifiers, body) { + return updateClassStaticBlockDeclaration(node, body); + }, + }) + .bind({ + 0: function (_a) { + var body = _a[1], other1 = _a[2], other2 = _a[3]; + return (other1 === undefined) && + (other2 === undefined) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], body = _a[3]; + return (decorators === undefined || ts.isArray(decorators)) && + (modifiers === undefined || ts.isArray(decorators)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS_AND_MODIFIERS + }) + .finish(); + factory.createClassExpression = ts.buildOverload("createClassExpression") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createClassExpression(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createClassExpression(ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateClassExpression = ts.buildOverload("updateClassExpression") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassExpression(node, ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createFunctionDeclaration = ts.buildOverload("createFunctionDeclaration") + .overload({ + 0: function (modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + 1: function (_decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[1], name = _a[2], typeParameters = _a[3], parameters = _a[4], type = _a[5], body = _a[6], other = _a[7]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isIdentifier(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], asteriskToken = _a[2], name = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken !== "string" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateFunctionDeclaration = ts.buildOverload("updateFunctionDeclaration") + .overload({ + 0: function (node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + 1: function (node, _decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[2], name = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7], other = _a[8]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || ts.isIdentifier(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], asteriskToken = _a[3], name = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken !== "string" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createClassDeclaration = ts.buildOverload("createClassDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createClassDeclaration(ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function () { return true; }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateClassDeclaration = ts.buildOverload("updateClassDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createInterfaceDeclaration = ts.buildOverload("createInterfaceDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (_decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateInterfaceDeclaration = ts.buildOverload("updateInterfaceDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, _decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createTypeAliasDeclaration = ts.buildOverload("createTypeAliasDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, type) { + return createTypeAliasDeclaration(modifiers, name, typeParameters, type); + }, + 1: function (_decorators, modifiers, name, typeParameters, type) { + return createTypeAliasDeclaration(modifiers, name, typeParameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], typeParameters = _a[2], type = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], typeParameters = _a[3], type = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateTypeAliasDeclaration = ts.buildOverload("updateTypeAliasDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, type) { + return updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type); + }, + 1: function (node, _decorators, modifiers, name, typeParameters, type) { + return updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], type = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], typeParameters = _a[4], type = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createEnumDeclaration = ts.buildOverload("createEnumDeclaration") + .overload({ + 0: function (modifiers, name, members) { + return createEnumDeclaration(modifiers, name, members); + }, + 1: function (_decorators, modifiers, name, members) { + return createEnumDeclaration(modifiers, name, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], members = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], members = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateEnumDeclaration = ts.buildOverload("updateEnumDeclaration") + .overload({ + 0: function (node, modifiers, name, members) { + return updateEnumDeclaration(node, modifiers, name, members); + }, + 1: function (node, _decorators, modifiers, name, members) { + return updateEnumDeclaration(node, modifiers, name, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], members = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], members = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createModuleDeclaration = ts.buildOverload("createModuleDeclaration") + .overload({ + 0: function (modifiers, name, body, flags) { + return createModuleDeclaration(modifiers, name, body, flags); + }, + 1: function (_decorators, modifiers, name, body, flags) { + return createModuleDeclaration(modifiers, name, body, flags); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], body = _a[2], flags = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name !== undefined && !ts.isArray(name)) && + (body === undefined || ts.isModuleBody(body)) && + (flags === undefined || typeof flags === "number"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], body = _a[3], flags = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name !== undefined && ts.isModuleName(name)) && + (body === undefined || typeof body === "object") && + (flags === undefined || typeof flags === "number"); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateModuleDeclaration = ts.buildOverload("updateModuleDeclaration") + .overload({ + 0: function (node, modifiers, name, body) { + return updateModuleDeclaration(node, modifiers, name, body); + }, + 1: function (node, _decorators, modifiers, name, body) { + return updateModuleDeclaration(node, modifiers, name, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (body === undefined || ts.isModuleBody(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], body = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name !== undefined && ts.isModuleName(name)) && + (body === undefined || ts.isModuleBody(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createImportEqualsDeclaration = ts.buildOverload("createImportEqualsDeclaration") + .overload({ + 0: function (modifiers, isTypeOnly, name, moduleReference) { + return createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference); + }, + 1: function (_decorators, modifiers, isTypeOnly, name, moduleReference) { + return createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isTypeOnly = _a[1], name = _a[2], moduleReference = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name !== "boolean") && + (typeof moduleReference !== "string"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isTypeOnly = _a[2], name = _a[3], moduleReference = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name === "string" || ts.isIdentifier(name)) && + (moduleReference !== undefined && ts.isModuleReference(moduleReference)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateImportEqualsDeclaration = ts.buildOverload("updateImportEqualsDeclaration") + .overload({ + 0: function (node, modifiers, isTypeOnly, name, moduleReference) { + return updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference); + }, + 1: function (node, _decorators, modifiers, isTypeOnly, name, moduleReference) { + return updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], isTypeOnly = _a[2], name = _a[3], moduleReference = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name !== "boolean") && + (typeof moduleReference !== "string"); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], isTypeOnly = _a[3], name = _a[4], moduleReference = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name === "string" || ts.isIdentifier(name)) && + (moduleReference !== undefined && ts.isModuleReference(moduleReference)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createImportDeclaration = ts.buildOverload("createImportDeclaration") + .overload({ + 0: function (modifiers, importClause, moduleSpecifier, assertClause) { + return createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + }, + 1: function (_decorators, modifiers, importClause, moduleSpecifier, assertClause) { + return createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], importClause = _a[1], moduleSpecifier = _a[2], assertClause = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (importClause === undefined || !ts.isArray(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], importClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (importClause === undefined || ts.isImportClause(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateImportDeclaration = ts.buildOverload("updateImportDeclaration") + .overload({ + 0: function (node, modifiers, importClause, moduleSpecifier, assertClause) { + return updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause); + }, + 1: function (node, _decorators, modifiers, importClause, moduleSpecifier, assertClause) { + return updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], importClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (importClause === undefined || !ts.isArray(importClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], importClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (importClause === undefined || ts.isImportClause(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createExportAssignment = ts.buildOverload("createExportAssignment") + .overload({ + 0: function (modifiers, isExportEquals, expression) { + return createExportAssignment(modifiers, isExportEquals, expression); + }, + 1: function (_decorators, modifiers, isExportEquals, expression) { + return createExportAssignment(modifiers, isExportEquals, expression); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isExportEquals = _a[1], expression = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isExportEquals === undefined || typeof isExportEquals === "boolean") && + (typeof expression === "object"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isExportEquals = _a[2], expression = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isExportEquals === undefined || typeof isExportEquals === "boolean") && + (expression !== undefined && ts.isExpression(expression)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateExportAssignment = ts.buildOverload("updateExportAssignment") + .overload({ + 0: function (node, modifiers, expression) { + return updateExportAssignment(node, modifiers, expression); + }, + 1: function (node, _decorators, modifiers, expression) { + return updateExportAssignment(node, modifiers, expression); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], expression = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (expression !== undefined && !ts.isArray(expression)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], expression = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (expression !== undefined && ts.isExpression(expression)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createExportDeclaration = ts.buildOverload("createExportDeclaration") + .overload({ + 0: function (modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + 1: function (_decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isTypeOnly = _a[1], exportClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (typeof isTypeOnly === "boolean") && + (typeof exportClause !== "boolean") && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isTypeOnly = _a[2], exportClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (typeof isTypeOnly === "boolean") && + (exportClause === undefined || ts.isNamedExportBindings(exportClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateExportDeclaration = ts.buildOverload("updateExportDeclaration") + .overload({ + 0: function (node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + 1: function (node, _decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], isTypeOnly = _a[2], exportClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5], other = _a[6]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (typeof isTypeOnly === "boolean") && + (typeof exportClause !== "boolean") && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], isTypeOnly = _a[3], exportClause = _a[4], moduleSpecifier = _a[5], assertClause = _a[6]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (typeof isTypeOnly === "boolean") && + (exportClause === undefined || ts.isNamedExportBindings(exportClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); })(ts || (ts = {})); /*@internal*/ var ts; @@ -179251,7 +183802,20 @@ var ts; var useWatchGuard = process.platform === "win32" && nodeVersion >= 4; var originalWatchDirectory = sys.watchDirectory.bind(sys); var logger = createLogger(); - var pending = []; + // enable deprecation logging + ts.Debug.loggingHost = { + log: function (level, s) { + switch (level) { + case ts.LogLevel.Error: + case ts.LogLevel.Warning: + return logger.msg(s, server.Msg.Err); + case ts.LogLevel.Info: + case ts.LogLevel.Verbose: + return logger.msg(s, server.Msg.Info); + } + } + }; + var pending = ts.createQueue(); var canWrite = true; if (useWatchGuard) { var currentDrive_1 = extractWatchDirectoryCacheKey(sys.resolvePath(sys.getCurrentDirectory()), /*currentDriveKey*/ undefined); @@ -179380,7 +183944,7 @@ var ts; } function writeMessage(buf) { if (!canWrite) { - pending.push(buf); + pending.enqueue(buf); } else { canWrite = false; @@ -179389,8 +183953,8 @@ var ts; } function setCanWriteFlagAndWriteMessageIfNecessary() { canWrite = true; - if (pending.length) { - writeMessage(pending.shift()); + if (!pending.isEmpty()) { + writeMessage(pending.dequeue()); } } function extractWatchDirectoryCacheKey(path, currentDriveKey) { @@ -179460,7 +184024,7 @@ var ts; this.validateDefaultNpmLocation = validateDefaultNpmLocation; this.event = event; this.activeRequestCount = 0; - this.requestQueue = []; + this.requestQueue = ts.createQueue(); this.requestMap = new ts.Map(); // Maps operation ID to newest requestQueue entry with that ID /** We will lazily request the types registry on the first call to `isKnownTypesPackageName` and store it in `typesRegistryCache`. */ this.requestedRegistry = false; @@ -179565,7 +184129,7 @@ var ts; if (this.logger.hasLevel(server.LogLevel.verbose)) { this.logger.info("Deferring request for: ".concat(operationId)); } - this.requestQueue.push(queuedRequest); + this.requestQueue.enqueue(queuedRequest); this.requestMap.set(operationId, queuedRequest); } }; @@ -179641,8 +184205,8 @@ var ts; else { ts.Debug.fail("Received too many responses"); } - while (this.requestQueue.length > 0) { - var queuedRequest = this.requestQueue.shift(); + while (!this.requestQueue.isEmpty()) { + var queuedRequest = this.requestQueue.dequeue(); if (this.requestMap.get(queuedRequest.operationId) === queuedRequest) { this.requestMap.delete(queuedRequest.operationId); this.scheduleRequest(queuedRequest); @@ -179875,9 +184439,23 @@ var ts; serverMode = modeOrUnknown; else unknownServerMode = modeOrUnknown; + var logger = createLogger(); + // enable deprecation logging + ts.Debug.loggingHost = { + log: function (level, s) { + switch (level) { + case ts.LogLevel.Error: + case ts.LogLevel.Warning: + return logger.msg(s, server.Msg.Err); + case ts.LogLevel.Info: + case ts.LogLevel.Verbose: + return logger.msg(s, server.Msg.Info); + } + } + }; return { args: args, - logger: createLogger(), + logger: logger, cancellationToken: server.nullCancellationToken, // Webserver defaults to partial semantic mode serverMode: serverMode !== null && serverMode !== void 0 ? serverMode : ts.LanguageServiceMode.PartialSemantic, diff --git a/tsserver/tsserverlibrary.d.ts b/tsserver/tsserverlibrary.d.ts index f7e45674..4744d065 100644 --- a/tsserver/tsserverlibrary.d.ts +++ b/tsserver/tsserverlibrary.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "4.7"; + const versionMajorMinor = "4.8"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -425,6 +425,7 @@ declare namespace ts { JSDocFunctionType = 317, JSDocVariadicType = 318, JSDocNamepathType = 319, + JSDoc = 320, /** @deprecated Use SyntaxKind.JSDoc */ JSDocComment = 320, JSDocText = 321, @@ -493,7 +494,6 @@ declare namespace ts { LastJSDocNode = 347, FirstJSDocTagNode = 327, LastJSDocTagNode = 347, - JSDoc = 320 } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; @@ -554,13 +554,15 @@ declare namespace ts { Override = 16384, In = 32768, Out = 65536, + Decorator = 131072, HasComputedFlags = 536870912, AccessibilityModifier = 28, ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, TypeScriptModifier = 116958, ExportDefault = 513, - All = 125951 + All = 257023, + Modifier = 125951 } export enum JsxFlags { None = 0, @@ -573,8 +575,6 @@ declare namespace ts { export interface Node extends ReadonlyTextRange { readonly kind: SyntaxKind; readonly flags: NodeFlags; - readonly decorators?: NodeArray; - readonly modifiers?: ModifiersArray; readonly parent: Node; } export interface JSDocContainer { @@ -583,7 +583,9 @@ declare namespace ts { export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; export type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; - export type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; + export type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | EnumMember; + export type HasDecorators = ParameterDeclaration | PropertyDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ClassExpression | ClassDeclaration; + export type HasModifiers = TypeParameterDeclaration | ParameterDeclaration | ConstructorTypeNode | PropertySignature | PropertyDeclaration | MethodSignature | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | IndexSignatureDeclaration | FunctionExpression | ArrowFunction | ClassExpression | VariableStatement | FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | ExportAssignment | ExportDeclaration; export interface NodeArray extends ReadonlyArray, ReadonlyTextRange { readonly hasTrailingComma: boolean; } @@ -632,6 +634,7 @@ declare namespace ts { /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | InKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OutKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; + export type ModifierLike = Modifier | Decorator; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; @@ -691,6 +694,7 @@ declare namespace ts { export interface TypeParameterDeclaration extends NamedDeclaration { readonly kind: SyntaxKind.TypeParameter; readonly parent: DeclarationWithTypeParameterChildren | InferTypeNode; + readonly modifiers?: NodeArray; readonly name: Identifier; /** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */ readonly constraint?: TypeNode; @@ -700,9 +704,9 @@ declare namespace ts { export interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { readonly kind: SignatureDeclaration["kind"]; readonly name?: PropertyName; - readonly typeParameters?: NodeArray; + readonly typeParameters?: NodeArray | undefined; readonly parameters: NodeArray; - readonly type?: TypeNode; + readonly type?: TypeNode | undefined; } export type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; export interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { @@ -728,6 +732,7 @@ declare namespace ts { export interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.Parameter; readonly parent: SignatureDeclaration; + readonly modifiers?: NodeArray; readonly dotDotDotToken?: DotDotDotToken; readonly name: BindingName; readonly questionToken?: QuestionToken; @@ -744,14 +749,15 @@ declare namespace ts { } export interface PropertySignature extends TypeElement, JSDocContainer { readonly kind: SyntaxKind.PropertySignature; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly questionToken?: QuestionToken; readonly type?: TypeNode; - initializer?: Expression; } export interface PropertyDeclaration extends ClassElement, JSDocContainer { readonly kind: SyntaxKind.PropertyDeclaration; readonly parent: ClassLikeDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly questionToken?: QuestionToken; readonly exclamationToken?: ExclamationToken; @@ -768,16 +774,12 @@ declare namespace ts { readonly kind: SyntaxKind.PropertyAssignment; readonly parent: ObjectLiteralExpression; readonly name: PropertyName; - readonly questionToken?: QuestionToken; - readonly exclamationToken?: ExclamationToken; readonly initializer: Expression; } export interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.ShorthandPropertyAssignment; readonly parent: ObjectLiteralExpression; readonly name: Identifier; - readonly questionToken?: QuestionToken; - readonly exclamationToken?: ExclamationToken; readonly equalsToken?: EqualsToken; readonly objectAssignmentInitializer?: Expression; } @@ -812,34 +814,38 @@ declare namespace ts { */ export interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { _functionLikeDeclarationBrand: any; - readonly asteriskToken?: AsteriskToken; - readonly questionToken?: QuestionToken; - readonly exclamationToken?: ExclamationToken; - readonly body?: Block | Expression; + readonly asteriskToken?: AsteriskToken | undefined; + readonly questionToken?: QuestionToken | undefined; + readonly exclamationToken?: ExclamationToken | undefined; + readonly body?: Block | Expression | undefined; } export type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; /** @deprecated Use SignatureDeclaration */ export type FunctionLike = SignatureDeclaration; export interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { readonly kind: SyntaxKind.FunctionDeclaration; + readonly modifiers?: NodeArray; readonly name?: Identifier; readonly body?: FunctionBody; } export interface MethodSignature extends SignatureDeclarationBase, TypeElement { readonly kind: SyntaxKind.MethodSignature; readonly parent: ObjectTypeDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; } export interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.MethodDeclaration; readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly modifiers?: NodeArray | undefined; readonly name: PropertyName; - readonly body?: FunctionBody; + readonly body?: FunctionBody | undefined; } export interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { readonly kind: SyntaxKind.Constructor; readonly parent: ClassLikeDeclaration; - readonly body?: FunctionBody; + readonly modifiers?: NodeArray | undefined; + readonly body?: FunctionBody | undefined; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ export interface SemicolonClassElement extends ClassElement { @@ -849,12 +855,14 @@ declare namespace ts { export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.GetAccessor; readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly body?: FunctionBody; } export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.SetAccessor; readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly body?: FunctionBody; } @@ -862,6 +870,7 @@ declare namespace ts { export interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { readonly kind: SyntaxKind.IndexSignature; readonly parent: ObjectTypeDeclaration; + readonly modifiers?: NodeArray; readonly type: TypeNode; } export interface ClassStaticBlockDeclaration extends ClassElement, JSDocContainer { @@ -901,6 +910,7 @@ declare namespace ts { } export interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase { readonly kind: SyntaxKind.ConstructorType; + readonly modifiers?: NodeArray; } export interface NodeWithTypeArguments extends TypeNode { readonly typeArguments?: NodeArray; @@ -1157,11 +1167,13 @@ declare namespace ts { export type ConciseBody = FunctionBody | Expression; export interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.FunctionExpression; + readonly modifiers?: NodeArray; readonly name?: Identifier; readonly body: FunctionBody; } export interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.ArrowFunction; + readonly modifiers?: NodeArray; readonly equalsGreaterThanToken: EqualsGreaterThanToken; readonly body: ConciseBody; readonly name: never; @@ -1388,8 +1400,9 @@ declare namespace ts { readonly kind: SyntaxKind.JsxAttribute; readonly parent: JsxAttributes; readonly name: Identifier; - readonly initializer?: StringLiteral | JsxExpression; + readonly initializer?: JsxAttributeValue; } + export type JsxAttributeValue = StringLiteral | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; export interface JsxSpreadAttribute extends ObjectLiteralElement { readonly kind: SyntaxKind.JsxSpreadAttribute; readonly parent: JsxAttributes; @@ -1442,6 +1455,7 @@ declare namespace ts { } export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; + readonly modifiers?: NodeArray; readonly declarationList: VariableDeclarationList; } export interface ExpressionStatement extends Statement { @@ -1558,11 +1572,13 @@ declare namespace ts { } export interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { readonly kind: SyntaxKind.ClassDeclaration; + readonly modifiers?: NodeArray; /** May be undefined in `export default class { ... }`. */ readonly name?: Identifier; } export interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { readonly kind: SyntaxKind.ClassExpression; + readonly modifiers?: NodeArray; } export type ClassLikeDeclaration = ClassDeclaration | ClassExpression; export interface ClassElement extends NamedDeclaration { @@ -1572,10 +1588,11 @@ declare namespace ts { export interface TypeElement extends NamedDeclaration { _typeElementBrand: any; readonly name?: PropertyName; - readonly questionToken?: QuestionToken; + readonly questionToken?: QuestionToken | undefined; } export interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.InterfaceDeclaration; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly typeParameters?: NodeArray; readonly heritageClauses?: NodeArray; @@ -1589,6 +1606,7 @@ declare namespace ts { } export interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.TypeAliasDeclaration; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly typeParameters?: NodeArray; readonly type: TypeNode; @@ -1601,6 +1619,7 @@ declare namespace ts { } export interface EnumDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.EnumDeclaration; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly members: NodeArray; } @@ -1609,6 +1628,7 @@ declare namespace ts { export interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ModuleDeclaration; readonly parent: ModuleBody | SourceFile; + readonly modifiers?: NodeArray; readonly name: ModuleName; readonly body?: ModuleBody | JSDocNamespaceDeclaration; } @@ -1636,6 +1656,7 @@ declare namespace ts { export interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ImportEqualsDeclaration; readonly parent: SourceFile | ModuleBlock; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly isTypeOnly: boolean; readonly moduleReference: ModuleReference; @@ -1648,6 +1669,7 @@ declare namespace ts { export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; + readonly modifiers?: NodeArray; readonly importClause?: ImportClause; /** If this is not a StringLiteral it will be a grammar error. */ readonly moduleSpecifier: Expression; @@ -1692,6 +1714,7 @@ declare namespace ts { export interface ExportDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ExportDeclaration; readonly parent: SourceFile | ModuleBlock; + readonly modifiers?: NodeArray; readonly isTypeOnly: boolean; /** Will not be assigned in the case of `export * from "foo";` */ readonly exportClause?: NamedExportBindings; @@ -1759,6 +1782,7 @@ declare namespace ts { export interface ExportAssignment extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ExportAssignment; readonly parent: SourceFile; + readonly modifiers?: NodeArray; readonly isExportEquals?: boolean; readonly expression: Expression; } @@ -2072,6 +2096,12 @@ declare namespace ts { * It is _public_ so that (pre)transformers can set this field, * since it switches the builtin `node` module transform. Generally speaking, if unset, * the field is treated as though it is `ModuleKind.CommonJS`. + * + * Note that this field is only set by the module resolution process when + * `moduleResolution` is `Node16` or `NodeNext`, which is implied by the `module` setting + * of `Node16` or `NodeNext`, respectively, but may be overriden (eg, by a `moduleResolution` + * of `node`). If so, this field will be unset and source files will be considered to be + * CommonJS-output-format by the node module transformer and type checker, regardless of extension or context. */ impliedNodeFormat?: ModuleKind.ESNext | ModuleKind.CommonJS; } @@ -2396,6 +2426,7 @@ declare namespace ts { UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, NoTypeReduction = 536870912, + OmitThisParameter = 33554432, AllowThisInObjectLiteral = 32768, AllowQualifiedNameInPlaceOfIdentifier = 65536, /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ @@ -2426,6 +2457,7 @@ declare namespace ts { UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, NoTypeReduction = 536870912, + OmitThisParameter = 33554432, AllowUniqueESSymbolType = 1048576, AddUndefined = 131072, WriteArrowStyleSignature = 262144, @@ -2434,7 +2466,7 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 814775659 + NodeBuilderFlagsMask = 848330091 } export enum SymbolFormatFlags { None = 0, @@ -3402,39 +3434,35 @@ declare namespace ts { createComputedPropertyName(expression: Expression): ComputedPropertyName; updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; createTypeParameterDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; - /** @deprecated */ - createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - /** @deprecated */ - updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - createParameterDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; - updateParameterDeclaration(node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + createParameterDeclaration(modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + updateParameterDeclaration(node: ParameterDeclaration, modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; createDecorator(expression: Expression): Decorator; updateDecorator(node: Decorator, expression: Expression): Decorator; createPropertySignature(modifiers: readonly Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature; updatePropertySignature(node: PropertySignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature; - createPropertyDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; - updatePropertyDeclaration(node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + createPropertyDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + updatePropertyDeclaration(node: PropertyDeclaration, modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; createMethodSignature(modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): MethodSignature; updateMethodSignature(node: MethodSignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): MethodSignature; - createMethodDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; - updateMethodDeclaration(node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; - createConstructorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; - updateConstructorDeclaration(node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; - createGetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - updateGetAccessorDeclaration(node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - createSetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; - updateSetAccessorDeclaration(node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + createMethodDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + updateMethodDeclaration(node: MethodDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + createConstructorDeclaration(modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + updateConstructorDeclaration(node: ConstructorDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + createGetAccessorDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + updateGetAccessorDeclaration(node: GetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + createSetAccessorDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + updateSetAccessorDeclaration(node: SetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; createCallSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; createConstructSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - createIndexSignature(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - updateIndexSignature(node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + createIndexSignature(modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + updateIndexSignature(node: IndexSignatureDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; createTemplateLiteralTypeSpan(type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan; updateTemplateLiteralTypeSpan(node: TemplateLiteralTypeSpan, type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan; - createClassStaticBlockDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; - updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; + createClassStaticBlockDeclaration(body: Block): ClassStaticBlockDeclaration; + updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, body: Block): ClassStaticBlockDeclaration; createKeywordTypeNode(kind: TKind): KeywordTypeNode; createTypePredicateNode(assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode | string, type: TypeNode | undefined): TypePredicateNode; updateTypePredicateNode(node: TypePredicateNode, assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode, type: TypeNode | undefined): TypePredicateNode; @@ -3443,11 +3471,7 @@ declare namespace ts { createFunctionTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): FunctionTypeNode; updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): FunctionTypeNode; createConstructorTypeNode(modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; - /** @deprecated */ - createConstructorTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; updateConstructorTypeNode(node: ConstructorTypeNode, modifiers: readonly Modifier[] | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; - /** @deprecated */ - updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; createTypeQueryNode(exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode; updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode; createTypeLiteralNode(members: readonly TypeElement[] | undefined): TypeLiteralNode; @@ -3470,9 +3494,7 @@ declare namespace ts { updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode; updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode; - createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; createImportTypeNode(argument: TypeNode, assertions?: ImportTypeAssertionContainer, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; - updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; @@ -3552,8 +3574,8 @@ declare namespace ts { updateYieldExpression(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression | undefined): YieldExpression; createSpreadElement(expression: Expression): SpreadElement; updateSpreadElement(node: SpreadElement, expression: Expression): SpreadElement; - createClassExpression(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; - updateClassExpression(node: ClassExpression, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + createClassExpression(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + updateClassExpression(node: ClassExpression, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; createOmittedExpression(): OmittedExpression; createExpressionWithTypeArguments(expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments; updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments; @@ -3608,28 +3630,28 @@ declare namespace ts { updateVariableDeclaration(node: VariableDeclaration, name: BindingName, exclamationToken: ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; createVariableDeclarationList(declarations: readonly VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; updateVariableDeclarationList(node: VariableDeclarationList, declarations: readonly VariableDeclaration[]): VariableDeclarationList; - createFunctionDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - updateFunctionDeclaration(node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - createClassDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; - updateClassDeclaration(node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; - createInterfaceDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; - updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; - createTypeAliasDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; - updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; - createEnumDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; - updateEnumDeclaration(node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; - createModuleDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; - updateModuleDeclaration(node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + createFunctionDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + updateFunctionDeclaration(node: FunctionDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + createClassDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + updateClassDeclaration(node: ClassDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + createInterfaceDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + updateInterfaceDeclaration(node: InterfaceDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + createTypeAliasDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + updateTypeAliasDeclaration(node: TypeAliasDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + createEnumDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + updateEnumDeclaration(node: EnumDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + createModuleDeclaration(modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + updateModuleDeclaration(node: ModuleDeclaration, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; createModuleBlock(statements: readonly Statement[]): ModuleBlock; updateModuleBlock(node: ModuleBlock, statements: readonly Statement[]): ModuleBlock; createCaseBlock(clauses: readonly CaseOrDefaultClause[]): CaseBlock; updateCaseBlock(node: CaseBlock, clauses: readonly CaseOrDefaultClause[]): CaseBlock; createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; - createImportEqualsDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - createImportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; - updateImportDeclaration(node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + createImportEqualsDeclaration(modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + updateImportEqualsDeclaration(node: ImportEqualsDeclaration, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + createImportDeclaration(modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; + updateImportDeclaration(node: ImportDeclaration, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; createAssertClause(elements: NodeArray, multiLine?: boolean): AssertClause; @@ -3646,10 +3668,10 @@ declare namespace ts { updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports; createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - createExportAssignment(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; - updateExportAssignment(node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; - createExportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; - updateExportDeclaration(node: ExportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; + createExportAssignment(modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + updateExportAssignment(node: ExportAssignment, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + createExportDeclaration(modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; + updateExportDeclaration(node: ExportDeclaration, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; createNamedExports(elements: readonly ExportSpecifier[]): NamedExports; updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports; createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; @@ -3746,8 +3768,8 @@ declare namespace ts { createJsxOpeningFragment(): JsxOpeningFragment; createJsxJsxClosingFragment(): JsxClosingFragment; updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment): JsxFragment; - createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression | undefined): JsxAttribute; - updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression | undefined): JsxAttribute; + createJsxAttribute(name: Identifier, initializer: JsxAttributeValue | undefined): JsxAttribute; + updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: JsxAttributeValue | undefined): JsxAttribute; createJsxAttributes(properties: readonly JsxAttributeLike[]): JsxAttributes; updateJsxAttributes(node: JsxAttributes, properties: readonly JsxAttributeLike[]): JsxAttributes; createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; @@ -4055,7 +4077,7 @@ declare namespace ts { NoSpaceIfEmpty = 524288, SingleElement = 1048576, SpaceAfterList = 2097152, - Modifiers = 262656, + Modifiers = 2359808, HeritageClauses = 512, SingleLineTypeLiteralMembers = 768, MultiLineTypeLiteralMembers = 32897, @@ -4119,9 +4141,12 @@ declare namespace ts { readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; readonly includeInlayFunctionParameterTypeHints?: boolean; readonly includeInlayVariableTypeHints?: boolean; + readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; readonly includeInlayPropertyDeclarationTypeHints?: boolean; readonly includeInlayFunctionLikeReturnTypeHints?: boolean; readonly includeInlayEnumMemberValueHints?: boolean; + readonly allowRenameOfImportPath?: boolean; + readonly autoImportFileExcludePatterns?: string[]; } /** Represents a bigint literal value without requiring bigint support */ export interface PseudoBigInt { @@ -4138,7 +4163,7 @@ declare namespace ts { Changed = 1, Deleted = 2 } - export type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; + export type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind, modifiedTime?: Date) => void; export type DirectoryWatcherCallback = (fileName: string) => void; export interface System { args: string[]; @@ -4349,6 +4374,8 @@ declare namespace ts { function symbolName(symbol: Symbol): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined; function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined; + function getDecorators(node: HasDecorators): readonly Decorator[] | undefined; + function getModifiers(node: HasModifiers): readonly Modifier[] | undefined; /** * Gets the JSDoc parameter tags for the node if present. * @@ -4437,6 +4464,12 @@ declare namespace ts { /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + * + * This does *not* return type parameters from a jsdoc reference to a generic type, eg + * + * type Id = (x: T) => T + * /** @type {Id} / + * function id(x) { return x } */ function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[]; function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; @@ -4482,6 +4515,7 @@ declare namespace ts { function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; + function isModifierLike(node: Node): node is ModifierLike; function isTypeElement(node: Node): node is TypeElement; function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement; function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; @@ -4510,6 +4544,8 @@ declare namespace ts { function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; function isStringLiteralLike(node: Node): node is StringLiteralLike; function isJSDocLinkLike(node: Node): node is JSDocLink | JSDocLinkCode | JSDocLinkPlain; + function hasRestParameter(s: SignatureDeclaration | JSDocSignature): boolean; + function isRestParameter(node: ParameterDeclaration | JSDocParameterTag): boolean; } declare namespace ts { const factory: NodeFactory; @@ -4720,6 +4756,7 @@ declare namespace ts { function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; function isImportDeclaration(node: Node): node is ImportDeclaration; function isImportClause(node: Node): node is ImportClause; + function isImportTypeAssertionContainer(node: Node): node is ImportTypeAssertionContainer; function isAssertClause(node: Node): node is AssertClause; function isAssertEntry(node: Node): node is AssertEntry; function isNamespaceImport(node: Node): node is NamespaceImport; @@ -4797,6 +4834,8 @@ declare namespace ts { } declare namespace ts { function setTextRange(range: T, location: TextRange | undefined): T; + function canHaveModifiers(node: Node): node is HasModifiers; + function canHaveDecorators(node: Node): node is HasDecorators; } declare namespace ts { /** @@ -5098,6 +5137,31 @@ declare namespace ts { export function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; export function formatDiagnosticsWithColorAndContext(diagnostics: readonly Diagnostic[], host: FormatDiagnosticsHost): string; export function flattenDiagnosticMessageText(diag: string | DiagnosticMessageChain | undefined, newLine: string, indent?: number): string; + /** + * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly + * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. + */ + export function getModeForFileReference(ref: FileReference | string, containingFileMode: SourceFile["impliedNodeFormat"]): ModuleKind.CommonJS | ModuleKind.ESNext | undefined; + /** + * Calculates the final resolution mode for an import at some index within a file's imports list. This is generally the explicitly + * defined mode of the import if provided, or, if not, the mode of the containing file (with some exceptions: import=require is always commonjs, dynamic import is always esm). + * If you have an actual import node, prefer using getModeForUsageLocation on the reference string node. + * @param file File to fetch the resolution mode within + * @param index Index into the file's complete resolution list to get the resolution of - this is a concatenation of the file's imports and module augmentations + */ + export function getModeForResolutionAtIndex(file: SourceFile, index: number): ModuleKind.CommonJS | ModuleKind.ESNext | undefined; + /** + * Calculates the final resolution mode for a given module reference node. This is generally the explicitly provided resolution mode, if + * one exists, or the mode of the containing source file. (Excepting import=require, which is always commonjs, and dynamic import, which is always esm). + * Notably, this function always returns `undefined` if the containing file has an `undefined` `impliedNodeFormat` - this field is only set when + * `moduleResolution` is `node16`+. + * @param file The file the import or import-like reference is contained within + * @param usage The module reference string + * @returns The final resolution mode of the import + */ + export function getModeForUsageLocation(file: { + impliedNodeFormat?: SourceFile["impliedNodeFormat"]; + }, usage: StringLiteralLike): ModuleKind.CommonJS | ModuleKind.ESNext | undefined; export function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): readonly Diagnostic[]; /** * A function for determining if a given file is esm or cjs format, assuming modern node module resolution rules, as configured by the @@ -5357,6 +5421,10 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile?: SourceFile): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: SourceFile["impliedNodeFormat"] | undefined): (ResolvedTypeReferenceDirective | undefined)[]; + /** + * Returns the module resolution cache used by a provided `resolveModuleNames` implementation so that any non-name module resolution operations (eg, package.json lookup) can reuse it + */ + getModuleResolutionCache?(): ModuleResolutionCache | undefined; } interface WatchCompilerHost extends ProgramHost, WatchHost { /** Instead of using output d.ts file from project reference, use its source file */ @@ -5871,6 +5939,8 @@ declare namespace ts { getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; + getRenameInfo(fileName: string, position: number, preferences: UserPreferences): RenameInfo; + /** @deprecated Use the signature with `UserPreferences` instead. */ getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo; findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): readonly RenameLocation[] | undefined; getSmartSelectionRange(fileName: string, position: number): SelectionRange; @@ -6250,6 +6320,7 @@ declare namespace ts { Insert = "insert", Remove = "remove" } + /** @deprecated - consider using EditorSettings instead */ interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -6267,6 +6338,7 @@ declare namespace ts { indentStyle?: IndentStyle; trimTrailingWhitespace?: boolean; } + /** @deprecated - consider using FormatCodeSettings instead */ interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; InsertSpaceAfterSemicolonInForStatements: boolean; @@ -6392,6 +6464,9 @@ declare namespace ts { canRename: false; localizedErrorMessage: string; } + /** + * @deprecated Use `UserPreferences` instead. + */ interface RenameInfoOptions { readonly allowRenameOfImportPath?: boolean; } @@ -6829,8 +6904,8 @@ declare namespace ts { * @param version Current version of the file. Only used if the file was not found * in the registry and a new one was created. */ - acquireDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; - acquireDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + acquireDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; + acquireDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; /** * Request an updated version of an already existing SourceFile with a given fileName * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile @@ -6846,8 +6921,8 @@ declare namespace ts { * @param scriptSnapshot Text of the file. * @param version Current version of the file. */ - updateDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; - updateDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + updateDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; + updateDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey; /** * Informs the DocumentRegistry that a file is not needed any longer. @@ -6857,9 +6932,10 @@ declare namespace ts { * * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file + * @param scriptKind The script kind of the file to be released */ - /**@deprecated pass scriptKind for correctness */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /**@deprecated pass scriptKind and impliedNodeFormat for correctness */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind?: ScriptKind): void; /** * Informs the DocumentRegistry that a file is not needed any longer. * @@ -6869,12 +6945,13 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file * @param scriptKind The script kind of the file to be released + * @param impliedNodeFormat The implied source file format of the file to be released */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind, impliedNodeFormat: SourceFile["impliedNodeFormat"]): void; /** - * @deprecated pass scriptKind for correctness */ - releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; - releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; + * @deprecated pass scriptKind for and impliedNodeFormat correctness */ + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind?: ScriptKind): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind, impliedNodeFormat: SourceFile["impliedNodeFormat"]): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { @@ -6934,7 +7011,7 @@ declare namespace ts.server { compressionKind: string; data: any; } - type RequireResult = { + type ModuleImportResult = { module: {}; error: undefined; } | { @@ -6944,6 +7021,8 @@ declare namespace ts.server { message?: string; }; }; + /** @deprecated Use {@link ModuleImportResult} instead. */ + type RequireResult = ModuleImportResult; interface ServerHost extends System { watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; @@ -6953,7 +7032,8 @@ declare namespace ts.server { clearImmediate(timeoutId: any): void; gc?(): void; trace?(s: string): void; - require?(initialPath: string, moduleName: string): RequireResult; + require?(initialPath: string, moduleName: string): ModuleImportResult; + importServicePlugin?(root: string, moduleName: string): Promise; } } declare namespace ts.server { @@ -9708,9 +9788,11 @@ declare namespace ts.server.protocol { readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; readonly includeInlayFunctionParameterTypeHints?: boolean; readonly includeInlayVariableTypeHints?: boolean; + readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; readonly includeInlayPropertyDeclarationTypeHints?: boolean; readonly includeInlayFunctionLikeReturnTypeHints?: boolean; readonly includeInlayEnumMemberValueHints?: boolean; + readonly autoImportFileExcludePatterns?: string[]; } interface CompilerOptions { allowJs?: boolean; @@ -10402,6 +10484,8 @@ declare namespace ts.server { /** Tracks projects that we have already sent telemetry for. */ private readonly seenProjects; private performanceEventHandler?; + private pendingPluginEnablements?; + private currentPluginEnablementPromise?; constructor(opts: ProjectServiceOptions); toPath(fileName: string): Path; private loadTypesMap; @@ -10561,6 +10645,9 @@ declare namespace ts.server { applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; openExternalProject(proj: protocol.ExternalProject): void; hasDeferredExtension(): boolean; + private enableRequestedPluginsAsync; + private enableRequestedPluginsWorker; + private enableRequestedPluginsForProjectAsync; configurePlugin(args: protocol.ConfigurePluginRequestArguments): void; } export {}; @@ -10841,33 +10928,69 @@ declare namespace ts { (node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; }; /** @deprecated Use `factory.createParameterDeclaration` or the factory supplied by your transformation context instead. */ - const createParameter: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined) => ParameterDeclaration; + const createParameter: { + (modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined): ParameterDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined): ParameterDeclaration; + }; /** @deprecated Use `factory.updateParameterDeclaration` or the factory supplied by your transformation context instead. */ - const updateParameter: (node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) => ParameterDeclaration; + const updateParameter: { + (node: ParameterDeclaration, modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + (node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + }; /** @deprecated Use `factory.createDecorator` or the factory supplied by your transformation context instead. */ const createDecorator: (expression: Expression) => Decorator; /** @deprecated Use `factory.updateDecorator` or the factory supplied by your transformation context instead. */ const updateDecorator: (node: Decorator, expression: Expression) => Decorator; /** @deprecated Use `factory.createPropertyDeclaration` or the factory supplied by your transformation context instead. */ - const createProperty: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) => PropertyDeclaration; + const createProperty: { + (modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + }; /** @deprecated Use `factory.updatePropertyDeclaration` or the factory supplied by your transformation context instead. */ - const updateProperty: (node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) => PropertyDeclaration; + const updateProperty: { + (node: PropertyDeclaration, modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + (node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + }; /** @deprecated Use `factory.createMethodDeclaration` or the factory supplied by your transformation context instead. */ - const createMethod: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => MethodDeclaration; + const createMethod: { + (modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + }; /** @deprecated Use `factory.updateMethodDeclaration` or the factory supplied by your transformation context instead. */ - const updateMethod: (node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => MethodDeclaration; + const updateMethod: { + (node: MethodDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + (node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + }; /** @deprecated Use `factory.createConstructorDeclaration` or the factory supplied by your transformation context instead. */ - const createConstructor: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined) => ConstructorDeclaration; + const createConstructor: { + (modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + }; /** @deprecated Use `factory.updateConstructorDeclaration` or the factory supplied by your transformation context instead. */ - const updateConstructor: (node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined) => ConstructorDeclaration; + const updateConstructor: { + (node: ConstructorDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + (node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + }; /** @deprecated Use `factory.createGetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const createGetAccessor: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => GetAccessorDeclaration; + const createGetAccessor: { + (modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + }; /** @deprecated Use `factory.updateGetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const updateGetAccessor: (node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => GetAccessorDeclaration; + const updateGetAccessor: { + (node: GetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + (node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + }; /** @deprecated Use `factory.createSetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const createSetAccessor: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined) => SetAccessorDeclaration; + const createSetAccessor: { + (modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + }; /** @deprecated Use `factory.updateSetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const updateSetAccessor: (node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined) => SetAccessorDeclaration; + const updateSetAccessor: { + (node: SetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + (node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + }; /** @deprecated Use `factory.createCallSignature` or the factory supplied by your transformation context instead. */ const createCallSignature: (typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined) => CallSignatureDeclaration; /** @deprecated Use `factory.updateCallSignature` or the factory supplied by your transformation context instead. */ @@ -10877,7 +11000,10 @@ declare namespace ts { /** @deprecated Use `factory.updateConstructSignature` or the factory supplied by your transformation context instead. */ const updateConstructSignature: (node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) => ConstructSignatureDeclaration; /** @deprecated Use `factory.updateIndexSignature` or the factory supplied by your transformation context instead. */ - const updateIndexSignature: (node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode) => IndexSignatureDeclaration; + const updateIndexSignature: { + (node: IndexSignatureDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + (node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + }; /** @deprecated Use `factory.createKeywordTypeNode` or the factory supplied by your transformation context instead. */ const createKeywordTypeNode: (kind: TKind) => KeywordTypeNode; /** @deprecated Use `factory.createTypePredicateNode` or the factory supplied by your transformation context instead. */ @@ -10938,13 +11064,14 @@ declare namespace ts { const updateInferTypeNode: (node: InferTypeNode, typeParameter: TypeParameterDeclaration) => InferTypeNode; /** @deprecated Use `factory.createImportTypeNode` or the factory supplied by your transformation context instead. */ const createImportTypeNode: { - (argument: TypeNode, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; (argument: TypeNode, assertions?: ImportTypeAssertionContainer | undefined, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; + (argument: TypeNode, assertions?: ImportTypeAssertionContainer | undefined, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; + (argument: TypeNode, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; }; /** @deprecated Use `factory.updateImportTypeNode` or the factory supplied by your transformation context instead. */ const updateImportTypeNode: { - (node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; (node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; + (node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; }; /** @deprecated Use `factory.createParenthesizedType` or the factory supplied by your transformation context instead. */ const createParenthesizedType: (type: TypeNode) => ParenthesizedTypeNode; @@ -11189,29 +11316,65 @@ declare namespace ts { /** @deprecated Use `factory.updateVariableDeclarationList` or the factory supplied by your transformation context instead. */ const updateVariableDeclarationList: (node: VariableDeclarationList, declarations: readonly VariableDeclaration[]) => VariableDeclarationList; /** @deprecated Use `factory.createFunctionDeclaration` or the factory supplied by your transformation context instead. */ - const createFunctionDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => FunctionDeclaration; + const createFunctionDeclaration: { + (modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + }; /** @deprecated Use `factory.updateFunctionDeclaration` or the factory supplied by your transformation context instead. */ - const updateFunctionDeclaration: (node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => FunctionDeclaration; + const updateFunctionDeclaration: { + (node: FunctionDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + (node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + }; /** @deprecated Use `factory.createClassDeclaration` or the factory supplied by your transformation context instead. */ - const createClassDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]) => ClassDeclaration; + const createClassDeclaration: { + (modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + }; /** @deprecated Use `factory.updateClassDeclaration` or the factory supplied by your transformation context instead. */ - const updateClassDeclaration: (node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]) => ClassDeclaration; + const updateClassDeclaration: { + (node: ClassDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + (node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + }; /** @deprecated Use `factory.createInterfaceDeclaration` or the factory supplied by your transformation context instead. */ - const createInterfaceDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]) => InterfaceDeclaration; + const createInterfaceDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + }; /** @deprecated Use `factory.updateInterfaceDeclaration` or the factory supplied by your transformation context instead. */ - const updateInterfaceDeclaration: (node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]) => InterfaceDeclaration; + const updateInterfaceDeclaration: { + (node: InterfaceDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + (node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + }; /** @deprecated Use `factory.createTypeAliasDeclaration` or the factory supplied by your transformation context instead. */ - const createTypeAliasDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode) => TypeAliasDeclaration; + const createTypeAliasDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + }; /** @deprecated Use `factory.updateTypeAliasDeclaration` or the factory supplied by your transformation context instead. */ - const updateTypeAliasDeclaration: (node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode) => TypeAliasDeclaration; + const updateTypeAliasDeclaration: { + (node: TypeAliasDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + (node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + }; /** @deprecated Use `factory.createEnumDeclaration` or the factory supplied by your transformation context instead. */ - const createEnumDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]) => EnumDeclaration; + const createEnumDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + }; /** @deprecated Use `factory.updateEnumDeclaration` or the factory supplied by your transformation context instead. */ - const updateEnumDeclaration: (node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]) => EnumDeclaration; + const updateEnumDeclaration: { + (node: EnumDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + (node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + }; /** @deprecated Use `factory.createModuleDeclaration` or the factory supplied by your transformation context instead. */ - const createModuleDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags | undefined) => ModuleDeclaration; + const createModuleDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags | undefined): ModuleDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags | undefined): ModuleDeclaration; + }; /** @deprecated Use `factory.updateModuleDeclaration` or the factory supplied by your transformation context instead. */ - const updateModuleDeclaration: (node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined) => ModuleDeclaration; + const updateModuleDeclaration: { + (node: ModuleDeclaration, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + (node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + }; /** @deprecated Use `factory.createModuleBlock` or the factory supplied by your transformation context instead. */ const createModuleBlock: (statements: readonly Statement[]) => ModuleBlock; /** @deprecated Use `factory.updateModuleBlock` or the factory supplied by your transformation context instead. */ @@ -11225,13 +11388,25 @@ declare namespace ts { /** @deprecated Use `factory.updateNamespaceExportDeclaration` or the factory supplied by your transformation context instead. */ const updateNamespaceExportDeclaration: (node: NamespaceExportDeclaration, name: Identifier) => NamespaceExportDeclaration; /** @deprecated Use `factory.createImportEqualsDeclaration` or the factory supplied by your transformation context instead. */ - const createImportEqualsDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference) => ImportEqualsDeclaration; + const createImportEqualsDeclaration: { + (modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + }; /** @deprecated Use `factory.updateImportEqualsDeclaration` or the factory supplied by your transformation context instead. */ - const updateImportEqualsDeclaration: (node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference) => ImportEqualsDeclaration; + const updateImportEqualsDeclaration: { + (node: ImportEqualsDeclaration, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + (node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + }; /** @deprecated Use `factory.createImportDeclaration` or the factory supplied by your transformation context instead. */ - const createImportDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause | undefined) => ImportDeclaration; + const createImportDeclaration: { + (modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause | undefined): ImportDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause | undefined): ImportDeclaration; + }; /** @deprecated Use `factory.updateImportDeclaration` or the factory supplied by your transformation context instead. */ - const updateImportDeclaration: (node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined) => ImportDeclaration; + const updateImportDeclaration: { + (node: ImportDeclaration, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + (node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + }; /** @deprecated Use `factory.createNamespaceImport` or the factory supplied by your transformation context instead. */ const createNamespaceImport: (name: Identifier) => NamespaceImport; /** @deprecated Use `factory.updateNamespaceImport` or the factory supplied by your transformation context instead. */ @@ -11245,9 +11420,15 @@ declare namespace ts { /** @deprecated Use `factory.updateImportSpecifier` or the factory supplied by your transformation context instead. */ const updateImportSpecifier: (node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) => ImportSpecifier; /** @deprecated Use `factory.createExportAssignment` or the factory supplied by your transformation context instead. */ - const createExportAssignment: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression) => ExportAssignment; + const createExportAssignment: { + (modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + }; /** @deprecated Use `factory.updateExportAssignment` or the factory supplied by your transformation context instead. */ - const updateExportAssignment: (node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression) => ExportAssignment; + const updateExportAssignment: { + (node: ExportAssignment, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + (node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + }; /** @deprecated Use `factory.createNamedExports` or the factory supplied by your transformation context instead. */ const createNamedExports: (elements: readonly ExportSpecifier[]) => NamedExports; /** @deprecated Use `factory.updateNamedExports` or the factory supplied by your transformation context instead. */ @@ -11337,9 +11518,9 @@ declare namespace ts { /** @deprecated Use `factory.updateJsxFragment` or the factory supplied by your transformation context instead. */ const updateJsxFragment: (node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment) => JsxFragment; /** @deprecated Use `factory.createJsxAttribute` or the factory supplied by your transformation context instead. */ - const createJsxAttribute: (name: Identifier, initializer: StringLiteral | JsxExpression | undefined) => JsxAttribute; + const createJsxAttribute: (name: Identifier, initializer: JsxAttributeValue | undefined) => JsxAttribute; /** @deprecated Use `factory.updateJsxAttribute` or the factory supplied by your transformation context instead. */ - const updateJsxAttribute: (node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression | undefined) => JsxAttribute; + const updateJsxAttribute: (node: JsxAttribute, name: Identifier, initializer: JsxAttributeValue | undefined) => JsxAttribute; /** @deprecated Use `factory.createJsxAttributes` or the factory supplied by your transformation context instead. */ const createJsxAttributes: (properties: readonly JsxAttributeLike[]) => JsxAttributes; /** @deprecated Use `factory.updateJsxAttributes` or the factory supplied by your transformation context instead. */ @@ -11551,8 +11732,12 @@ declare namespace ts { * @deprecated Use an appropriate `factory.update...` method instead, use `setCommentRange` or `setSourceMapRange`, and avoid setting `parent`. */ const getMutableClone: (node: T) => T; +} +declare namespace ts { /** @deprecated Use `isTypeAssertionExpression` instead. */ const isTypeAssertion: (node: Node) => node is TypeAssertion; +} +declare namespace ts { /** * @deprecated Use `ts.ReadonlyESMap` instead. */ @@ -11563,11 +11748,240 @@ declare namespace ts { */ interface Map extends ESMap { } +} +declare namespace ts { /** * @deprecated Use `isMemberName` instead. */ const isIdentifierOrPrivateIdentifier: (node: Node) => node is MemberName; } +declare namespace ts { + interface NodeFactory { + /** @deprecated Use the overload that accepts 'modifiers' */ + createConstructorTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; + /** @deprecated Use the overload that accepts 'modifiers' */ + updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; + } +} +declare namespace ts { + interface NodeFactory { + createImportTypeNode(argument: TypeNode, assertions?: ImportTypeAssertionContainer, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; + /** @deprecated Use the overload that accepts 'assertions' */ + createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; + /** @deprecated Use the overload that accepts 'assertions' */ + updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; + } +} +declare namespace ts { + interface NodeFactory { + /** @deprecated Use the overload that accepts 'modifiers' */ + createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + /** @deprecated Use the overload that accepts 'modifiers' */ + updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + } +} +declare namespace ts { + interface Node { + /** + * @deprecated `decorators` has been removed from `Node` and merged with `modifiers` on the `Node` subtypes that support them. + * Use `ts.canHaveDecorators()` to test whether a `Node` can have decorators. + * Use `ts.getDecorators()` to get the decorators of a `Node`. + * + * For example: + * ```ts + * const decorators = ts.canHaveDecorators(node) ? ts.getDecorators(node) : undefined; + * ``` + */ + readonly decorators?: undefined; + /** + * @deprecated `modifiers` has been removed from `Node` and moved to the `Node` subtypes that support them. + * Use `ts.canHaveModifiers()` to test whether a `Node` can have modifiers. + * Use `ts.getModifiers()` to get the modifiers of a `Node`. + * + * For example: + * ```ts + * const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined; + * ``` + */ + readonly modifiers?: NodeArray | undefined; + } + interface PropertySignature { + /** @deprecated A property signature cannot have an initializer */ + readonly initializer?: Expression | undefined; + } + interface PropertyAssignment { + /** @deprecated A property assignment cannot have a question token */ + readonly questionToken?: QuestionToken | undefined; + /** @deprecated A property assignment cannot have an exclamation token */ + readonly exclamationToken?: ExclamationToken | undefined; + } + interface ShorthandPropertyAssignment { + /** @deprecated A shorthand property assignment cannot have modifiers */ + readonly modifiers?: NodeArray | undefined; + /** @deprecated A shorthand property assignment cannot have a question token */ + readonly questionToken?: QuestionToken | undefined; + /** @deprecated A shorthand property assignment cannot have an exclamation token */ + readonly exclamationToken?: ExclamationToken | undefined; + } + interface FunctionTypeNode { + /** @deprecated A function type cannot have modifiers */ + readonly modifiers?: NodeArray | undefined; + } + interface NodeFactory { + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createParameterDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateParameterDeclaration(node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createPropertyDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updatePropertyDeclaration(node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createMethodDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateMethodDeclaration(node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + /** + * @deprecated This node does not support Decorators. Callers should use an overload that does not accept a `decorators` parameter. + */ + createConstructorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + /** + * @deprecated This node does not support Decorators. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateConstructorDeclaration(node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createGetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateGetAccessorDeclaration(node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createSetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateSetAccessorDeclaration(node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createIndexSignature(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + /** + * @deprecated Decorators and modifiers are no longer supported for this function. Callers should use an overload that does not accept the `decorators` and `modifiers` parameters. + */ + updateIndexSignature(node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + /** + * @deprecated Decorators and modifiers are no longer supported for this function. Callers should use an overload that does not accept the `decorators` and `modifiers` parameters. + */ + createClassStaticBlockDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createClassExpression(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassExpression(node: ClassExpression, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createFunctionDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateFunctionDeclaration(node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createClassDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassDeclaration(node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createInterfaceDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createTypeAliasDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createEnumDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateEnumDeclaration(node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createModuleDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateModuleDeclaration(node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createImportEqualsDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createImportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateImportDeclaration(node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createExportAssignment(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateExportAssignment(node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createExportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateExportDeclaration(node: ExportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; + } +} export = ts; export as namespace ts; \ No newline at end of file diff --git a/tsserver/tsserverlibrary.js b/tsserver/tsserverlibrary.js index 54c7b529..57276bce 100644 --- a/tsserver/tsserverlibrary.js +++ b/tsserver/tsserverlibrary.js @@ -91,6 +91,15 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; /* @internal */ var ts; (function (ts) { @@ -290,11 +299,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.7"; + ts.versionMajorMinor = "4.8"; // 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 = "4.7.2"; + ts.version = "4.8.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -500,8 +509,10 @@ var ts; return true; } ts.every = every; - function find(array, predicate) { - for (var i = 0; i < array.length; i++) { + function find(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { var value = array[i]; if (predicate(value, i)) { return value; @@ -510,8 +521,10 @@ var ts; return undefined; } ts.find = find; - function findLast(array, predicate) { - for (var i = array.length - 1; i >= 0; i--) { + function findLast(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { var value = array[i]; if (predicate(value, i)) { return value; @@ -522,7 +535,9 @@ var ts; ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate, startIndex) { - for (var i = startIndex || 0; i < array.length; i++) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -531,7 +546,9 @@ var ts; } ts.findIndex = findIndex; function findLastIndex(array, predicate, startIndex) { - for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { if (predicate(array[i], i)) { return i; } @@ -1309,7 +1326,7 @@ var ts; * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return array.length === 0 ? undefined : array[0]; + return array === undefined || array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -1321,7 +1338,7 @@ var ts; * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return array.length === 0 ? undefined : array[array.length - 1]; + return array === undefined || array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -1662,6 +1679,43 @@ var ts; return createMultiMap(); } ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; + function createQueue(items) { + var elements = (items === null || items === void 0 ? void 0 : items.slice()) || []; + var headIndex = 0; + function isEmpty() { + return headIndex === elements.length; + } + function enqueue() { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + elements.push.apply(elements, items); + } + function dequeue() { + if (isEmpty()) { + throw new Error("Queue is empty"); + } + var result = elements[headIndex]; + elements[headIndex] = undefined; // Don't keep referencing dequeued item + headIndex++; + // If more than half of the queue is empty, copy the remaining elements to the + // front and shrink the array (unless we'd be saving fewer than 100 slots) + if (headIndex > 100 && headIndex > (elements.length >> 1)) { + var newLength = elements.length - headIndex; + elements.copyWithin(/*target*/ 0, /*start*/ headIndex); + elements.length = newLength; + headIndex = 0; + } + return result; + } + return { + enqueue: enqueue, + dequeue: dequeue, + isEmpty: isEmpty, + }; + } + ts.createQueue = createQueue; /** * Creates a Set with custom equality and hash code functionality. This is useful when you * want to use something looser than object identity - e.g. "has the same span". @@ -1850,6 +1904,10 @@ var ts; /** Does nothing. */ function noop(_) { } ts.noop = noop; + ts.noopPush = { + push: noop, + length: 0 + }; /** Do nothing and return false */ function returnFalse() { return false; @@ -2205,7 +2263,7 @@ var ts; * and 1 insertion/deletion at 3 characters) */ function getSpellingSuggestion(name, candidates, getName) { - var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var maximumLengthDifference = Math.max(2, Math.floor(name.length * 0.34)); var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother. var bestCandidate; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -2432,6 +2490,7 @@ var ts; startsWith(candidate, prefix) && endsWith(candidate, suffix); } + ts.isPatternMatch = isPatternMatch; function and(f, g) { return function (arg) { return f(arg) && g(arg); }; } @@ -2624,6 +2683,7 @@ var ts; var currentAssertionLevel = 0 /* AssertionLevel.None */; Debug.currentLogLevel = LogLevel.Warning; Debug.isDebugging = false; + Debug.enableDeprecationWarnings = true; function getTypeScriptVersion() { return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version)); } @@ -2842,7 +2902,7 @@ var ts; return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; } if (isFlags) { - var result = ""; + var result = []; var remainingFlags = value; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; @@ -2850,12 +2910,12 @@ var ts; break; } if (enumValue !== 0 && enumValue & value) { - result = "".concat(result).concat(result ? "|" : "").concat(enumName); + result.push(enumName); remainingFlags &= ~enumValue; } } if (remainingFlags === 0) { - return result; + return result.join("|"); } } else { @@ -2869,7 +2929,15 @@ var ts; return value.toString(); } Debug.formatEnum = formatEnum; + var enumMemberCache = new ts.Map(); function getEnumMembers(enumObject) { + // Assuming enum objects do not change at runtime, we can cache the enum members list + // to reuse later. This saves us from reconstructing this each and every time we call + // a formatting function (which can be expensive for large enums like SyntaxKind). + var existing = enumMemberCache.get(enumObject); + if (existing) { + return existing; + } var result = []; for (var name in enumObject) { var value = enumObject[name]; @@ -2877,7 +2945,9 @@ var ts; result.push([value, name]); } } - return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + var sorted = ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + enumMemberCache.set(enumObject, sorted); + return sorted; } function formatSyntaxKind(kind) { return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); @@ -2923,6 +2993,22 @@ var ts; return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true); } Debug.formatFlowFlags = formatFlowFlags; + function formatRelationComparisonResult(result) { + return formatEnum(result, ts.RelationComparisonResult, /*isFlags*/ true); + } + Debug.formatRelationComparisonResult = formatRelationComparisonResult; + function formatCheckMode(mode) { + return formatEnum(mode, ts.CheckMode, /*isFlags*/ true); + } + Debug.formatCheckMode = formatCheckMode; + function formatSignatureCheckMode(mode) { + return formatEnum(mode, ts.SignatureCheckMode, /*isFlags*/ true); + } + Debug.formatSignatureCheckMode = formatSignatureCheckMode; + function formatTypeFacts(facts) { + return formatEnum(facts, ts.TypeFacts, /*isFlags*/ true); + } + Debug.formatTypeFacts = formatTypeFacts; var isDebugInfoEnabled = false; var extendedDebugModule; function extendedDebug() { @@ -3221,7 +3307,7 @@ var ts; function createWarningDeprecation(name, errorAfter, since, message) { var hasWrittenDeprecation = false; return function () { - if (!hasWrittenDeprecation) { + if (Debug.enableDeprecationWarnings && !hasWrittenDeprecation) { log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message)); hasWrittenDeprecation = true; } @@ -3240,6 +3326,7 @@ var ts; warn ? createWarningDeprecation(name, errorAfter, since, options.message) : ts.noop; } + Debug.createDeprecation = createDeprecation; function wrapFunction(deprecation, func) { return function () { deprecation(); @@ -3247,10 +3334,53 @@ var ts; }; } function deprecate(func, options) { - var deprecation = createDeprecation(getFunctionName(func), options); + var _a; + var deprecation = createDeprecation((_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : getFunctionName(func), options); return wrapFunction(deprecation, func); } Debug.deprecate = deprecate; + function formatVariance(varianceFlags) { + var variance = varianceFlags & 7 /* VarianceFlags.VarianceMask */; + var result = variance === 0 /* VarianceFlags.Invariant */ ? "in out" : + variance === 3 /* VarianceFlags.Bivariant */ ? "[bivariant]" : + variance === 2 /* VarianceFlags.Contravariant */ ? "in" : + variance === 1 /* VarianceFlags.Covariant */ ? "out" : + variance === 4 /* VarianceFlags.Independent */ ? "[independent]" : ""; + if (varianceFlags & 8 /* VarianceFlags.Unmeasurable */) { + result += " (unmeasurable)"; + } + else if (varianceFlags & 16 /* VarianceFlags.Unreliable */) { + result += " (unreliable)"; + } + return result; + } + Debug.formatVariance = formatVariance; + var DebugTypeMapper = /** @class */ (function () { + function DebugTypeMapper() { + } + DebugTypeMapper.prototype.__debugToString = function () { + var _a; + type(this); + switch (this.kind) { + case 3 /* TypeMapKind.Function */: return ((_a = this.debugInfo) === null || _a === void 0 ? void 0 : _a.call(this)) || "(function mapper)"; + case 0 /* TypeMapKind.Simple */: return "".concat(this.source.__debugTypeToString(), " -> ").concat(this.target.__debugTypeToString()); + case 1 /* TypeMapKind.Array */: return ts.zipWith(this.sources, this.targets || ts.map(this.sources, function () { return "any"; }), function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(typeof t === "string" ? t : t.__debugTypeToString()); }).join(", "); + case 2 /* TypeMapKind.Deferred */: return ts.zipWith(this.sources, this.targets, function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(t().__debugTypeToString()); }).join(", "); + case 5 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: return "m1: ".concat(this.mapper1.__debugToString().split("\n").join("\n "), "\nm2: ").concat(this.mapper2.__debugToString().split("\n").join("\n ")); + default: return assertNever(this); + } + }; + return DebugTypeMapper; + }()); + Debug.DebugTypeMapper = DebugTypeMapper; + function attachDebugPrototypeIfDebug(mapper) { + if (Debug.isDebugging) { + return Object.setPrototypeOf(mapper, DebugTypeMapper.prototype); + } + return mapper; + } + Debug.attachDebugPrototypeIfDebug = attachDebugPrototypeIfDebug; })(Debug = ts.Debug || (ts.Debug = {})); })(ts || (ts = {})); /* @internal */ @@ -3992,9 +4122,9 @@ var ts; eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } tracingEnabled.push = push; - function pop() { + function pop(results) { ts.Debug.assert(eventStack.length > 0); - writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); + writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp(), results); eventStack.length--; } tracingEnabled.pop = pop; @@ -4008,14 +4138,15 @@ var ts; tracingEnabled.popAll = popAll; // sample every 10ms var sampleInterval = 1000 * 10; - function writeStackEvent(index, endTime) { + function writeStackEvent(index, endTime, results) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { + ts.Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`"); writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } // test if [time,endTime) straddles a sampling point else if (sampleInterval - (time % sampleInterval) <= endTime - time) { - writeEvent("X", phase, name, args, "\"dur\":".concat(endTime - time), time); + writeEvent("X", phase, name, __assign(__assign({}, args), { results: results }), "\"dur\":".concat(endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { @@ -4514,6 +4645,7 @@ var ts; SyntaxKind[SyntaxKind["JSDocFunctionType"] = 317] = "JSDocFunctionType"; SyntaxKind[SyntaxKind["JSDocVariadicType"] = 318] = "JSDocVariadicType"; SyntaxKind[SyntaxKind["JSDocNamepathType"] = 319] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; /** @deprecated Use SyntaxKind.JSDoc */ SyntaxKind[SyntaxKind["JSDocComment"] = 320] = "JSDocComment"; SyntaxKind[SyntaxKind["JSDocText"] = 321] = "JSDocText"; @@ -4588,7 +4720,6 @@ var ts; SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 347] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 126] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 160] = "LastContextualKeyword"; - SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4662,6 +4793,7 @@ var ts; ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["In"] = 32768] = "In"; ModifierFlags[ModifierFlags["Out"] = 65536] = "Out"; + ModifierFlags[ModifierFlags["Decorator"] = 131072] = "Decorator"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. @@ -4669,7 +4801,8 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 116958] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 125951] = "All"; + ModifierFlags[ModifierFlags["All"] = 257023] = "All"; + ModifierFlags[ModifierFlags["Modifier"] = 125951] = "Modifier"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4854,6 +4987,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + NodeBuilderFlags[NodeBuilderFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; @@ -4894,6 +5028,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + TypeFormatFlags[TypeFormatFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -4905,7 +5040,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 848330091] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -5294,6 +5429,11 @@ var ts; // Flags that require TypeFlags.Union /* @internal */ ObjectFlags[ObjectFlags["ContainsIntersections"] = 16777216] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnionComputed"] = 33554432] = "IsUnknownLikeUnionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnion"] = 67108864] = "IsUnknownLikeUnion"; + /* @internal */ // Flags that require TypeFlags.Intersection /* @internal */ ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 16777216] = "IsNeverIntersectionComputed"; @@ -5379,9 +5519,10 @@ var ts; (function (TypeMapKind) { TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple"; TypeMapKind[TypeMapKind["Array"] = 1] = "Array"; - TypeMapKind[TypeMapKind["Function"] = 2] = "Function"; - TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite"; - TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged"; + TypeMapKind[TypeMapKind["Deferred"] = 2] = "Deferred"; + TypeMapKind[TypeMapKind["Function"] = 3] = "Function"; + TypeMapKind[TypeMapKind["Composite"] = 4] = "Composite"; + TypeMapKind[TypeMapKind["Merged"] = 5] = "Merged"; })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {})); var InferencePriority; (function (InferencePriority) { @@ -5760,25 +5901,24 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 4096] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; - TransformFlags[TransformFlags["ContainsLexicalSuper"] = 33554432] = "ContainsLexicalSuper"; - TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 67108864] = "ContainsUpdateExpressionForIdentifier"; - // Please leave this as 1 << 29. - // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. - // It is a good reminder of how much room we have left - TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 8192] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 32768] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 65536] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 131072] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 262144] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 524288] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 1048576] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 2097152] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 4194304] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 8388608] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 16777216] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsDecorators"] = 33554432] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 67108864] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsLexicalSuper"] = 134217728] = "ContainsLexicalSuper"; + TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 268435456] = "ContainsUpdateExpressionForIdentifier"; + TransformFlags[TransformFlags["ContainsPrivateIdentifierInExpression"] = 536870912] = "ContainsPrivateIdentifierInExpression"; + TransformFlags[TransformFlags["HasComputedFlags"] = -2147483648] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; @@ -5797,27 +5937,27 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 591310848] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 591306752] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 574529536] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 570433536] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 589443072] = "ModuleExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = -2147483648] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = -2147483648] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = -2147483648] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = -2072174592] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = -1937940480] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = -1937948672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = -2005057536] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = -2013249536] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = -2147344384] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = -1941676032] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; - TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 33562624] = "ContainsLexicalThisOrSuper"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = -2147278848] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = -2147450880] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = -2146893824] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = -2147483648] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = -2147418112] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = -2147450880] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 134234112] = "ContainsLexicalThisOrSuper"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 33562624] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 134234112] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -5990,7 +6130,7 @@ var ts; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["Modifiers"] = 2359808] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; @@ -6385,7 +6525,7 @@ var ts; }; } function createDirectoryWatcher(dirName, dirPath, fallbackOptions) { - var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName) { + var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName, modifiedTime) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" if (!ts.isString(relativeFileName)) return; @@ -6395,7 +6535,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); + fileCallback(fileName, FileWatcherEventKind.Changed, modifiedTime); } } }, @@ -6449,7 +6589,7 @@ var ts; } else { cache.set(path, { - watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options), + watcher: watchFile(fileName, function (fileName, eventKind, modifiedTime) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind, modifiedTime); }); }, pollingInterval, options), refCount: 1 }); } @@ -6477,7 +6617,8 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + // Pass modified times so tsc --build can use it + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime), modifiedTime); return true; } return false; @@ -6512,7 +6653,7 @@ var ts; */ /*@internal*/ function createDirectoryWatcherSupportingRecursive(_a) { - var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, directoryExists = _a.directoryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, fileSystemEntryExists = _a.fileSystemEntryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; var cache = new ts.Map(); var callbackCache = ts.createMultiMap(); var cacheToUpdateChildWatches = new ts.Map(); @@ -6612,7 +6753,7 @@ var ts; function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) { // Iterate through existing children and update the watches if needed var parentWatcher = cache.get(dirPath); - if (parentWatcher && directoryExists(dirName)) { + if (parentWatcher && fileSystemEntryExists(dirName, 1 /* FileSystemEntryKind.Directory */)) { // Schedule the update and postpone invoke for callbacks scheduleUpdateChildWatches(dirName, dirPath, fileName, options); return; @@ -6685,7 +6826,7 @@ var ts; if (!parentWatcher) return false; var newChildWatches; - var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { + var hasChanges = ts.enumerateInsertsAndDeletes(fileSystemEntryExists(parentDir, 1 /* FileSystemEntryKind.Directory */) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch @@ -6728,17 +6869,19 @@ var ts; })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {})); /*@internal*/ function createFileWatcherCallback(callback) { - return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + return function (_fileName, eventKind, modifiedTime) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", "", modifiedTime); }; } ts.createFileWatcherCallback = createFileWatcherCallback; - function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) { - return function (eventName) { + function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime) { + return function (eventName, _relativeFileName, modifiedTime) { if (eventName === "rename") { - callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + // Check time stamps rather than file system entry checks + modifiedTime || (modifiedTime = getModifiedTime(fileName) || ts.missingFileModifiedTime); + callback(fileName, modifiedTime !== ts.missingFileModifiedTime ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted, modifiedTime); } else { // Change - callback(fileName, FileWatcherEventKind.Changed); + callback(fileName, FileWatcherEventKind.Changed, modifiedTime); } }; } @@ -6762,11 +6905,12 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; + var pollingWatchFile = _a.pollingWatchFile, 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 dynamicPollingWatchFile; var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; + var hitSystemWatcherLimit = false; return { watchFile: watchFile, watchDirectory: watchDirectory @@ -6784,7 +6928,7 @@ var ts; case ts.WatchFileKind.FixedChunkSizePolling: return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: - return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), + return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); case ts.WatchFileKind.UseFsEventsOnParentDirectory: if (!nonPollingWatchFile) { @@ -6845,7 +6989,7 @@ var ts; hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - directoryExists: directoryExists, + fileSystemEntryExists: fileSystemEntryExists, getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories, watchDirectory: nonRecursiveWatchDirectory, realpath: realpath, @@ -6896,6 +7040,124 @@ var ts; }; } } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { + var lastDirectoryPartWithDirectorySeparator; + var lastDirectoryPart; + if (inodeWatching) { + lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substring(fileOrDirectory.lastIndexOf(ts.directorySeparator)); + lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); + } + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + if (watcher) { + watcher.close(); + watcher = undefined; + } + } + }; + function updateWatcher(createWatcher) { + // If watcher is not closed, update it + if (watcher) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + if (hitSystemWatcherLimit) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + try { + var presentWatcher = fsWatchWorker(fileOrDirectory, recursive, inodeWatching ? + callbackChangingToMissingFileSystemEntry : + callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { + callback("rename", ""); + updateWatcher(watchMissingFileSystemEntry); + }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + function callbackChangingToMissingFileSystemEntry(event, relativeName) { + // In some scenarios, file save operation fires event with fileName.ext~ instead of fileName.ext + // To ensure we see the file going missing and coming back up (file delete and then recreated) + // and watches being updated correctly we are calling back with fileName.ext as well as fileName.ext~ + // The worst is we have fired event that was not needed but we wont miss any changes + // especially in cases where file goes missing and watches wrong inode + var originalRelativeName; + if (relativeName && ts.endsWith(relativeName, "~")) { + originalRelativeName = relativeName; + relativeName = relativeName.slice(0, relativeName.length - 1); + } + // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations + // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path + if (event === "rename" && + (!relativeName || + relativeName === lastDirectoryPart || + ts.endsWith(relativeName, lastDirectoryPartWithDirectorySeparator))) { + var modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime; + if (originalRelativeName) + callback(event, originalRelativeName, modifiedTime); + callback(event, relativeName, modifiedTime); + if (inodeWatching) { + // If this was rename event, inode has changed means we need to update watcher + updateWatcher(modifiedTime === ts.missingFileModifiedTime ? watchMissingFileSystemEntry : watchPresentFileSystemEntry); + } + else if (modifiedTime === ts.missingFileModifiedTime) { + updateWatcher(watchMissingFileSystemEntry); + } + } + else { + if (originalRelativeName) + callback(event, originalRelativeName); + callback(event, relativeName); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return watchFile(fileOrDirectory, function (_fileName, eventKind, modifiedTime) { + if (eventKind === FileWatcherEventKind.Created) { + modifiedTime || (modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime); + if (modifiedTime !== ts.missingFileModifiedTime) { + callback("rename", "", modifiedTime); + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + updateWatcher(watchPresentFileSystemEntry); + } + } + }, fallbackPollingInterval, fallbackOptions); + } + } } ts.createSystemWatchFunctions = createSystemWatchFunctions; /** @@ -6933,7 +7195,6 @@ var ts; // not actually work. var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { - var _a; var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/; var _fs = require("fs"); var _path = require("path"); @@ -6943,41 +7204,41 @@ var ts; try { _crypto = require("crypto"); } - catch (_b) { + catch (_a) { _crypto = undefined; } var activeSession; var profilePath = "./profile.cpuprofile"; - var hitSystemWatcherLimit = false; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; + var fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); - var _c = createSystemWatchFunctions({ + var _b = createSystemWatchFunctions({ pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames), getModifiedTime: getModifiedTime, setTimeout: setTimeout, clearTimeout: clearTimeout, - fsWatch: fsWatch, + fsWatchWorker: fsWatchWorker, useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - fileExists: fileExists, + fileSystemEntryExists: fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch, - directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, realpath: realpath, 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); }, - }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; + inodeWatching: isLinuxOrMacOs, + sysLog: sysLog, + }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -7226,110 +7487,14 @@ var ts; // File changed eventKind = FileWatcherEventKind.Changed; } - callback(fileName, eventKind); + callback(fileName, eventKind, curr.mtime); } } - function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { - var options; - var lastDirectoryPartWithDirectorySeparator; - var lastDirectoryPart; - if (isLinuxOrMacOs) { - lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator)); - lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); - } - /** Watcher for the file system entry depending on whether it is missing or present */ - var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? - watchMissingFileSystemEntry() : - watchPresentFileSystemEntry(); - return { - close: function () { - // Close the watcher (either existing file system entry watcher or missing file system entry watcher) - watcher.close(); - watcher = undefined; - } - }; - /** - * Invoke the callback with rename and update the watcher if not closed - * @param createWatcher - */ - function invokeCallbackAndUpdateWatcher(createWatcher) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); - // Call the callback for current directory - callback("rename", ""); - // If watcher is not closed, update it - if (watcher) { - watcher.close(); - watcher = createWatcher(); - } - } - /** - * Watch the file or directory that is currently present - * and when the watched file or directory is deleted, switch to missing file system entry watcher - */ - function watchPresentFileSystemEntry() { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows - // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) - if (options === undefined) { - if (fsSupportsRecursiveFsWatch) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - } - if (hitSystemWatcherLimit) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - try { - var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ? - callbackChangingToMissingFileSystemEntry : - callback); - // Watch the missing file or directory or error - presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); - return presentWatcher; - } - catch (e) { - // Catch the exception and use polling instead - // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - // so instead of throwing error, use fs.watchFile - hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - } - function callbackChangingToMissingFileSystemEntry(event, relativeName) { - // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations - // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path - return event === "rename" && - (!relativeName || - relativeName === lastDirectoryPart || - (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && - !fileSystemEntryExists(fileOrDirectory, entryKind) ? - invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : - callback(event, relativeName); - } - /** - * Watch the file or directory using fs.watchFile since fs.watch threw exception - * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - */ - function watchPresentFileSystemEntryWithFsWatchFile() { - return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); - } - /** - * Watch the file or directory that is missing - * and switch to existing file or directory when the missing filesystem entry is created - */ - function watchMissingFileSystemEntry() { - return watchFile(fileOrDirectory, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { - // Call the callback for current file or directory - // For now it could be callback for the inner directory creation, - // but just return current directory, better than current no-op - invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); - } - }, fallbackPollingInterval, fallbackOptions); - } + function fsWatchWorker(fileOrDirectory, recursive, callback) { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + return _fs.watch(fileOrDirectory, fsSupportsRecursiveFsWatch ? + { persistent: true, recursive: !!recursive } : { persistent: true }, callback); } function readFileWorker(fileName, _encoding) { var buffer; @@ -7466,9 +7631,12 @@ var ts; function getDirectories(path) { return getAccessibleFileSystemEntries(path).directories.slice(); } + function fsRealPathHandlingLongPath(path) { + return path.length < 260 ? _fs.realpathSync.native(path) : _fs.realpathSync(path); + } function realpath(path) { try { - return realpathSync(path); + return fsRealpath(path); } catch (_a) { return path; @@ -7476,12 +7644,19 @@ var ts; } function getModifiedTime(path) { var _a; + // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve + // the CPU time performance. + var originalStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; try { return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime; } catch (e) { return undefined; } + finally { + Error.stackTraceLimit = originalStackTraceLimit; + } } function setModifiedTime(path, time) { try { @@ -8336,6 +8511,7 @@ var ts; String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + or_JSX_element_expected: diag(1145, ts.DiagnosticCategory.Error, "or_JSX_element_expected_1145", "'{' or JSX element expected."), Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), @@ -8389,6 +8565,7 @@ var ts; Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), _0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module: diag(1208, ts.DiagnosticCategory.Error, "_0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_imp_1208", "'{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module."), + Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0: diag(1209, ts.DiagnosticCategory.Error, "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209", "Invalid optional chain from new expression. Did you mean to call '{0}()'?"), Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode: diag(1210, ts.DiagnosticCategory.Error, "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210", "Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of '{0}'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode."), A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), @@ -8481,6 +8658,7 @@ var ts; infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Class_constructor_may_not_be_an_accessor: diag(1341, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_an_accessor_1341", "Class constructor may not be an accessor."), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), @@ -8499,6 +8677,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Class_constructor_may_not_be_a_generator: diag(1360, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_a_generator_1360", "Class constructor may not be a generator."), _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."), _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), @@ -8583,18 +8762,30 @@ var ts; Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, ts.DiagnosticCategory.Message, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."), Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments: diag(1450, ts.DiagnosticCategory.Message, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional assertion as arguments"), Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"), - Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "Resolution modes are only supported when `moduleResolution` is `node16` or `nodenext`."), + resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "'resolution-mode' assertions are only supported when `moduleResolution` is `node16` or `nodenext`."), resolution_mode_should_be_either_require_or_import: diag(1453, ts.DiagnosticCategory.Error, "resolution_mode_should_be_either_require_or_import_1453", "`resolution-mode` should be either `require` or `import`."), resolution_mode_can_only_be_set_for_type_only_imports: diag(1454, ts.DiagnosticCategory.Error, "resolution_mode_can_only_be_set_for_type_only_imports_1454", "`resolution-mode` can only be set for type-only imports."), resolution_mode_is_the_only_valid_key_for_type_import_assertions: diag(1455, ts.DiagnosticCategory.Error, "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455", "`resolution-mode` is the only valid key for type import assertions."), Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require: diag(1456, ts.DiagnosticCategory.Error, "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456", "Type import assertions should have exactly one key - `resolution-mode` - with value `import` or `require`."), + Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk: diag(1457, ts.DiagnosticCategory.Message, "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457", "Matched by default include pattern '**/*'"), + File_is_ECMAScript_module_because_0_has_field_type_with_value_module: diag(1458, ts.DiagnosticCategory.Message, "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458", "File is ECMAScript module because '{0}' has field \"type\" with value \"module\""), + File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module: diag(1459, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459", "File is CommonJS module because '{0}' has field \"type\" whose value is not \"module\""), + File_is_CommonJS_module_because_0_does_not_have_field_type: diag(1460, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_does_not_have_field_type_1460", "File is CommonJS module because '{0}' does not have field \"type\""), + File_is_CommonJS_module_because_package_json_was_not_found: diag(1461, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_package_json_was_not_found_1461", "File is CommonJS module because 'package.json' was not found"), The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."), - Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."), + Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported with 'require'. Use an ECMAScript import instead."), catch_or_finally_expected: diag(1472, ts.DiagnosticCategory.Error, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), An_import_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1473, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473", "An import declaration can only be used at the top level of a module."), An_export_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1474, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474", "An export declaration can only be used at the top level of a module."), Control_what_method_is_used_to_detect_module_format_JS_files: diag(1475, ts.DiagnosticCategory.Message, "Control_what_method_is_used_to_detect_module_format_JS_files_1475", "Control what method is used to detect module-format JS files."), auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules: diag(1476, ts.DiagnosticCategory.Message, "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476", "\"auto\": Treat files with imports, exports, import.meta, jsx (with jsx: react-jsx), or esm format (with module: node16+) as modules."), + An_instantiation_expression_cannot_be_followed_by_a_property_access: diag(1477, ts.DiagnosticCategory.Error, "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477", "An instantiation expression cannot be followed by a property access."), + Identifier_or_string_literal_expected: diag(1478, ts.DiagnosticCategory.Error, "Identifier_or_string_literal_expected_1478", "Identifier or string literal expected."), + The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead: diag(1479, ts.DiagnosticCategory.Error, "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479", "The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import(\"{0}\")' call instead."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module: diag(1480, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480", "To convert this file to an ECMAScript module, change its file extension to '{0}' or create a local package.json file with `{ \"type\": \"module\" }`."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1: diag(1481, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481", "To convert this file to an ECMAScript module, change its file extension to '{0}', or add the field `\"type\": \"module\"` to '{1}'."), + To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0: diag(1482, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482", "To convert this file to an ECMAScript module, add the field `\"type\": \"module\"` to '{0}'."), + To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module: diag(1483, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483", "To convert this file to an ECMAScript module, create a local package.json file with `{ \"type\": \"module\" }`."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8603,8 +8794,11 @@ var ts; Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."), The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."), + This_type_parameter_might_need_an_extends_0_constraint: diag(2208, ts.DiagnosticCategory.Error, "This_type_parameter_might_need_an_extends_0_constraint_2208", "This type parameter might need an `extends {0}` constraint."), The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2209, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209", "The project root is ambiguous, but is required to resolve export map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2210, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210", "The project root is ambiguous, but is required to resolve import map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), + Add_extends_constraint: diag(2211, ts.DiagnosticCategory.Message, "Add_extends_constraint_2211", "Add `extends` constraint."), + Add_extends_constraint_to_all_type_parameters: diag(2212, ts.DiagnosticCategory.Message, "Add_extends_constraint_to_all_type_parameters_2212", "Add `extends` constraint to all type parameters"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -8805,6 +8999,7 @@ var ts; Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + A_tuple_type_cannot_be_indexed_with_a_negative_value: diag(2514, ts.DiagnosticCategory.Error, "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514", "A tuple type cannot be indexed with a negative value."), Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), @@ -9087,6 +9282,12 @@ var ts; Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls: diag(2836, ts.DiagnosticCategory.Error, "Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls_2836", "Import assertions are not allowed on statements that transpile to commonjs 'require' calls."), Import_assertion_values_must_be_string_literal_expressions: diag(2837, ts.DiagnosticCategory.Error, "Import_assertion_values_must_be_string_literal_expressions_2837", "Import assertion values must be string literal expressions."), All_declarations_of_0_must_have_identical_constraints: diag(2838, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_constraints_2838", "All declarations of '{0}' must have identical constraints."), + This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value: diag(2839, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839", "This condition will always return '{0}' since JavaScript compares objects by reference, not value."), + An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes: diag(2840, ts.DiagnosticCategory.Error, "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840", "An interface cannot extend a primitive type like '{0}'; an interface can only extend named types and classes"), + The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(2841, ts.DiagnosticCategory.Error, "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841", "The type of this expression cannot be named without a 'resolution-mode' assertion, which is an unstable feature. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + _0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation: diag(2842, ts.DiagnosticCategory.Error, "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842", "'{0}' is an unused renaming of '{1}'. Did you intend to use it as a type annotation?"), + We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here: diag(2843, ts.DiagnosticCategory.Error, "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843", "We can only write a type for '{0}' by adding a type for the entire parameter here."), + Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2844, ts.DiagnosticCategory.Error, "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844", "Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -9194,7 +9395,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), - Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "Resolution mode assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "'resolution-mode' assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -9497,8 +9698,8 @@ var ts; Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Referenced_project_0_may_not_disable_emit: diag(6310, ts.DiagnosticCategory.Error, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."), - Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), - Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_1_is_older_than_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350", "Project '{0}' is out of date because output '{1}' is older than input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than output '{2}'"), Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), @@ -9542,6 +9743,8 @@ var ts; Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6396, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6397, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."), + 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"), 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."), @@ -9782,6 +9985,8 @@ var ts; Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, ts.DiagnosticCategory.Error, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."), The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."), + You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder: diag(8035, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035", "You cannot rename elements that are defined in a 'node_modules' folder."), + You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -10052,6 +10257,9 @@ var ts; For_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, ts.DiagnosticCategory.Error, "For_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'For await' loops cannot be used inside a class static block."), Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, ts.DiagnosticCategory.Error, "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."), A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, ts.DiagnosticCategory.Error, "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."), + _0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation: diag(18042, ts.DiagnosticCategory.Error, "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042", "'{0}' is a type and cannot be imported in JavaScript files. Use '{1}' in a JSDoc type annotation."), + Types_cannot_appear_in_export_declarations_in_JavaScript_files: diag(18043, ts.DiagnosticCategory.Error, "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043", "Types cannot appear in export declarations in JavaScript files."), + _0_is_automatically_exported_here: diag(18044, ts.DiagnosticCategory.Message, "_0_is_automatically_exported_here_18044", "'{0}' is automatically exported here."), }; })(ts || (ts = {})); var ts; @@ -12939,6 +13147,18 @@ var ts; } } ts.getAssignedName = getAssignedName; + function getDecorators(node) { + if (ts.hasDecorators(node)) { + return ts.filter(node.modifiers, ts.isDecorator); + } + } + ts.getDecorators = getDecorators; + function getModifiers(node) { + if (ts.hasSyntacticModifier(node, 125951 /* ModifierFlags.Modifier */)) { + return ts.filter(node.modifiers, isModifier); + } + } + ts.getModifiers = getModifiers; function getJSDocParameterTagsWorker(param, noCache) { if (param.name) { if (ts.isIdentifier(param.name)) { @@ -13209,6 +13429,12 @@ var ts; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + * + * This does *not* return type parameters from a jsdoc reference to a generic type, eg + * + * type Id = (x: T) => T + * /** @type {Id} / + * function id(x) { return x } */ function getEffectiveTypeParameterDeclarations(node) { if (ts.isJSDocSignature(node)) { @@ -13221,6 +13447,9 @@ var ts; if (node.typeParameters) { return node.typeParameters; } + if (ts.canHaveIllegalTypeParameters(node) && node.typeParameters) { + return node.typeParameters; + } if (ts.isInJSFile(node)) { var decls = ts.getJSDocTypeParameterDeclarations(node); if (decls.length) { @@ -13397,6 +13626,19 @@ var ts; return isLiteralKind(node.kind); } ts.isLiteralExpression = isLiteralExpression; + /** @internal */ + function isLiteralExpressionOfObject(node) { + switch (node.kind) { + case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 13 /* SyntaxKind.RegularExpressionLiteral */: + case 213 /* SyntaxKind.FunctionExpression */: + case 226 /* SyntaxKind.ClassExpression */: + return true; + } + return false; + } + ts.isLiteralExpressionOfObject = isLiteralExpressionOfObject; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { @@ -13606,6 +13848,10 @@ var ts; } ts.isMethodOrAccessor = isMethodOrAccessor; // Type members + function isModifierLike(node) { + return isModifier(node) || ts.isDecorator(node); + } + ts.isModifierLike = isModifierLike; function isTypeElement(node) { var kind = node.kind; return kind === 175 /* SyntaxKind.ConstructSignature */ @@ -14215,7 +14461,6 @@ var ts; case 254 /* SyntaxKind.VariableDeclaration */: case 164 /* SyntaxKind.Parameter */: case 203 /* SyntaxKind.BindingElement */: - case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: case 296 /* SyntaxKind.PropertyAssignment */: case 299 /* SyntaxKind.EnumMember */: @@ -14267,6 +14512,16 @@ var ts; return node.kind === 324 /* SyntaxKind.JSDocLink */ || node.kind === 325 /* SyntaxKind.JSDocLinkCode */ || node.kind === 326 /* SyntaxKind.JSDocLinkPlain */; } ts.isJSDocLinkLike = isJSDocLinkLike; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; // #endregion })(ts || (ts = {})); /* @internal */ @@ -14747,10 +15002,11 @@ var ts; } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { - if (nodeIsMissing(node) || !node.decorators) { + var lastDecorator = !nodeIsMissing(node) && ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + if (!lastDecorator) { return getTokenPosOfNode(node, sourceFile); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastDecorator.end); } ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { @@ -16136,7 +16392,7 @@ var ts; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { - return node.decorators !== undefined + return hasDecorators(node) && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; @@ -16212,6 +16468,8 @@ var ts; case 218 /* SyntaxKind.AwaitExpression */: case 231 /* SyntaxKind.MetaProperty */: return true; + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + return !ts.isHeritageClause(node.parent); case 161 /* SyntaxKind.QualifiedName */: while (node.parent.kind === 161 /* SyntaxKind.QualifiedName */) { node = node.parent; @@ -16383,9 +16641,6 @@ var ts; } ts.isVariableDeclarationInitializedToBareOrAccessedRequire = isVariableDeclarationInitializedToBareOrAccessedRequire; function isVariableDeclarationInitializedWithRequireHelper(node, allowAccessedRequire) { - if (node.kind === 203 /* SyntaxKind.BindingElement */) { - node = node.parent.parent; - } return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, /*requireStringLiteralLikeArgument*/ true); @@ -17037,16 +17292,6 @@ var ts; return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function hasRestParameter(s) { - var last = ts.lastOrUndefined(s.parameters); - return !!last && isRestParameter(last); - } - ts.hasRestParameter = hasRestParameter; - function isRestParameter(node) { - var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; - } - ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { return !!node.typeArguments; } @@ -17168,6 +17413,12 @@ var ts; return [child, node]; } ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild; + function skipTypeParentheses(node) { + while (ts.isParenthesizedTypeNode(node)) + node = node.type; + return node; + } + ts.skipTypeParentheses = skipTypeParentheses; function skipParentheses(node, excludeJSDocTypeAssertions) { var flags = excludeJSDocTypeAssertions ? 1 /* OuterExpressionKinds.Parentheses */ | 16 /* OuterExpressionKinds.ExcludeJSDocTypeAssertion */ : @@ -18914,6 +19165,10 @@ var ts; return hasEffectiveModifier(node, 64 /* ModifierFlags.Readonly */); } ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier; + function hasDecorators(node) { + return hasSyntacticModifier(node, 131072 /* ModifierFlags.Decorator */); + } + ts.hasDecorators = hasDecorators; function getSelectedEffectiveModifierFlags(node, flags) { return getEffectiveModifierFlags(node) & flags; } @@ -18991,7 +19246,7 @@ var ts; * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc. */ function getSyntacticModifierFlagsNoCache(node) { - var flags = modifiersToFlags(node.modifiers); + var flags = ts.canHaveModifiers(node) ? modifiersToFlags(node.modifiers) : 0 /* ModifierFlags.None */; if (node.flags & 4 /* NodeFlags.NestedNamespace */ || (node.kind === 79 /* SyntaxKind.Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* ModifierFlags.Export */; } @@ -19025,6 +19280,7 @@ var ts; case 159 /* SyntaxKind.OverrideKeyword */: return 16384 /* ModifierFlags.Override */; case 101 /* SyntaxKind.InKeyword */: return 32768 /* ModifierFlags.In */; case 144 /* SyntaxKind.OutKeyword */: return 65536 /* ModifierFlags.Out */; + case 165 /* SyntaxKind.Decorator */: return 131072 /* ModifierFlags.Decorator */; } return 0 /* ModifierFlags.None */; } @@ -19402,8 +19658,9 @@ var ts; * Moves the start position of a range past any decorators. */ function moveRangePastDecorators(node) { - return node.decorators && node.decorators.length > 0 - ? moveRangePos(node, node.decorators.end) + var lastDecorator = ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + return lastDecorator && !positionIsSynthesized(lastDecorator.end) + ? moveRangePos(node, lastDecorator.end) : node; } ts.moveRangePastDecorators = moveRangePastDecorators; @@ -19411,8 +19668,9 @@ var ts; * Moves the start position of a range past any decorators or modifiers. */ function moveRangePastModifiers(node) { - return node.modifiers && node.modifiers.length > 0 - ? moveRangePos(node, node.modifiers.end) + var lastModifier = ts.canHaveModifiers(node) ? ts.lastOrUndefined(node.modifiers) : undefined; + return lastModifier && !positionIsSynthesized(lastModifier.end) + ? moveRangePos(node, lastModifier.end) : moveRangePastDecorators(node); } ts.moveRangePastModifiers = moveRangePastModifiers; @@ -19534,7 +19792,8 @@ var ts; function getDeclarationModifierFlagsFromSymbol(s, isWrite) { if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 173 /* SyntaxKind.SetAccessor */; })) || s.valueDeclaration; + var declaration = (isWrite && s.declarations && ts.find(s.declarations, ts.isSetAccessorDeclaration)) + || (s.flags & 32768 /* SymbolFlags.GetAccessor */ && ts.find(s.declarations, ts.isGetAccessorDeclaration)) || s.valueDeclaration; var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* SymbolFlags.Class */ ? flags : flags & ~28 /* ModifierFlags.AccessibilityModifier */; } @@ -20207,8 +20466,9 @@ var ts; */ function isFileForcedToBeModuleByFormat(file) { // Excludes declaration files - they still require an explicit `export {}` or the like - // for back compat purposes. - return file.impliedNodeFormat === ts.ModuleKind.ESNext && !file.isDeclarationFile ? true : undefined; + // for back compat purposes. The only non-declaration files _not_ forced to be a module are `.js` files + // that aren't esm-mode (meaning not in a `type: module` scope). + return (file.impliedNodeFormat === ts.ModuleKind.ESNext || (ts.fileExtensionIsOneOf(file.fileName, [".cjs" /* Extension.Cjs */, ".cts" /* Extension.Cts */, ".mjs" /* Extension.Mjs */, ".mts" /* Extension.Mts */]))) && !file.isDeclarationFile ? true : undefined; } function getSetExternalModuleIndicator(options) { // TODO: Should this callback be cached? @@ -20216,7 +20476,7 @@ var ts; case ts.ModuleDetectionKind.Force: // All non-declaration files are modules, declaration files still do the usual isFileProbablyExternalModule return function (file) { - file.externalModuleIndicator = !file.isDeclarationFile || ts.isFileProbablyExternalModule(file); + file.externalModuleIndicator = ts.isFileProbablyExternalModule(file) || !file.isDeclarationFile || undefined; }; case ts.ModuleDetectionKind.Legacy: // Files are modules if they have imports, exports, or import.meta @@ -20231,10 +20491,7 @@ var ts; if (options.jsx === 4 /* JsxEmit.ReactJSX */ || options.jsx === 5 /* JsxEmit.ReactJSXDev */) { checks.push(isFileModuleFromUsingJSXTag); } - var moduleKind = getEmitModuleKind(options); - if (moduleKind === ts.ModuleKind.Node16 || moduleKind === ts.ModuleKind.NodeNext) { - checks.push(isFileForcedToBeModuleByFormat); - } + checks.push(isFileForcedToBeModuleByFormat); var combined_1 = ts.or.apply(void 0, checks); var callback = function (file) { return void (file.externalModuleIndicator = combined_1(file)); }; return callback; @@ -20276,7 +20533,8 @@ var ts; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; function getEmitModuleDetectionKind(options) { - return options.moduleDetection || ts.ModuleDetectionKind.Auto; + return options.moduleDetection || + (getEmitModuleKind(options) === ts.ModuleKind.Node16 || getEmitModuleKind(options) === ts.ModuleKind.NodeNext ? ts.ModuleDetectionKind.Force : ts.ModuleDetectionKind.Auto); } ts.getEmitModuleDetectionKind = getEmitModuleDetectionKind; function hasJsonModuleEmitEnabled(options) { @@ -20359,6 +20617,10 @@ var ts; return optionsHaveChanges(oldOptions, newOptions, ts.affectsEmitOptionDeclarations); } ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit; + function compilerOptionsAffectDeclarationPath(newOptions, oldOptions) { + return optionsHaveChanges(oldOptions, newOptions, ts.affectsDeclarationPathOptionDeclarations); + } + ts.compilerOptionsAffectDeclarationPath = compilerOptionsAffectDeclarationPath; function getCompilerOptionValue(options, option) { return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; } @@ -21299,8 +21561,12 @@ var ts; return node.parent.templateSpans; case 233 /* SyntaxKind.TemplateSpan */: return node.parent.templateSpans; - case 165 /* SyntaxKind.Decorator */: - return node.parent.decorators; + case 165 /* SyntaxKind.Decorator */: { + var parent_2 = node.parent; + return ts.canHaveDecorators(parent_2) ? parent_2.modifiers : + ts.canHaveIllegalDecorators(parent_2) ? parent_2.illegalDecorators : + undefined; + } case 291 /* SyntaxKind.HeritageClause */: return node.parent.heritageClauses; } @@ -21814,7 +22080,7 @@ var ts; * Wraps an expression in parentheses if it is needed in order to use the expression for * property or element access. */ - function parenthesizeLeftSideOfAccess(expression) { + function parenthesizeLeftSideOfAccess(expression, optionalChain) { // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exception is: // @@ -21823,7 +22089,8 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments) + && (optionalChain || !ts.isOptionalChain(emittedExpression))) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -22770,13 +23037,8 @@ var ts; function createBaseNode(kind) { return baseFactory.createBaseNode(kind); } - function createBaseDeclaration(kind, decorators, modifiers) { + function createBaseDeclaration(kind) { var node = createBaseNode(kind); - node.decorators = asNodeArray(decorators); - node.modifiers = asNodeArray(modifiers); - node.transformFlags |= - propagateChildrenFlags(node.decorators) | - propagateChildrenFlags(node.modifiers); // NOTE: The following properties are commonly set by the binder and are added here to // ensure declarations have a stable shape. node.symbol = undefined; // initialized by binder @@ -22785,10 +23047,15 @@ var ts; node.nextContainer = undefined; // initialized by binder return node; } - function createBaseNamedDeclaration(kind, decorators, modifiers, name) { - var node = createBaseDeclaration(kind, decorators, modifiers); + function createBaseNamedDeclaration(kind, modifiers, name) { + var node = createBaseDeclaration(kind); name = asName(name); node.name = name; + if (ts.canHaveModifiers(node)) { + node.modifiers = asNodeArray(modifiers); + node.transformFlags |= propagateChildrenFlags(node.modifiers); + // node.decorators = filter(node.modifiers, isDecorator); + } // The PropertyName of a member is allowed to be `await`. // We don't need to exclude `await` for type signatures since types // don't propagate child flags. @@ -22811,16 +23078,16 @@ var ts; } return node; } - function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.typeParameters = asNodeArray(typeParameters); node.transformFlags |= propagateChildrenFlags(node.typeParameters); if (typeParameters) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.parameters = createNodeArray(parameters); node.type = type; node.transformFlags |= @@ -22828,50 +23095,45 @@ var ts; propagateChildFlags(node.type); if (type) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used for quick info + node.typeArguments = undefined; return node; } - function updateBaseSignatureDeclaration(updated, original) { - // copy children used only for error reporting - if (original.typeArguments) + function finishUpdateBaseSignatureDeclaration(updated, original) { + if (updated !== original) { + // copy children used for quick info updated.typeArguments = original.typeArguments; + } return update(updated, original); } - function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { - var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); + function createBaseFunctionLikeDeclaration(kind, modifiers, name, typeParameters, parameters, type, body) { + var node = createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateBaseFunctionLikeDeclaration(updated, original) { - // copy children used only for error reporting - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - if (original.typeArguments) - updated.typeArguments = original.typeArguments; - return updateBaseSignatureDeclaration(updated, original); - } - function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.heritageClauses = asNodeArray(heritageClauses); node.transformFlags |= propagateChildrenFlags(node.heritageClauses); return node; } - function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses); + function createBaseClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members); return node; } - function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseBindingLikeDeclaration(kind, modifiers, name, initializer) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.initializer = initializer; node.transformFlags |= propagateChildFlags(node.initializer); return node; } - function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) { - var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer); + function createBaseVariableLikeDeclaration(kind, modifiers, name, type, initializer) { + var node = createBaseBindingLikeDeclaration(kind, modifiers, name, initializer); node.type = type; node.transformFlags |= propagateChildFlags(type); if (type) @@ -22967,7 +23229,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 132 /* SyntaxKind.AwaitKeyword */) { - node.transformFlags |= 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } return node; } @@ -23019,7 +23281,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(80 /* SyntaxKind.PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags |= 16777216 /* TransformFlags.ContainsClassFields */; return node; } // @@ -23066,14 +23328,14 @@ var ts; transformFlags = 1 /* TransformFlags.ContainsTypeScript */; break; case 106 /* SyntaxKind.SuperKeyword */: - transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 33554432 /* TransformFlags.ContainsLexicalSuper */; + transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 134217728 /* TransformFlags.ContainsLexicalSuper */; break; case 124 /* SyntaxKind.StaticKeyword */: transformFlags = 1024 /* TransformFlags.ContainsES2015 */; break; case 108 /* SyntaxKind.ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 8192 /* TransformFlags.ContainsLexicalThis */; + transformFlags = 16384 /* TransformFlags.ContainsLexicalThis */; break; } if (transformFlags) { @@ -23171,7 +23433,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 65536 /* TransformFlags.ContainsComputedPropertyName */; + 131072 /* TransformFlags.ContainsComputedPropertyName */; return node; } // @api @@ -23180,41 +23442,19 @@ var ts; ? update(createComputedPropertyName(expression), node) : node; } - function createTypeParameterDeclaration(modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } - var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, - /*decorators*/ undefined, modifiers, name); + // + // Signature elements + // + // @api + function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) { + var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, modifiers, name); node.constraint = constraint; node.default = defaultType; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateTypeParameterDeclaration(node, modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } + // @api + function updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType) { return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint @@ -23223,8 +23463,8 @@ var ts; : node; } // @api - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -23237,32 +23477,32 @@ var ts; if (questionToken) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; if (ts.modifiersToFlags(node.modifiers) & 16476 /* ModifierFlags.ParameterPropertyModifier */) - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; } return node; } // @api - function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } // @api function createDecorator(expression) { var node = createBaseNode(165 /* SyntaxKind.Decorator */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */ | - 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */ | + 33554432 /* TransformFlags.ContainsDecorators */; return node; } // @api @@ -23276,11 +23516,12 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, - /*decorators*/ undefined, modifiers, name); + var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, modifiers, name); node.type = type; node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.initializer = undefined; return node; } // @api @@ -23289,20 +23530,27 @@ var ts; || node.name !== name || node.questionToken !== questionToken || node.type !== type - ? update(createPropertySignature(modifiers, name, questionToken, type), node) + ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) : node; } + function finishUpdatePropertySignature(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.initializer = original.initializer; + } + return update(updated, original); + } // @api - function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, decorators, modifiers, name, type, initializer); + function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 8388608 /* TransformFlags.ContainsClassFields */; + 16777216 /* TransformFlags.ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; @@ -23310,21 +23558,19 @@ var ts; return node; } // @api - function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.modifiers !== modifiers || node.name !== name || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer - ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23337,12 +23583,12 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node; } // @api - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= @@ -23363,12 +23609,13 @@ var ts; else if (asteriskToken) { node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } + // The following properties are used only to report grammar errors + node.exclamationToken = undefined; return node; } // @api - function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.questionToken !== questionToken @@ -23376,80 +23623,123 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } + function finishUpdateMethodDeclaration(updated, original) { + if (updated !== original) { + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api - function createClassStaticBlockDeclaration(decorators, modifiers, body) { - var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, decorators, modifiers, + function createClassStaticBlockDeclaration(body) { + var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, + /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined); node.body = body; - node.transformFlags = propagateChildFlags(body) | 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags = propagateChildFlags(body) | 16777216 /* TransformFlags.ContainsClassFields */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api - function updateClassStaticBlockDeclaration(node, decorators, modifiers, body) { - return node.decorators !== decorators - || node.modifier !== modifiers - || node.body !== body - ? update(createClassStaticBlockDeclaration(decorators, modifiers, body), node) + function updateClassStaticBlockDeclaration(node, body) { + return node.body !== body + ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) : node; } + function finishUpdateClassStaticBlockDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, decorators, modifiers, + function createConstructorDeclaration(modifiers, parameters, body) { + var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.typeParameters = undefined; + node.type = undefined; return node; } // @api - function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateConstructorDeclaration(node, modifiers, parameters, body) { + return node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node) + ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) : node; } + function finishUpdateConstructorDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, decorators, modifiers, name, + function createGetAccessorDeclaration(modifiers, name, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + return node; } // @api - function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node) + ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) : node; } + function finishUpdateGetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, decorators, modifiers, name, + function createSetAccessorDeclaration(modifiers, name, parameters, body) { + var node = createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + node.type = undefined; + return node; } // @api - function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateSetAccessorDeclaration(node, modifiers, name, parameters, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node) + ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) : node; } + function finishUpdateSetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createCallSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(174 /* SyntaxKind.CallSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23460,13 +23750,12 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node; } // @api function createConstructSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(175 /* SyntaxKind.ConstructSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23477,24 +23766,23 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node; } // @api - function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, decorators, modifiers, + function createIndexSignature(modifiers, parameters, type) { + var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } // @api - function updateIndexSignature(node, decorators, modifiers, parameters, type) { + function updateIndexSignature(node, modifiers, parameters, type) { return node.parameters !== parameters || node.type !== type - || node.decorators !== decorators || node.modifiers !== modifiers - ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node; } // @api @@ -23554,10 +23842,11 @@ var ts; // @api function createFunctionTypeNode(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(179 /* SyntaxKind.FunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.modifiers = undefined; return node; } // @api @@ -23565,9 +23854,15 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node) + ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) : node; } + function finishUpdateFunctionTypeNode(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createConstructorTypeNode() { var args = []; @@ -23579,8 +23874,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, - /*decorators*/ undefined, modifiers, + var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23604,7 +23898,7 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node; } /** @deprecated */ @@ -23784,33 +24078,27 @@ var ts; ? update(createTemplateLiteralType(head, templateSpans), node) : node; } - function createImportTypeNode(argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : false; + // @api + function createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = false; } var node = createBaseNode(200 /* SyntaxKind.ImportType */); node.argument = argument; - node.assertions = assertion; + node.assertions = assertions; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.isTypeOf = isTypeOf; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateImportTypeNode(node, argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : node.isTypeOf; + // @api + function updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; } return node.argument !== argument - || node.assertions !== assertion + || node.assertions !== assertions || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf - ? update(createImportTypeNode(argument, assertion, qualifier, typeArguments, isTypeOf), node) + ? update(createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf), node) : node; } // @api @@ -23909,11 +24197,11 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + 524288 /* TransformFlags.ContainsBindingPattern */; + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } return node; } @@ -23930,7 +24218,7 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; + 524288 /* TransformFlags.ContainsBindingPattern */; return node; } // @api @@ -23942,7 +24230,6 @@ var ts; // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(203 /* SyntaxKind.BindingElement */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; @@ -23955,7 +24242,7 @@ var ts; propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 16384 /* TransformFlags.ContainsRestOrSpread */; + node.transformFlags |= 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -24011,13 +24298,13 @@ var ts; // @api function createPropertyAccessExpression(expression, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.name = asName(name); node.transformFlags = propagateChildFlags(node.expression) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); if (ts.isSuperKeyword(expression)) { // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators @@ -24041,7 +24328,7 @@ var ts; function createPropertyAccessChain(expression, questionDotToken, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= @@ -24050,7 +24337,7 @@ var ts; propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); return node; } // @api @@ -24067,7 +24354,7 @@ var ts; // @api function createElementAccessExpression(expression, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.argumentExpression = asExpression(index); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24095,7 +24382,7 @@ var ts; function createElementAccessChain(expression, questionDotToken, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.argumentExpression = asExpression(index); node.transformFlags |= @@ -24119,7 +24406,7 @@ var ts; // @api function createCallExpression(expression, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); node.transformFlags |= @@ -24130,10 +24417,10 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 4194304 /* TransformFlags.ContainsDynamicImport */; + node.transformFlags |= 8388608 /* TransformFlags.ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24152,7 +24439,7 @@ var ts; function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -24166,7 +24453,7 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24207,7 +24494,7 @@ var ts; // @api function createTaggedTemplateExpression(tag, typeArguments, template) { var node = createBaseExpression(210 /* SyntaxKind.TaggedTemplateExpression */); - node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); + node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.template = template; node.transformFlags |= @@ -24264,8 +24551,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); if (node.typeParameters) { @@ -24293,20 +24579,19 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, - /*decorators*/ undefined, modifiers, + var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* SyntaxKind.EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | 1024 /* TransformFlags.ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { - node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24318,7 +24603,7 @@ var ts; || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } // @api @@ -24368,7 +24653,7 @@ var ts; propagateChildFlags(node.expression) | 256 /* TransformFlags.ContainsES2017 */ | 128 /* TransformFlags.ContainsES2018 */ | - 1048576 /* TransformFlags.ContainsAwait */; + 2097152 /* TransformFlags.ContainsAwait */; return node; } // @api @@ -24389,7 +24674,7 @@ var ts; ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -24410,7 +24695,7 @@ var ts; if (ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -24456,11 +24741,14 @@ var ts; else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { node.transformFlags |= 16 /* TransformFlags.ContainsES2021 */; } + if (operatorKind === 101 /* SyntaxKind.InKeyword */ && ts.isPrivateIdentifier(node.left)) { + node.transformFlags |= 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */; + } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; if (node.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer @@ -24468,8 +24756,8 @@ var ts; var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (target.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } if (target.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); @@ -24595,7 +24883,7 @@ var ts; propagateChildFlags(node.asteriskToken) | 1024 /* TransformFlags.ContainsES2015 */ | 128 /* TransformFlags.ContainsES2018 */ | - 524288 /* TransformFlags.ContainsYield */; + 1048576 /* TransformFlags.ContainsYield */; return node; } // @api @@ -24612,7 +24900,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 16384 /* TransformFlags.ContainsRestOrSpread */; + 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -24622,20 +24910,19 @@ var ts; : node; } // @api - function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, modifiers, name, typeParameters, heritageClauses, members); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; return node; } // @api - function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api @@ -24645,7 +24932,7 @@ var ts; // @api function createExpressionWithTypeArguments(expression, typeArguments) { var node = createBaseNode(228 /* SyntaxKind.ExpressionWithTypeArguments */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24681,7 +24968,7 @@ var ts; // @api function createNonNullExpression(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -24700,7 +24987,7 @@ var ts; function createNonNullChain(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -24783,10 +25070,12 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */); + node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= - propagateChildFlags(node.declarationList); + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.declarationList); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } @@ -24945,7 +25234,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24960,7 +25249,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24977,7 +25266,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -25077,7 +25366,6 @@ var ts; // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { var node = createBaseVariableLikeDeclaration(254 /* SyntaxKind.VariableDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; node.transformFlags |= propagateChildFlags(node.exclamationToken); @@ -25103,11 +25391,11 @@ var ts; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* NodeFlags.BlockScoped */) { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */ | - 131072 /* TransformFlags.ContainsBlockScopedBinding */; + 262144 /* TransformFlags.ContainsBlockScopedBinding */; } return node; } @@ -25118,8 +25406,8 @@ var ts; : node; } // @api - function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -25127,7 +25415,7 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { if (node.asteriskToken) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */; @@ -25140,104 +25428,133 @@ var ts; node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } } + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } + function finishUpdateFunctionDeclaration(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.illegalDecorators = original.illegalDecorators; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } else { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; - if (node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */) { + if (node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } } return node; } // @api - function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api - function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? finishUpdateInterfaceDeclaration(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } + function finishUpdateInterfaceDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + function createTypeAliasDeclaration(modifiers, name, typeParameters, type) { + var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type - ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + ? finishUpdateTypeAliasDeclaration(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; } + function finishUpdateTypeAliasDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, decorators, modifiers, name); + function createEnumDeclaration(modifiers, name, members) { + var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateEnumDeclaration(node, decorators, modifiers, name, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateEnumDeclaration(node, modifiers, name, members) { + return node.modifiers !== modifiers || node.name !== name || node.members !== members - ? update(createEnumDeclaration(decorators, modifiers, name, members), node) + ? finishUpdateEnumDeclaration(createEnumDeclaration(modifiers, name, members), node) : node; } + function finishUpdateEnumDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createModuleDeclaration(decorators, modifiers, name, body, flags) { + function createModuleDeclaration(modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* NodeFlags.None */; } - var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */); + node.modifiers = asNodeArray(modifiers); node.flags |= flags & (16 /* NodeFlags.Namespace */ | 4 /* NodeFlags.NestedNamespace */ | 1024 /* NodeFlags.GlobalAugmentation */); node.name = name; node.body = body; @@ -25246,22 +25563,30 @@ var ts; } else { node.transformFlags |= - propagateChildFlags(node.name) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateModuleDeclaration(node, decorators, modifiers, name, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateModuleDeclaration(node, modifiers, name, body) { + return node.modifiers !== modifiers || node.name !== name || node.body !== body - ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + ? finishUpdateModuleDeclaration(createModuleDeclaration(modifiers, name, body, node.flags), node) : node; } + function finishUpdateModuleDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createModuleBlock(statements) { var node = createBaseNode(262 /* SyntaxKind.ModuleBlock */); @@ -25291,60 +25616,84 @@ var ts; // @api function createNamespaceExportDeclaration(name) { var node = createBaseNamedDeclaration(264 /* SyntaxKind.NamespaceExportDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api function updateNamespaceExportDeclaration(node, name) { return node.name !== name - ? update(createNamespaceExportDeclaration(name), node) + ? finishUpdateNamespaceExportDeclaration(createNamespaceExportDeclaration(name), node) : node; } + function finishUpdateNamespaceExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, decorators, modifiers, name); + function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) { + var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference - ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node) + ? finishUpdateImportEqualsDeclaration(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; } + function finishUpdateImportEqualsDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */, decorators, modifiers); + function createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause), node) + ? finishUpdateImportDeclaration(createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateImportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createImportClause(isTypeOnly, name, namedBindings) { var node = createBaseNode(267 /* SyntaxKind.ImportClause */); @@ -25357,7 +25706,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25417,7 +25766,7 @@ var ts; var node = createBaseNode(268 /* SyntaxKind.NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25433,7 +25782,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.name) | 4 /* TransformFlags.ContainsESNext */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25447,7 +25796,7 @@ var ts; var node = createBaseNode(269 /* SyntaxKind.NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25465,7 +25814,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25477,54 +25826,71 @@ var ts; : node; } // @api - function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */, decorators, modifiers); + function createExportAssignment(modifiers, isExportEquals, expression) { + var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */); + node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(63 /* SyntaxKind.EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); - node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportAssignment(node, decorators, modifiers, expression) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportAssignment(node, modifiers, expression) { + return node.modifiers !== modifiers || node.expression !== expression - ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + ? finishUpdateExportAssignment(createExportAssignment(modifiers, node.isExportEquals, expression), node) : node; } + function finishUpdateExportAssignment(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */, decorators, modifiers); + function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= - propagateChildFlags(node.exportClause) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) + ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createNamedExports(elements) { var node = createBaseNode(273 /* SyntaxKind.NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25542,7 +25908,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25555,9 +25921,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */, - /*decorators*/ undefined, - /*modifiers*/ undefined); + var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */); return node; } // @@ -25568,7 +25932,7 @@ var ts; var node = createBaseNode(277 /* SyntaxKind.ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25624,7 +25988,6 @@ var ts; // @api function createJSDocFunctionType(parameters, type) { var node = createBaseSignatureDeclaration(317 /* SyntaxKind.JSDocFunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); @@ -26276,26 +26639,18 @@ var ts; // @api function createPropertyAssignment(name, initializer) { var node = createBaseNamedDeclaration(296 /* SyntaxKind.PropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer); + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdatePropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updatePropertyAssignment(node, name, initializer) { return node.name !== name @@ -26303,31 +26658,32 @@ var ts; ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) : node; } + function finishUpdatePropertyAssignment(updated, original) { + // copy children used only for error reporting + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { var node = createBaseNamedDeclaration(297 /* SyntaxKind.ShorthandPropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.equalsToken = undefined; + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdateShorthandPropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.equalsToken) - updated.equalsToken = original.equalsToken; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { return node.name !== name @@ -26335,6 +26691,17 @@ var ts; ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) : node; } + function finishUpdateShorthandPropertyAssignment(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.equalsToken = original.equalsToken; + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createSpreadAssignment(expression) { var node = createBaseNode(298 /* SyntaxKind.SpreadAssignment */); @@ -26342,7 +26709,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; return node; } // @api @@ -26662,13 +27029,11 @@ var ts; } function createExportDefault(expression) { return createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); } function createExternalModuleExport(exportName) { return createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, createNamedExports([ createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName) @@ -26826,7 +27191,7 @@ var ts; } else if (ts.getEmitFlags(callee) & 4096 /* EmitFlags.HelperName */) { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee, /*optionalChain*/ false); } else if (ts.isPropertyAccessExpression(callee)) { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { @@ -26855,7 +27220,7 @@ var ts; else { // for `a()` target is `a` and thisArg is `void 0` thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); } return { target: target, thisArg: thisArg }; } @@ -26864,9 +27229,7 @@ var ts; // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560) createParenthesizedExpression(createObjectLiteralExpression([ createSetAccessorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, "value", [createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, paramName, /*questionToken*/ undefined, @@ -27168,30 +27531,32 @@ var ts; else { modifierArray = modifiers; } - return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : - ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : - ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : - ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifierArray, node.parameters, node.body) : - ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.type, node.body) : - ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.body) : - ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifierArray, node.parameters, node.type) : - ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : - ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : - ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.type) : - ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifierArray, node.name, node.members) : - ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifierArray, node.name, node.body) : - ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : - ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : - ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifierArray, node.expression) : - ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : - ts.Debug.assertNever(node); + return ts.isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : + ts.isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : + ts.isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : + ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : + ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : + ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : + ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : + ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : + ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : + ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : + ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : + ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : + ts.isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : + ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : + ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : + ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : + ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : + ts.isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : + ts.isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : + ts.isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : + ts.Debug.assertNever(node); } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -27299,10 +27664,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 33562624 /* TransformFlags.PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 134234112 /* TransformFlags.PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -27333,29 +27698,29 @@ var ts; case 208 /* SyntaxKind.CallExpression */: case 209 /* SyntaxKind.NewExpression */: case 204 /* SyntaxKind.ArrayLiteralExpression */: - return 536887296 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; + return -2147450880 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; case 261 /* SyntaxKind.ModuleDeclaration */: - return 589443072 /* TransformFlags.ModuleExcludes */; + return -1941676032 /* TransformFlags.ModuleExcludes */; case 164 /* SyntaxKind.Parameter */: - return 536870912 /* TransformFlags.ParameterExcludes */; + return -2147483648 /* TransformFlags.ParameterExcludes */; case 214 /* SyntaxKind.ArrowFunction */: - return 557748224 /* TransformFlags.ArrowFunctionExcludes */; + return -2072174592 /* TransformFlags.ArrowFunctionExcludes */; case 213 /* SyntaxKind.FunctionExpression */: case 256 /* SyntaxKind.FunctionDeclaration */: - return 591310848 /* TransformFlags.FunctionExcludes */; + return -1937940480 /* TransformFlags.FunctionExcludes */; case 255 /* SyntaxKind.VariableDeclarationList */: - return 537165824 /* TransformFlags.VariableDeclarationListExcludes */; + return -2146893824 /* TransformFlags.VariableDeclarationListExcludes */; case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return 536940544 /* TransformFlags.ClassExcludes */; + return -2147344384 /* TransformFlags.ClassExcludes */; case 171 /* SyntaxKind.Constructor */: - return 591306752 /* TransformFlags.ConstructorExcludes */; + return -1937948672 /* TransformFlags.ConstructorExcludes */; case 167 /* SyntaxKind.PropertyDeclaration */: - return 570433536 /* TransformFlags.PropertyExcludes */; + return -2013249536 /* TransformFlags.PropertyExcludes */; case 169 /* SyntaxKind.MethodDeclaration */: case 172 /* SyntaxKind.GetAccessor */: case 173 /* SyntaxKind.SetAccessor */: - return 574529536 /* TransformFlags.MethodOrAccessorExcludes */; + return -2005057536 /* TransformFlags.MethodOrAccessorExcludes */; case 130 /* SyntaxKind.AnyKeyword */: case 147 /* SyntaxKind.NumberKeyword */: case 158 /* SyntaxKind.BigIntKeyword */: @@ -27375,23 +27740,23 @@ var ts; case 259 /* SyntaxKind.TypeAliasDeclaration */: return -2 /* TransformFlags.TypeExcludes */; case 205 /* SyntaxKind.ObjectLiteralExpression */: - return 536973312 /* TransformFlags.ObjectLiteralExcludes */; + return -2147278848 /* TransformFlags.ObjectLiteralExcludes */; case 292 /* SyntaxKind.CatchClause */: - return 536903680 /* TransformFlags.CatchClauseExcludes */; + return -2147418112 /* TransformFlags.CatchClauseExcludes */; case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: - return 536887296 /* TransformFlags.BindingPatternExcludes */; + return -2147450880 /* TransformFlags.BindingPatternExcludes */; case 211 /* SyntaxKind.TypeAssertionExpression */: case 229 /* SyntaxKind.AsExpression */: case 350 /* SyntaxKind.PartiallyEmittedExpression */: case 212 /* SyntaxKind.ParenthesizedExpression */: case 106 /* SyntaxKind.SuperKeyword */: - return 536870912 /* TransformFlags.OuterExpressionExcludes */; + return -2147483648 /* TransformFlags.OuterExpressionExcludes */; case 206 /* SyntaxKind.PropertyAccessExpression */: case 207 /* SyntaxKind.ElementAccessExpression */: - return 536870912 /* TransformFlags.PropertyAccessExcludes */; + return -2147483648 /* TransformFlags.PropertyAccessExcludes */; default: - return 536870912 /* TransformFlags.NodeExcludes */; + return -2147483648 /* TransformFlags.NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -28801,6 +29166,11 @@ var ts; return node.kind === 126 /* SyntaxKind.AbstractKeyword */; } ts.isAbstractModifier = isAbstractModifier; + /* @internal */ + function isOverrideModifier(node) { + return node.kind === 159 /* SyntaxKind.OverrideKeyword */; + } + ts.isOverrideModifier = isOverrideModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 106 /* SyntaxKind.SuperKeyword */; @@ -29256,6 +29626,10 @@ var ts; return node.kind === 267 /* SyntaxKind.ImportClause */; } ts.isImportClause = isImportClause; + function isImportTypeAssertionContainer(node) { + return node.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */; + } + ts.isImportTypeAssertionContainer = isImportTypeAssertionContainer; function isAssertClause(node) { return node.kind === 293 /* SyntaxKind.AssertClause */; } @@ -29593,7 +29967,7 @@ var ts; (function (ts) { // Compound nodes function createEmptyExports(factory) { - return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); + return factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); } ts.createEmptyExports = createEmptyExports; function createMemberAccessForPropertyName(factory, target, memberName, location) { @@ -29743,13 +30117,13 @@ var ts; return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({ enumerable: factory.createFalse(), configurable: true, - get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, + get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(getAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, /*type*/ undefined, getAccessor.body // TODO: GH#18217 ), getAccessor), getAccessor), - set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, + set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(setAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, @@ -29768,7 +30142,7 @@ var ts; /*original*/ property); } function createExpressionForMethodDeclaration(factory, method, receiver) { - return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken, + return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(ts.getModifiers(method), method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, /*type*/ undefined, method.body // TODO: GH#18217 @@ -30001,7 +30375,6 @@ var ts; } if (namedBindings) { var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText), /*assertClause*/ undefined); ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* EmitFlags.NeverApplyImportHelper */); @@ -30320,33 +30693,50 @@ var ts; } } ts.getJSDocTypeAliasName = getJSDocTypeAliasName; - function canHaveModifiers(node) { + function canHaveIllegalType(node) { var kind = node.kind; - return kind === 164 /* SyntaxKind.Parameter */ - || kind === 166 /* SyntaxKind.PropertySignature */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 168 /* SyntaxKind.MethodSignature */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ + return kind === 171 /* SyntaxKind.Constructor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalType = canHaveIllegalType; + function canHaveIllegalTypeParameters(node) { + var kind = node.kind; + return kind === 171 /* SyntaxKind.Constructor */ || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalTypeParameters = canHaveIllegalTypeParameters; + function canHaveIllegalDecorators(node) { + var kind = node.kind; + return kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 213 /* SyntaxKind.FunctionExpression */ - || kind === 214 /* SyntaxKind.ArrowFunction */ - || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ || kind === 237 /* SyntaxKind.VariableStatement */ - || kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 257 /* SyntaxKind.ClassDeclaration */ || kind === 258 /* SyntaxKind.InterfaceDeclaration */ || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ || kind === 260 /* SyntaxKind.EnumDeclaration */ || kind === 261 /* SyntaxKind.ModuleDeclaration */ || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ || kind === 266 /* SyntaxKind.ImportDeclaration */ - || kind === 271 /* SyntaxKind.ExportAssignment */ - || kind === 272 /* SyntaxKind.ExportDeclaration */; + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ + || kind === 272 /* SyntaxKind.ExportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */; } - ts.canHaveModifiers = canHaveModifiers; + ts.canHaveIllegalDecorators = canHaveIllegalDecorators; + function canHaveIllegalModifiers(node) { + var kind = node.kind; + return kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 179 /* SyntaxKind.FunctionType */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */; + } + ts.canHaveIllegalModifiers = canHaveIllegalModifiers; ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); @@ -30610,6 +31000,14 @@ var ts; } } ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; + function elideNodes(factory, nodes) { + if (nodes === undefined) + return undefined; + if (nodes.length === 0) + return nodes; + return ts.setTextRange(factory.createNodeArray([], nodes.hasTrailingComma), nodes); + } + ts.elideNodes = elideNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -30617,6 +31015,46 @@ var ts; return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range; } ts.setTextRange = setTextRange; + function canHaveModifiers(node) { + var kind = node.kind; + return kind === 163 /* SyntaxKind.TypeParameter */ + || kind === 164 /* SyntaxKind.Parameter */ + || kind === 166 /* SyntaxKind.PropertySignature */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 168 /* SyntaxKind.MethodSignature */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 176 /* SyntaxKind.IndexSignature */ + || kind === 180 /* SyntaxKind.ConstructorType */ + || kind === 213 /* SyntaxKind.FunctionExpression */ + || kind === 214 /* SyntaxKind.ArrowFunction */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 237 /* SyntaxKind.VariableStatement */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 257 /* SyntaxKind.ClassDeclaration */ + || kind === 258 /* SyntaxKind.InterfaceDeclaration */ + || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 260 /* SyntaxKind.EnumDeclaration */ + || kind === 261 /* SyntaxKind.ModuleDeclaration */ + || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 266 /* SyntaxKind.ImportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */ + || kind === 272 /* SyntaxKind.ExportDeclaration */; + } + ts.canHaveModifiers = canHaveModifiers; + function canHaveDecorators(node) { + var kind = node.kind; + return kind === 164 /* SyntaxKind.Parameter */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 257 /* SyntaxKind.ClassDeclaration */; + } + ts.canHaveDecorators = canHaveDecorators; })(ts || (ts = {})); var ts; (function (ts) { @@ -30686,7 +31124,7 @@ var ts; } ts.isFileProbablyExternalModule = isFileProbablyExternalModule; function isAnExternalModuleIndicatorNode(node) { - return hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) + return ts.canHaveModifiers(node) && hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) || ts.isImportDeclaration(node) || ts.isExportAssignment(node) @@ -30735,7 +31173,7 @@ var ts; visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || @@ -30745,79 +31183,128 @@ var ts; case 298 /* SyntaxKind.SpreadAssignment */: return visitNode(cbNode, node.expression); case 164 /* SyntaxKind.Parameter */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 167 /* SyntaxKind.PropertyDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 166 /* SyntaxKind.PropertySignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 296 /* SyntaxKind.PropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.initializer); case 254 /* SyntaxKind.VariableDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || + return visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 203 /* SyntaxKind.BindingElement */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.dotDotDotToken) || + return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: case 176 /* SyntaxKind.IndexSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); + case 180 /* SyntaxKind.ConstructorType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 179 /* SyntaxKind.FunctionType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + return visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 169 /* SyntaxKind.MethodDeclaration */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 168 /* SyntaxKind.MethodSignature */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 171 /* SyntaxKind.Constructor */: + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 172 /* SyntaxKind.GetAccessor */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 256 /* SyntaxKind.FunctionDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 214 /* SyntaxKind.ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.body); case 178 /* SyntaxKind.TypeReference */: @@ -30945,7 +31432,7 @@ var ts; return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); case 237 /* SyntaxKind.VariableStatement */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); case 255 /* SyntaxKind.VariableDeclarationList */: @@ -31010,27 +31497,26 @@ var ts; return visitNode(cbNode, node.expression); case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 258 /* SyntaxKind.InterfaceDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); case 260 /* SyntaxKind.EnumDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); @@ -31038,17 +31524,17 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 261 /* SyntaxKind.ModuleDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); case 266 /* SyntaxKind.ImportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -31062,7 +31548,8 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.value); case 264 /* SyntaxKind.NamespaceExportDeclaration */: - return visitNode(cbNode, node.name); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNode(cbNode, node.name); case 268 /* SyntaxKind.NamespaceImport */: return visitNode(cbNode, node.name); case 274 /* SyntaxKind.NamespaceExport */: @@ -31071,7 +31558,7 @@ var ts; case 273 /* SyntaxKind.NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); case 272 /* SyntaxKind.ExportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -31081,17 +31568,21 @@ var ts; return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); case 271 /* SyntaxKind.ExportAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); case 223 /* SyntaxKind.TemplateExpression */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 233 /* SyntaxKind.TemplateSpan */: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.literal); case 198 /* SyntaxKind.TemplateLiteralType */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 199 /* SyntaxKind.TemplateLiteralTypeSpan */: - return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.literal); case 162 /* SyntaxKind.ComputedPropertyName */: return visitNode(cbNode, node.expression); case 291 /* SyntaxKind.HeritageClause */: @@ -31102,7 +31593,8 @@ var ts; case 277 /* SyntaxKind.ExternalModuleReference */: return visitNode(cbNode, node.expression); case 276 /* SyntaxKind.MissingDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers); case 351 /* SyntaxKind.CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 278 /* SyntaxKind.JsxElement */: @@ -31781,7 +32273,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* NodeFlags.AwaitContext */) - && !!(node.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -31822,7 +32314,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setFields(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); setFields(sourceFile); } @@ -32750,7 +33242,7 @@ var ts; } return parseElement(); } - function currentNode(parsingContext) { + function currentNode(parsingContext, pos) { // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. // // If there is an outstanding parse error that we've encountered, but not attached to @@ -32763,7 +33255,7 @@ var ts; if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } - var node = syntaxCursor.currentNode(scanner.getStartPos()); + var node = syntaxCursor.currentNode(pos !== null && pos !== void 0 ? pos : scanner.getStartPos()); // Can't reuse a missing node. // Can't reuse a node that intersected the change range. // Can't reuse a node that contains a parse error. This is necessary so that we @@ -33038,7 +33530,9 @@ var ts; case 23 /* ParsingContext.ImportOrExportSpecifiers */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 13 /* ParsingContext.JsxAttributes */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 14 /* ParsingContext.JsxChildren */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - default: return [undefined]; // TODO: GH#18217 `default: Debug.assertNever(context);` + case 24 /* ParsingContext.AssertEntries */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_or_string_literal_expected); // AssertionKey. + case 25 /* ParsingContext.Count */: return ts.Debug.fail("ParsingContext.Count used as a context"); // Not a real context, only a marker. + default: ts.Debug.assertNever(context); } } function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { @@ -33354,7 +33848,6 @@ var ts; parseExpected(58 /* SyntaxKind.ColonToken */); } return finishNode(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier? @@ -33480,10 +33973,9 @@ var ts; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : doOutsideOfAwaitContext(parseDecorators); if (token() === 108 /* SyntaxKind.ThisKeyword */) { var node_1 = factory.createParameterDeclaration(decorators, - /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); @@ -33494,12 +33986,12 @@ var ts; } var savedTopLevel = topLevel; topLevel = false; - var modifiers = parseModifiers(); + var modifiers = combineDecoratorsAndModifiers(decorators, parseModifiers()); var dotDotDotToken = parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */); if (!allowAmbiguity && !isParameterNameStart()) { return undefined; } - var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createParameterDeclaration(modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); topLevel = savedTopLevel; return node; } @@ -33651,7 +34143,8 @@ var ts; var parameters = parseBracketedList(16 /* ParsingContext.Parameters */, function () { return parseParameter(/*inOuterAwaitContext*/ false); }, 22 /* SyntaxKind.OpenBracketToken */, 23 /* SyntaxKind.CloseBracketToken */); var type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - var node = factory.createIndexSignature(decorators, modifiers, parameters, type); + var node = factory.createIndexSignature(modifiers, parameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) { @@ -33724,10 +34217,10 @@ var ts; var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */, 4 /* SignatureFlags.Type */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */, 4 /* SignatureFlags.Type */); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); @@ -34365,10 +34858,10 @@ var ts; setDecoratorContext(/*val*/ false); } var pos = getNodePos(); - var expr = parseAssignmentExpressionOrHigher(); + var expr = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); var operatorToken; while ((operatorToken = parseOptionalToken(27 /* SyntaxKind.CommaToken */))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos); + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), pos); } if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -34376,9 +34869,9 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true) : undefined; } - function parseAssignmentExpressionOrHigher() { + function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) { // AssignmentExpression[in,yield]: // 1) ConditionalExpression[?in,?yield] // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] @@ -34404,7 +34897,7 @@ var ts; // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + var arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction); if (arrowExpression) { return arrowExpression; } @@ -34423,7 +34916,7 @@ var ts; // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. if (expr.kind === 79 /* SyntaxKind.Identifier */ && token() === 38 /* SyntaxKind.EqualsGreaterThanToken */) { - return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, /*asyncModifier*/ undefined); } // Now see if we might be in cases '2' or '3'. // If the expression was a LHS expression, and we have an assignment operator, then @@ -34432,10 +34925,10 @@ var ts; // Note: we call reScanGreaterToken so that we get an appropriately merged token // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos); + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); } // It wasn't an assignment or a lambda. This is a conditional expression: - return parseConditionalExpressionRest(expr, pos); + return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction); } function isYieldExpression() { if (token() === 125 /* SyntaxKind.YieldKeyword */) { @@ -34475,7 +34968,7 @@ var ts; nextToken(); if (!scanner.hasPrecedingLineBreak() && (token() === 41 /* SyntaxKind.AsteriskToken */ || isStartOfExpression())) { - return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher()), pos); + return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)), pos); } else { // if the next token is not on the same line as yield. or we don't have an '*' or @@ -34483,10 +34976,9 @@ var ts; return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { ts.Debug.assert(token() === 38 /* SyntaxKind.EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var parameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, identifier, /*questionToken*/ undefined, @@ -34495,11 +34987,11 @@ var ts; finishNode(parameter, identifier.pos); var parameters = createNodeArray([parameter], parameter.pos, parameter.end); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); - var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier, allowReturnTypeInArrowFunction); var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body); return addJSDocComment(finishNode(node, pos)); } - function tryParseParenthesizedArrowFunctionExpression() { + function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var triState = isParenthesizedArrowFunctionExpression(); if (triState === 0 /* Tristate.False */) { // It's definitely not a parenthesized arrow function expression. @@ -34510,8 +35002,8 @@ var ts; // it out, but don't allow any ambiguity, and return 'undefined' if this could be an // expression instead. return triState === 1 /* Tristate.True */ ? - parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) : - tryParse(parsePossibleParenthesizedArrowFunctionExpression); + parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true, /*allowReturnTypeInArrowFunction*/ true) : + tryParse(function () { return parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction); }); } // True -> We definitely expect a parenthesized arrow function here. // False -> There *cannot* be a parenthesized arrow function here. @@ -34576,7 +35068,7 @@ var ts; // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. if (ts.isModifierKind(second) && second !== 131 /* SyntaxKind.AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { - if (lookAhead(function () { return nextToken() === 127 /* SyntaxKind.AsKeyword */; })) { + if (nextToken() === 127 /* SyntaxKind.AsKeyword */) { // https://github.com/microsoft/TypeScript/issues/44466 return 0 /* Tristate.False */; } @@ -34645,25 +35137,25 @@ var ts; return 2 /* Tristate.Unknown */; } } - function parsePossibleParenthesizedArrowFunctionExpression() { + function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var tokenPos = scanner.getTokenPos(); if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) { return undefined; } - var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false); + var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false, allowReturnTypeInArrowFunction); if (!result) { (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos); } return result; } - function tryParseAsyncSimpleArrowFunctionExpression() { + function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() === 131 /* SyntaxKind.AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* Tristate.True */) { var pos = getNodePos(); var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0 /* OperatorPrecedence.Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); } } return undefined; @@ -34687,7 +35179,7 @@ var ts; } return 0 /* Tristate.False */; } - function parseParenthesizedArrowFunctionExpression(allowAmbiguity) { + function parseParenthesizedArrowFunctionExpression(allowAmbiguity, allowReturnTypeInArrowFunction) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiersForArrowFunction(); @@ -34722,6 +35214,7 @@ var ts; return undefined; } } + var hasReturnColon = token() === 58 /* SyntaxKind.ColonToken */; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) { return undefined; @@ -34750,12 +35243,37 @@ var ts; var lastToken = token(); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); var body = (lastToken === 38 /* SyntaxKind.EqualsGreaterThanToken */ || lastToken === 18 /* SyntaxKind.OpenBraceToken */) - ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier)) + ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier(); + // Given: + // x ? y => ({ y }) : z => ({ z }) + // We try to parse the body of the first arrow function by looking at: + // ({ y }) : z => ({ z }) + // This is a valid arrow function with "z" as the return type. + // + // But, if we're in the true side of a conditional expression, this colon + // terminates the expression, so we cannot allow a return type if we aren't + // certain whether or not the preceding text was parsed as a parameter list. + // + // For example, + // a() ? (b: number, c?: string): void => d() : e + // is determined by isParenthesizedArrowFunctionExpression to unambiguously + // be an arrow expression, so we allow a return type. + if (!allowReturnTypeInArrowFunction && hasReturnColon) { + // However, if the arrow function we were able to parse is followed by another colon + // as in: + // a ? (x): string => x : null + // Then allow the arrow function, and treat the second colon as terminating + // the conditional expression. It's okay to do this because this code would + // be a syntax error in JavaScript (as the second colon shouldn't be there). + if (token() !== 58 /* SyntaxKind.ColonToken */) { + return undefined; + } + } var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseArrowFunctionExpressionBody(isAsync) { + function parseArrowFunctionExpressionBody(isAsync, allowReturnTypeInArrowFunction) { if (token() === 18 /* SyntaxKind.OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* SignatureFlags.Await */ : 0 /* SignatureFlags.None */); } @@ -34783,12 +35301,12 @@ var ts; var savedTopLevel = topLevel; topLevel = false; var node = isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + ? doInAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }) + : doOutsideOfAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }); topLevel = savedTopLevel; return node; } - function parseConditionalExpressionRest(leftOperand, pos) { + function parseConditionalExpressionRest(leftOperand, pos, allowReturnTypeInArrowFunction) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. var questionToken = parseOptionalToken(57 /* SyntaxKind.QuestionToken */); if (!questionToken) { @@ -34797,8 +35315,8 @@ var ts; // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. var colonToken; - return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) - ? parseAssignmentExpressionOrHigher() + return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ false); }), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) + ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(79 /* SyntaxKind.Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* SyntaxKind.ColonToken */))), pos); } function parseBinaryExpressionOrHigher(precedence) { @@ -35183,6 +35701,9 @@ var ts; var typeArguments = tryParse(parseTypeArgumentsInExpression); if (typeArguments !== undefined) { parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments); + if (!isTemplateStartOfTaggedTemplate()) { + expression = factory.createExpressionWithTypeArguments(expression, typeArguments); + } } } if (token() === 20 /* SyntaxKind.OpenParenToken */ || token() === 24 /* SyntaxKind.DotToken */ || token() === 22 /* SyntaxKind.OpenBracketToken */) { @@ -35395,9 +35916,22 @@ var ts; } scanJsxIdentifier(); var pos = getNodePos(); - return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 63 /* SyntaxKind.EqualsToken */ ? undefined : - scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */ ? parseLiteralNode() : - parseJsxExpression(/*inExpressionContext*/ true)), pos); + return finishNode(factory.createJsxAttribute(parseIdentifierName(), parseJsxAttributeValue()), pos); + } + function parseJsxAttributeValue() { + if (token() === 63 /* SyntaxKind.EqualsToken */) { + if (scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */) { + return parseLiteralNode(); + } + if (token() === 18 /* SyntaxKind.OpenBraceToken */) { + return parseJsxExpression(/*inExpressionContext*/ true); + } + if (token() === 29 /* SyntaxKind.LessThanToken */) { + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + parseErrorAtCurrentToken(ts.Diagnostics.or_JSX_element_expected); + } + return undefined; } function parseJsxSpreadAttribute() { var pos = getNodePos(); @@ -35487,6 +36021,11 @@ var ts; if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) { parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers); } + if (ts.isExpressionWithTypeArguments(expression) && expression.typeArguments) { + var pos_2 = expression.typeArguments.pos - 1; + var end = ts.skipTrivia(sourceText, expression.typeArguments.end) + 1; + parseErrorAt(pos_2, end, ts.Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access); + } return finishNode(propertyAccess, pos); } function parseElementAccessExpressionRest(pos, expression, questionDotToken) { @@ -35612,10 +36151,11 @@ var ts; } nextToken(); var typeArguments = parseDelimitedList(20 /* ParsingContext.TypeArguments */, parseType); - if (!parseExpected(31 /* SyntaxKind.GreaterThanToken */)) { + if (reScanGreaterToken() !== 31 /* SyntaxKind.GreaterThanToken */) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } + nextToken(); // We successfully parsed a type argument list. The next token determines whether we want to // treat it as such. If the type argument list is followed by `(` or a template literal, as in // `f(42)`, we favor the type argument interpretation even though JavaScript would view @@ -35629,9 +36169,18 @@ var ts; case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: // foo `...` case 15 /* SyntaxKind.TemplateHead */: // foo `...${100}...` return true; + // A type argument list followed by `<` never makes sense, and a type argument list followed + // by `>` is ambiguous with a (re-scanned) `>>` operator, so we disqualify both. Also, in + // this context, `+` and `-` are unary operators, not binary operators. + case 29 /* SyntaxKind.LessThanToken */: + case 31 /* SyntaxKind.GreaterThanToken */: + case 39 /* SyntaxKind.PlusToken */: + case 40 /* SyntaxKind.MinusToken */: + return false; } - // Consider something a type argument list only if the following token can't start an expression. - return !isStartOfExpression(); + // We favor the type argument list interpretation when it is immediately followed by + // a line break, a binary operator, or something that can't start an expression. + return scanner.hasPrecedingLineBreak() || isBinaryOperator() || !isStartOfExpression(); } function parsePrimaryExpression() { switch (token()) { @@ -35690,13 +36239,13 @@ var ts; function parseSpreadElement() { var pos = getNodePos(); parseExpected(25 /* SyntaxKind.DotDotDotToken */); - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createSpreadElement(expression), pos); } function parseArgumentOrArrayLiteralElement() { return token() === 25 /* SyntaxKind.DotDotDotToken */ ? parseSpreadElement() : token() === 27 /* SyntaxKind.CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) : - parseAssignmentExpressionOrHigher(); + parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); @@ -35714,16 +36263,16 @@ var ts; var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); if (parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */)) { - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc); } var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } var asteriskToken = parseOptionalToken(41 /* SyntaxKind.AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -35743,7 +36292,7 @@ var ts; var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* SyntaxKind.ColonToken */); if (isShorthandPropertyAssignment) { var equalsToken = parseOptionalToken(63 /* SyntaxKind.EqualsToken */); - var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined; + var objectAssignmentInitializer = equalsToken ? allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }) : undefined; node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer); // Save equals token for error reporting. // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful. @@ -35751,11 +36300,11 @@ var ts; } else { parseExpected(58 /* SyntaxKind.ColonToken */); - var initializer = allowInAnd(parseAssignmentExpressionOrHigher); + var initializer = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); node = factory.createPropertyAssignment(name, initializer); } // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; node.questionToken = questionToken; node.exclamationToken = exclamationToken; @@ -35815,6 +36364,9 @@ var ts; typeArguments = expression.typeArguments; expression = expression.expression; } + if (token() === 28 /* SyntaxKind.QuestionDotToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, ts.getTextOfNodeFromSourceText(sourceText, expression)); + } var argumentList = token() === 20 /* SyntaxKind.OpenParenToken */ ? parseArgumentList() : undefined; return finishNode(factory.createNewExpression(expression, typeArguments, argumentList), pos); } @@ -35925,7 +36477,7 @@ var ts; } var node; if (awaitToken ? parseExpected(160 /* SyntaxKind.OfKeyword */) : parseOptional(160 /* SyntaxKind.OfKeyword */)) { - var expression = allowInAnd(parseAssignmentExpressionOrHigher); + var expression = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); parseExpected(21 /* SyntaxKind.CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); } @@ -36330,24 +36882,19 @@ var ts; return modifier.kind === 135 /* SyntaxKind.DeclareKeyword */; } function parseDeclaration() { - // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner - // if we can't reuse the declaration, so that we don't do this work twice? - // // `parseListElement` attempted to get the reused node at this position, // but the ambient context flag was not yet set, so the node appeared // not reusable in that context. - var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier); - if (isAmbient) { - var node = tryReuseAmbientDeclaration(); - if (node) { - return node; - } - } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var decorators = parseDecorators(); var modifiers = parseModifiers(); + var isAmbient = ts.some(modifiers, isDeclareModifier); if (isAmbient) { + var node = tryReuseAmbientDeclaration(pos); + if (node) { + return node; + } for (var _i = 0, _a = modifiers; _i < _a.length; _i++) { var m = _a[_i]; m.flags |= 16777216 /* NodeFlags.Ambient */; @@ -36358,9 +36905,9 @@ var ts; return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); } } - function tryReuseAmbientDeclaration() { + function tryReuseAmbientDeclaration(pos) { return doInsideOfContext(16777216 /* NodeFlags.Ambient */, function () { - var node = currentNode(parsingContext); + var node = currentNode(parsingContext, pos); if (node) { return consumeNode(node); } @@ -36405,7 +36952,7 @@ var ts; // would follow. For recovery and error reporting purposes, return an incomplete declaration. var missing = createMissingNode(276 /* SyntaxKind.MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); - missing.decorators = decorators; + missing.illegalDecorators = decorators; missing.modifiers = modifiers; return missing; } @@ -36417,9 +36964,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* SyntaxKind.StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 18 /* SyntaxKind.OpenBraceToken */ && canParseSemicolon()) { - parseSemicolon(); - return; + if (token() !== 18 /* SyntaxKind.OpenBraceToken */) { + if (flags & 4 /* SignatureFlags.Type */) { + parseTypeMemberSemicolon(); + return; + } + if (canParseSemicolon()) { + parseSemicolon(); + return; + } } return parseFunctionBlock(flags, diagnosticMessage); } @@ -36542,7 +37095,7 @@ var ts; parseSemicolon(); var node = factory.createVariableStatement(modifiers, declarationList); // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker. - node.decorators = decorators; + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36561,7 +37114,8 @@ var ts; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); setAwaitContext(savedAwaitContext); - var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + var node = factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseConstructorName() { @@ -36582,8 +37136,9 @@ var ts; var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */, ts.Diagnostics.or_expected); - var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body); - // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker. + var node = factory.createConstructorDeclaration(modifiers, parameters, body); + // Attach invalid nodes if they exist so that we can report them in the grammar checker. + node.illegalDecorators = decorators; node.typeParameters = typeParameters; node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36597,7 +37152,7 @@ var ts; var parameters = parseParameters(isGenerator | isAsync); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + var node = factory.createMethodDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); // An exclamation token on a method is invalid syntax and will be handled by the grammar checker node.exclamationToken = exclamationToken; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36607,7 +37162,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = doOutsideOfContext(8192 /* NodeFlags.YieldContext */ | 32768 /* NodeFlags.AwaitContext */ | 4096 /* NodeFlags.DisallowInContext */, parseInitializer); parseSemicolonAfterPropertyName(name, type, initializer); - var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer); + var node = factory.createPropertyDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, questionToken || exclamationToken, type, initializer); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36621,18 +37176,18 @@ var ts; } return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken); } - function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) { + function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind, flags) { var name = parsePropertyName(); var typeParameters = parseTypeParameters(); var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); - var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */); + var body = parseFunctionBlockOrSemicolon(flags); var node = kind === 172 /* SyntaxKind.GetAccessor */ - ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) - : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); + ? factory.createGetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, type, body) + : factory.createSetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 173 /* SyntaxKind.SetAccessor */) + if (ts.isSetAccessorDeclaration(node)) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -36698,7 +37253,10 @@ var ts; function parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers) { parseExpectedToken(124 /* SyntaxKind.StaticKeyword */); var body = parseClassStaticBlockBody(); - return withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(decorators, modifiers, body), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(body), pos), hasJSDoc); + node.illegalDecorators = decorators; + node.modifiers = modifiers; + return node; } function parseClassStaticBlockBody() { var savedYieldContext = inYieldContext(); @@ -36761,6 +37319,15 @@ var ts; } return finishNode(factory.createToken(kind), pos); } + function combineDecoratorsAndModifiers(decorators, modifiers) { + if (!decorators) + return modifiers; + if (!modifiers) + return decorators; + var decoratorsAndModifiers = factory.createNodeArray(ts.concatenate(decorators, modifiers)); + ts.setTextRangePosEnd(decoratorsAndModifiers, decorators.pos, modifiers.end); + return decoratorsAndModifiers; + } /* * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect @@ -36801,10 +37368,10 @@ var ts; return parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers); } if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } if (token() === 134 /* SyntaxKind.ConstructorKeyword */ || token() === 10 /* SyntaxKind.StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -36869,8 +37436,8 @@ var ts; } setAwaitContext(savedAwaitContext); var node = kind === 257 /* SyntaxKind.ClassDeclaration */ - ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) - : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); + ? factory.createClassDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members) + : factory.createClassExpression(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseNameOfClassDeclarationOrExpression() { @@ -36927,7 +37494,8 @@ var ts; var typeParameters = parseTypeParameters(); var heritageClauses = parseHeritageClauses(); var members = parseObjectTypeMembers(); - var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = factory.createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36937,7 +37505,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var type = token() === 138 /* SyntaxKind.IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); parseSemicolon(); - var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type); + var node = factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } // In an ambient declaration, the grammar only allows integer literals as initializers. @@ -36962,7 +37531,8 @@ var ts; else { members = createMissingList(); } - var node = factory.createEnumDeclaration(decorators, modifiers, name, members); + var node = factory.createEnumDeclaration(modifiers, name, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleBlock() { @@ -36985,7 +37555,8 @@ var ts; var body = parseOptional(24 /* SyntaxKind.DotToken */) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NodeFlags.NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -37007,7 +37578,8 @@ var ts; else { parseSemicolon(); } - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -37047,7 +37619,7 @@ var ts; parseSemicolon(); var node = factory.createNamespaceExportDeclaration(name); // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -37086,14 +37658,15 @@ var ts; assertClause = parseAssertClause(); } parseSemicolon(); - var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause); + var node = factory.createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAssertEntry() { var pos = getNodePos(); var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* SyntaxKind.StringLiteral */); parseExpected(58 /* SyntaxKind.ColonToken */); - var value = parseAssignmentExpressionOrHigher(); + var value = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createAssertEntry(name, value), pos); } function parseAssertClause(skipAssertKeyword) { @@ -37130,7 +37703,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var moduleReference = parseModuleReference(); parseSemicolon(); - var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference); + var node = factory.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference); + node.illegalDecorators = decorators; var finished = withJSDoc(finishNode(node, pos), hasJSDoc); return finished; } @@ -37319,7 +37893,8 @@ var ts; } parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + var node = factory.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) { @@ -37332,10 +37907,11 @@ var ts; else { parseExpected(88 /* SyntaxKind.DefaultKeyword */); } - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression); + var node = factory.createExportAssignment(modifiers, isExportEquals, expression); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } var ParsingContext; @@ -38126,7 +38702,6 @@ var ts; if (parseOptional(24 /* SyntaxKind.DotToken */)) { var body = parseJSDocTypeNameWithNamespace(/*nested*/ true); var jsDocNamespaceNode = factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NodeFlags.NestedNamespace */ : undefined); return finishNode(jsDocNamespaceNode, pos); } @@ -38563,10 +39138,10 @@ var ts; } function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { - var pos_2 = node.pos; + var pos_3 = node.pos; var visitNode_1 = function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; + ts.Debug.assert(child.pos >= pos_3); + pos_3 = child.end; }; if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -38575,7 +39150,7 @@ var ts; } } forEachChild(node, visitNode_1); - ts.Debug.assert(pos_2 <= node.end); + ts.Debug.assert(pos_3 <= node.end); } } function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { @@ -39173,6 +39748,7 @@ var ts; ["es2022.error", "lib.es2022.error.d.ts"], ["es2022.intl", "lib.es2022.intl.d.ts"], ["es2022.object", "lib.es2022.object.d.ts"], + ["es2022.sharedmemory", "lib.es2022.sharedmemory.d.ts"], ["es2022.string", "lib.es2022.string.d.ts"], ["esnext.array", "lib.es2022.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], @@ -39386,6 +39962,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, defaultValueDescription: false, @@ -39420,12 +39997,40 @@ var ts; affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, defaultValueDescription: 0 /* ScriptTarget.ES3 */, }; + /*@internal*/ + ts.moduleOptionDeclaration = { + name: "module", + shortName: "m", + type: new ts.Map(ts.getEntries({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + es2020: ts.ModuleKind.ES2020, + es2022: ts.ModuleKind.ES2022, + esnext: ts.ModuleKind.ESNext, + node16: ts.ModuleKind.Node16, + nodenext: ts.ModuleKind.NodeNext, + })), + affectsModuleResolution: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Modules, + description: ts.Diagnostics.Specify_what_module_code_is_generated, + defaultValueDescription: undefined, + }; var commandOptionsWithoutBuild = [ // CommandLine only options { @@ -39487,37 +40092,14 @@ var ts; category: ts.Diagnostics.Command_line_Options, affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, isCommandLineOnly: true, description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, defaultValueDescription: false, }, // Basic ts.targetOptionDeclaration, - { - name: "module", - shortName: "m", - type: new ts.Map(ts.getEntries({ - none: ts.ModuleKind.None, - commonjs: ts.ModuleKind.CommonJS, - amd: ts.ModuleKind.AMD, - system: ts.ModuleKind.System, - umd: ts.ModuleKind.UMD, - es6: ts.ModuleKind.ES2015, - es2015: ts.ModuleKind.ES2015, - es2020: ts.ModuleKind.ES2020, - es2022: ts.ModuleKind.ES2022, - esnext: ts.ModuleKind.ESNext, - node16: ts.ModuleKind.Node16, - nodenext: ts.ModuleKind.NodeNext, - })), - affectsModuleResolution: true, - affectsEmit: true, - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Modules, - description: ts.Diagnostics.Specify_what_module_code_is_generated, - defaultValueDescription: undefined, - }, + ts.moduleOptionDeclaration, { name: "lib", type: "list", @@ -39554,6 +40136,7 @@ var ts; type: jsxOptionMap, affectsSourceFile: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -39566,6 +40149,7 @@ var ts; shortName: "d", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -39576,6 +40160,7 @@ var ts; name: "declarationMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -39586,6 +40171,7 @@ var ts; name: "emitDeclarationOnly", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, @@ -39596,6 +40182,7 @@ var ts; name: "sourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -39605,6 +40192,9 @@ var ts; name: "outFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, showInSimplifiedHelpView: true, @@ -39616,6 +40206,8 @@ var ts; name: "outDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, showInSimplifiedHelpView: true, @@ -39626,6 +40218,8 @@ var ts; name: "rootDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Modules, @@ -39636,6 +40230,8 @@ var ts; name: "composite", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isTSConfigOnly: true, category: ts.Diagnostics.Projects, transpileOptionValue: undefined, @@ -39646,6 +40242,8 @@ var ts; name: "tsBuildInfoFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, category: ts.Diagnostics.Projects, @@ -39657,6 +40255,7 @@ var ts; name: "removeComments", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -39675,6 +40274,7 @@ var ts; name: "importHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, defaultValueDescription: false, @@ -39688,6 +40288,7 @@ var ts; })), affectsEmit: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, defaultValueDescription: 0 /* ImportsNotUsedAsValues.Remove */, @@ -39696,6 +40297,7 @@ var ts; name: "downlevelIteration", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, defaultValueDescription: false, @@ -39714,6 +40316,9 @@ var ts; type: "boolean", // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here // The value of each strictFlag depends on own strictFlag value or this and never accessed directly. + // But we need to store `strict` in builf info, even though it won't be examined directly, so that the + // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_all_strict_type_checking_options, @@ -39723,6 +40328,7 @@ var ts; name: "noImplicitAny", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, @@ -39732,6 +40338,7 @@ var ts; name: "strictNullChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_type_checking_take_into_account_null_and_undefined, @@ -39740,6 +40347,8 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, @@ -39748,6 +40357,8 @@ var ts; { name: "strictBindCallApply", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, @@ -39757,6 +40368,7 @@ var ts; name: "strictPropertyInitialization", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, @@ -39766,6 +40378,7 @@ var ts; name: "noImplicitThis", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, @@ -39775,6 +40388,7 @@ var ts; name: "useUnknownInCatchVariables", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, @@ -39784,6 +40398,8 @@ var ts; name: "alwaysStrict", type: "boolean", affectsSourceFile: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_use_strict_is_always_emitted, @@ -39794,6 +40410,7 @@ var ts; name: "noUnusedLocals", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, defaultValueDescription: false, @@ -39802,6 +40419,7 @@ var ts; name: "noUnusedParameters", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, defaultValueDescription: false, @@ -39810,6 +40428,7 @@ var ts; name: "exactOptionalPropertyTypes", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, defaultValueDescription: false, @@ -39818,6 +40437,7 @@ var ts; name: "noImplicitReturns", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, defaultValueDescription: false, @@ -39827,6 +40447,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, defaultValueDescription: false, @@ -39835,6 +40456,7 @@ var ts; name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, defaultValueDescription: false, @@ -39843,6 +40465,7 @@ var ts; name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, defaultValueDescription: false, @@ -39850,6 +40473,8 @@ var ts; { name: "noPropertyAccessFromIndexSignature", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: false, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, @@ -39935,6 +40560,7 @@ var ts; name: "allowSyntheticDefaultImports", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, defaultValueDescription: ts.Diagnostics.module_system_or_esModuleInterop @@ -39944,6 +40570,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, @@ -39960,6 +40587,7 @@ var ts; name: "allowUmdGlobalAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules, defaultValueDescription: false, @@ -39981,6 +40609,7 @@ var ts; name: "sourceRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code, @@ -39989,6 +40618,7 @@ var ts; name: "mapRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, @@ -39997,6 +40627,7 @@ var ts; name: "inlineSourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -40005,6 +40636,7 @@ var ts; name: "inlineSources", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -40014,6 +40646,7 @@ var ts; name: "experimentalDecorators", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, defaultValueDescription: false, @@ -40023,6 +40656,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, defaultValueDescription: false, @@ -40047,6 +40681,7 @@ var ts; type: "string", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, @@ -40064,6 +40699,9 @@ var ts; name: "out", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: false, // for correct behaviour, please use outFile category: ts.Diagnostics.Backwards_Compatibility, @@ -40075,6 +40713,7 @@ var ts; name: "reactNamespace", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, defaultValueDescription: "`React`", @@ -40082,6 +40721,8 @@ var ts; { name: "skipDefaultLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, defaultValueDescription: false, @@ -40097,6 +40738,7 @@ var ts; name: "emitBOM", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, defaultValueDescription: false, @@ -40108,6 +40750,7 @@ var ts; lf: 1 /* NewLineKind.LineFeed */ })), affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Set_the_newline_character_for_emitting_files, @@ -40117,6 +40760,7 @@ var ts; name: "noErrorTruncation", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_truncating_types_in_error_messages, defaultValueDescription: false, @@ -40147,6 +40791,7 @@ var ts; name: "stripInternal", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, defaultValueDescription: false, @@ -40187,6 +40832,7 @@ var ts; name: "noImplicitUseStrict", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, defaultValueDescription: false, @@ -40195,6 +40841,7 @@ var ts; name: "noEmitHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, defaultValueDescription: false, @@ -40203,6 +40850,7 @@ var ts; name: "noEmitOnError", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, @@ -40212,6 +40860,7 @@ var ts; name: "preserveConstEnums", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, defaultValueDescription: false, @@ -40220,6 +40869,8 @@ var ts; name: "declarationDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, category: ts.Diagnostics.Emit, @@ -40229,6 +40880,8 @@ var ts; { name: "skipLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_all_d_ts_files, defaultValueDescription: false, @@ -40238,6 +40891,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unused_labels, defaultValueDescription: undefined, @@ -40247,6 +40901,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code, defaultValueDescription: undefined, @@ -40255,6 +40910,7 @@ var ts; name: "suppressExcessPropertyErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, defaultValueDescription: false, @@ -40263,6 +40919,7 @@ var ts; name: "suppressImplicitAnyIndexErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, defaultValueDescription: false, @@ -40287,6 +40944,7 @@ var ts; name: "noStrictGenericChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, defaultValueDescription: false, @@ -40296,6 +40954,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, defaultValueDescription: ts.Diagnostics.true_for_ES2022_and_above_including_ESNext @@ -40304,6 +40963,7 @@ var ts; name: "preserveValueImports", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, defaultValueDescription: false, @@ -40347,6 +41007,8 @@ var ts; /* @internal */ ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; }); /* @internal */ + ts.affectsDeclarationPathOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsDeclarationPath; }); + /* @internal */ ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); /* @internal */ ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { @@ -41169,7 +41831,7 @@ var ts; return undefined; if (ts.length(specs) !== 1) return specs; - if (specs[0] === "**/*") + if (specs[0] === ts.defaultIncludeSpec) return undefined; return specs; } @@ -41202,6 +41864,7 @@ var ts; return optionDefinition.type; } } + /* @internal */ function getNameOfCompilerOptionValue(value, customTypeMap) { // There is a typeMap associated with this command-line option so use it to map value back to its name return ts.forEachEntry(customTypeMap, function (mapValue, key) { @@ -41210,6 +41873,7 @@ var ts; } }); } + ts.getNameOfCompilerOptionValue = getNameOfCompilerOptionValue; function serializeCompilerOptions(options, pathOptions) { return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); } @@ -41447,6 +42111,8 @@ var ts; // until consistent casing errors are reported return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } + /*@internal*/ + ts.defaultIncludeSpec = "**/*"; /** * Parse the contents of a config file from json or json source file (tsconfig.json). * @param json The contents of the config file to parse @@ -41512,6 +42178,7 @@ var ts; } var includeSpecs = toPropValue(getSpecsFromRaw("include")); var excludeOfRaw = getSpecsFromRaw("exclude"); + var isDefaultIncludeSpec = false; var excludeSpecs = toPropValue(excludeOfRaw); if (excludeOfRaw === "no-prop" && raw.compilerOptions) { var outDir = raw.compilerOptions.outDir; @@ -41521,7 +42188,8 @@ var ts; } } if (filesSpecs === undefined && includeSpecs === undefined) { - includeSpecs = ["**/*"]; + includeSpecs = [ts.defaultIncludeSpec]; + isDefaultIncludeSpec = true; } var validatedIncludeSpecs, validatedExcludeSpecs; // The exclude spec list is converted into a regular expression, which allows us to quickly @@ -41540,7 +42208,8 @@ var ts; validatedFilesSpec: ts.filter(filesSpecs, ts.isString), validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, - pathPatterns: undefined, // Initialized on first use + pathPatterns: undefined, + isDefaultIncludeSpec: isDefaultIncludeSpec, }; } function getFileNames(basePath) { @@ -42200,7 +42869,7 @@ var ts; } if (ts.isImplicitGlob(spec.substring(spec.lastIndexOf(ts.directorySeparator) + 1))) { return { - key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec), + key: ts.removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec)), flags: 1 /* WatchDirectoryFlags.Recursive */ }; } @@ -42370,16 +43039,18 @@ var ts; ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, diagnostics, resultFromCache) { - var _a; + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache) { + var _a, _b; if (resultFromCache) { (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = resultFromCache.affectingLocations).push.apply(_b, affectingLocations); return resultFromCache; } return { resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations, - resolutionDiagnostics: diagnostics + affectingLocations: affectingLocations, + resolutionDiagnostics: diagnostics, }; } function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { @@ -42568,6 +43239,7 @@ var ts; } } var failedLookupLocations = []; + var affectingLocations = []; var features = getDefaultNodeResolutionFeatures(options); // Unlike `import` statements, whose mode-calculating APIs are all guaranteed to return `undefined` if we're in an un-mode-ed module resolution // setting, type references will return their target mode regardless of options because of how the parser works, so we guard against the mode being @@ -42586,6 +43258,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -42602,15 +43275,17 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + var pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host); resolvedTypeReferenceDirective = { primary: primary, - resolvedFileName: resolvedFileName, - originalPath: arePathsEqual(fileName, resolvedFileName, host) ? undefined : fileName, + // If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedFileName: pathsAreEqual ? fileName : resolvedFileName, + originalPath: pathsAreEqual ? undefined : fileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName), }; } - result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, resolutionDiagnostics: diagnostics }; + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, affectingLocations: affectingLocations, resolutionDiagnostics: diagnostics }; perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, /*mode*/ resolutionMode, result); if (traceEnabled) traceResult(result); @@ -42685,17 +43360,7 @@ var ts; * Does not try `@types/${packageName}` - use a second pass if needed. */ function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ts.emptyArray, - features: NodeResolutionFeatures.None, - requestContainingDirectory: containingDirectory, - reportDiagnostic: ts.noop - }; + var moduleResolutionState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); return ts.forEachAncestorDirectory(containingDirectory, function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var nodeModulesFolder = ts.combinePaths(ancestorDirectory, "node_modules"); @@ -42792,7 +43457,7 @@ var ts; ts.createCacheWithRedirects = createCacheWithRedirects; function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { var cache; - return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries }; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries, getInternalMap: getInternalMap }; function getPackageJsonInfo(packageJsonPath) { return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); } @@ -42806,6 +43471,9 @@ var ts; var iter = cache === null || cache === void 0 ? void 0 : cache.entries(); return iter ? ts.arrayFrom(iter) : []; } + function getInternalMap() { + return cache; + } } function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); @@ -42909,15 +43577,18 @@ var ts; } ts.zipToModeAwareCache = zipToModeAwareCache; function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; }, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); - moduleNameToDirectoryMap.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + } function update(options) { updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); } @@ -42993,13 +43664,16 @@ var ts; } ts.createModuleResolutionCache = createModuleResolutionCache; function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { clear: clear, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + } } ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { @@ -43305,16 +43979,20 @@ var ts; function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.NodeNextDefault, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); + var tsconfigExtensions = [Extensions.TSConfig]; function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { var containingDirectory = ts.getDirectoryPath(containingFile); // es module file or cjs-like input file, use a variant of the legacy cjs resolver that supports the selected modern features var esmMode = resolutionMode === ts.ModuleKind.ESNext ? NodeResolutionFeatures.EsmMode : 0; - return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions, redirectedReference); + var extensions = compilerOptions.noDtsResolution ? [Extensions.TsOnly, Extensions.JavaScript] : tsExtensions; + if (compilerOptions.resolveJsonModule) { + extensions = __spreadArray(__spreadArray([], extensions, true), [Extensions.Json], false); + } + return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference); } - var jsOnlyExtensions = [Extensions.JavaScript]; - var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; - var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); - var tsconfigExtensions = [Extensions.TSConfig]; function tryResolveJSModuleWorker(moduleName, initialDir, host) { return nodeModuleNameResolverWorker(NodeResolutionFeatures.None, moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); } @@ -43340,6 +44018,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; // conditions are only used by the node16/nodenext resolver - there's no priority order in the list, //it's essentially a set (priority is determined by object insertion order in the object we look at). var conditions = features & NodeResolutionFeatures.EsmMode ? ["node", "import", "types"] : ["node", "require", "types"]; @@ -43352,6 +44031,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -43359,7 +44039,7 @@ var ts; reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; 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, diagnostics, state.resultFromCache); + 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) { var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); @@ -43385,8 +44065,10 @@ var ts; var resolvedValue = resolved_1.value; if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - var originalPath = arePathsEqual(path, resolvedValue.path, host) ? undefined : resolvedValue.path; - resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath }); + var pathsAreEqual = arePathsEqual(path, resolvedValue.path, host); + var originalPath = pathsAreEqual ? undefined : resolvedValue.path; + // If the path and realpath are differing only in casing prefer path so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedValue = __assign(__assign({}, resolvedValue), { path: pathsAreEqual ? resolvedValue.path : path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; @@ -43649,17 +44331,9 @@ var ts; var entrypoints; var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript; var features = getDefaultNodeResolutionFeatures(options); - var requireState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ["node", "require", "types"], - features: features, - requestContainingDirectory: packageJsonInfo.packageDirectory, - reportDiagnostic: ts.noop - }; + var requireState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); + requireState.conditions = ["node", "require", "types"]; + requireState.requestContainingDirectory = packageJsonInfo.packageDirectory; var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, /*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths); entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path); @@ -43732,22 +44406,27 @@ var ts; } } } - /** - * A function for locating the package.json scope for a given path - */ /*@internal*/ - function getPackageScopeForPath(fileName, packageJsonInfoCache, host, options) { - var state = { + function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) { + return { host: host, compilerOptions: options, traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], + failedLookupLocations: ts.noopPush, + affectingLocations: ts.noopPush, packageJsonInfoCache: packageJsonInfoCache, - features: 0, - conditions: [], + features: NodeResolutionFeatures.None, + conditions: ts.emptyArray, requestContainingDirectory: undefined, reportDiagnostic: ts.noop }; + } + ts.getTemporaryModuleResolutionState = getTemporaryModuleResolutionState; + /** + * A function for locating the package.json scope for a given path + */ + /*@internal*/ + function getPackageScopeForPath(fileName, state) { var parts = ts.getPathComponents(fileName); parts.pop(); while (parts.length > 0) { @@ -43774,6 +44453,7 @@ var ts; if (typeof existing !== "boolean") { if (traceEnabled) trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + state.affectingLocations.push(packageJsonPath); return existing; } else { @@ -43792,6 +44472,7 @@ var ts; var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined }; (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + state.affectingLocations.push(packageJsonPath); return result; } else { @@ -43916,7 +44597,7 @@ var ts; var _a, _b; var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope || !scope.packageJsonContent.exports) { return undefined; } @@ -43975,7 +44656,7 @@ var ts; } var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath); @@ -43997,13 +44678,38 @@ var ts; } return toSearchResult(/*value*/ undefined); } + /** + * @internal + * From https://github.com/nodejs/node/blob/8f39f51cbbd3b2de14b9ee896e26421cc5b20121/lib/internal/modules/esm/resolve.js#L722 - + * "longest" has some nuance as to what "longest" means in the presence of pattern trailers + */ + function comparePatternKeys(a, b) { + var aPatternIndex = a.indexOf("*"); + var bPatternIndex = b.indexOf("*"); + var baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + var baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + if (baseLenA > baseLenB) + return -1; + if (baseLenB > baseLenA) + return 1; + if (aPatternIndex === -1) + return 1; + if (bPatternIndex === -1) + return -1; + if (a.length > b.length) + return -1; + if (b.length > a.length) + return 1; + return 0; + } + ts.comparePatternKeys = comparePatternKeys; function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { 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); } - var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), function (a, b) { return a.length - b.length; }); + 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++) { var potentialTarget = expandingKeys_1[_i]; if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) { @@ -44322,8 +45028,8 @@ var ts; var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths); if (!pathAndExtension && packageInfo - && packageInfo.packageJsonContent.exports === undefined - && packageInfo.packageJsonContent.main === undefined + // eslint-disable-next-line no-null/no-null + && (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null) && state.features & NodeResolutionFeatures.EsmMode) { // EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume // a default `index.js` entrypoint if no `main` or `exports` are present @@ -44432,12 +45138,25 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: cache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: containingDirectory, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, + /*isExternalLibraryImport*/ false, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { @@ -44480,10 +45199,23 @@ var ts; trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; + var affectingLocations = []; var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: undefined, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: packageJsonInfoCache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: undefined, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false, /*cache*/ undefined, /*redirectedReference*/ undefined); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved, + /*isExternalLibraryImport*/ true, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -44849,7 +45581,7 @@ var ts; case 164 /* SyntaxKind.Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind, ", expected JSDocFunctionType"); }); + ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind), ", expected JSDocFunctionType"); }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -46033,8 +46765,6 @@ var ts; // - `BindingElement: BindingPattern Initializer?` // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization // - `BindingElement: BindingPattern Initializer?` - bindEach(node.decorators); - bindEach(node.modifiers); bind(node.dotDotDotToken); bind(node.propertyName); bind(node.initializer); @@ -46375,37 +47105,6 @@ var ts; typeLiteralSymbol.members.set(symbol.escapedName, symbol); } function bindObjectLiteralExpression(node) { - var ElementKind; - (function (ElementKind) { - ElementKind[ElementKind["Property"] = 1] = "Property"; - ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; - })(ElementKind || (ElementKind = {})); - if (inStrictMode && !ts.isAssignmentTarget(node)) { - var seen = new ts.Map(); - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 298 /* SyntaxKind.SpreadAssignment */ || prop.name.kind !== 79 /* SyntaxKind.Identifier */) { - continue; - } - var identifier = prop.name; - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 296 /* SyntaxKind.PropertyAssignment */ || prop.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || prop.kind === 169 /* SyntaxKind.MethodDeclaration */ - ? 1 /* ElementKind.Property */ - : 2 /* ElementKind.Accessor */; - var existingKind = seen.get(identifier.escapedText); - if (!existingKind) { - seen.set(identifier.escapedText, currentKind); - continue; - } - } - } return bindAnonymousDeclaration(node, 4096 /* SymbolFlags.ObjectLiteral */, "__object" /* InternalSymbolName.Object */); } function bindJsxAttributes(node) { @@ -47062,7 +47761,7 @@ var ts; } } function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { + if (ts.some(node.modifiers)) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level @@ -47099,12 +47798,14 @@ var ts; } } function setCommonJsModuleIndicator(node) { - if (file.externalModuleIndicator) { + if (file.externalModuleIndicator && file.externalModuleIndicator !== true) { return false; } if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } return true; } @@ -47518,7 +48219,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) && !ts.getJSDocTypeTag(node) && !(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */)) { + var possibleVariableDecl = node.kind === 254 /* SyntaxKind.VariableDeclaration */ ? node : node.parent.parent; + if (ts.isInJSFile(node) && + ts.isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && + !ts.getJSDocTypeTag(node) && + !(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* SymbolFlags.Alias */, 2097152 /* SymbolFlags.AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -47708,10 +48413,11 @@ var ts; } function isExportsOrModuleExportsOrAlias(sourceFile, node) { var i = 0; - var q = [node]; - while (q.length && i < 100) { + var q = ts.createQueue(); + q.enqueue(node); + while (!q.isEmpty() && i < 100) { i++; - node = q.shift(); + node = q.dequeue(); if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) { return true; } @@ -47719,10 +48425,10 @@ var ts; var symbol = lookupSymbolForName(sourceFile, node.escapedText); if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) { var init = symbol.valueDeclaration.initializer; - q.push(init); + q.enqueue(init); if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) { - q.push(init.left); - q.push(init.right); + q.enqueue(init.left); + q.enqueue(init.right); } } } @@ -47982,7 +48688,10 @@ var ts; TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; - TypeFacts[TypeFacts["All"] = 16777215] = "All"; + TypeFacts[TypeFacts["IsUndefined"] = 16777216] = "IsUndefined"; + TypeFacts[TypeFacts["IsNull"] = 33554432] = "IsNull"; + TypeFacts[TypeFacts["IsUndefinedOrNull"] = 50331648] = "IsUndefinedOrNull"; + TypeFacts[TypeFacts["All"] = 134217727] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. @@ -48024,25 +48733,17 @@ var ts; TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; - TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["VoidFacts"] = 9830144] = "VoidFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 26607360] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 42917664] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 83427327] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 83886079] = "EmptyObjectFacts"; + TypeFacts[TypeFacts["UnknownFacts"] = 83886079] = "UnknownFacts"; TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE"; - TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; // Masks TypeFacts[TypeFacts["OrFactsMask"] = 8256] = "OrFactsMask"; - TypeFacts[TypeFacts["AndFactsMask"] = 16768959] = "AndFactsMask"; - })(TypeFacts || (TypeFacts = {})); - var typeofEQFacts = new ts.Map(ts.getEntries({ - string: 1 /* TypeFacts.TypeofEQString */, - number: 2 /* TypeFacts.TypeofEQNumber */, - bigint: 4 /* TypeFacts.TypeofEQBigInt */, - boolean: 8 /* TypeFacts.TypeofEQBoolean */, - symbol: 16 /* TypeFacts.TypeofEQSymbol */, - undefined: 65536 /* TypeFacts.EQUndefined */, - object: 32 /* TypeFacts.TypeofEQObject */, - function: 64 /* TypeFacts.TypeofEQFunction */ - })); + TypeFacts[TypeFacts["AndFactsMask"] = 134209471] = "AndFactsMask"; + })(TypeFacts = ts.TypeFacts || (ts.TypeFacts = {})); var typeofNEFacts = new ts.Map(ts.getEntries({ string: 256 /* TypeFacts.TypeofNEString */, number: 512 /* TypeFacts.TypeofNENumber */, @@ -48077,7 +48778,7 @@ var ts; CheckMode[CheckMode["RestBindingElement"] = 64] = "RestBindingElement"; // e.g. in `const { a, ...rest } = foo`, when checking the type of `foo` to determine the type of `rest`, // we need to preserve generic types instead of substituting them for constraints - })(CheckMode || (CheckMode = {})); + })(CheckMode = ts.CheckMode || (ts.CheckMode = {})); var SignatureCheckMode; (function (SignatureCheckMode) { SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback"; @@ -48085,7 +48786,7 @@ var ts; SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes"; SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity"; SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback"; - })(SignatureCheckMode || (SignatureCheckMode = {})); + })(SignatureCheckMode = ts.SignatureCheckMode || (ts.SignatureCheckMode = {})); var IntersectionState; (function (IntersectionState) { IntersectionState[IntersectionState["None"] = 0] = "None"; @@ -48419,7 +49120,7 @@ var ts; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); - return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + return node ? getContextualTypeForObjectLiteralElement(node, /*contextFlags*/ undefined) : undefined; }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -48427,7 +49128,7 @@ var ts; }, getContextualTypeForJsxAttribute: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); - return node && getContextualTypeForJsxAttribute(node); + return node && getContextualTypeForJsxAttribute(node, /*contextFlags*/ undefined); }, isContextSensitive: isContextSensitive, getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, @@ -48541,9 +49242,9 @@ var ts; return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, - tryGetThisTypeAt: function (nodeIn, includeGlobalThis) { + tryGetThisTypeAt: function (nodeIn, includeGlobalThis, container) { var node = ts.getParseTreeNode(nodeIn); - return node && tryGetThisTypeAt(node, includeGlobalThis); + return node && tryGetThisTypeAt(node, includeGlobalThis, container); }, getTypeArgumentConstraint: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); @@ -48633,6 +49334,7 @@ var ts; var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); var subtypeReductionCache = new ts.Map(); + var cachedTypes = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var markerTypes = new ts.Set(); @@ -48641,11 +49343,10 @@ var ts; var unresolvedSymbols = new ts.Map(); var errorTypes = new ts.Map(); var anyType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); - var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); + var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 262144 /* ObjectFlags.NonInferrableType */); var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error"); var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved"); - var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); @@ -48674,8 +49375,7 @@ var ts; var esSymbolType = createIntrinsicType(4096 /* TypeFlags.ESSymbol */, "symbol"); var voidType = createIntrinsicType(16384 /* TypeFlags.Void */, "void"); var neverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); + var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* TypeFlags.NonPrimitive */, "object"); @@ -48685,16 +49385,30 @@ var ts; var numberOrBigIntType = getUnionType([numberType, bigintType]); var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]); var numericStringType = getTemplateLiteralType(["", ""], [numberType]); // The `${number}` type - var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }); - var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }); + var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }, function () { return "(restrictive mapper)"; }); + var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }, function () { return "(permissive mapper)"; }); var uniqueLiteralType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); // `uniqueLiteralType` is a special `never` flagged by union reduction to behave as a literal - var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }); // replace all type parameters with the unique literal type (disregarding constraints) + var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }, function () { return "(unique literal mapper)"; }); // replace all type parameters with the unique literal type (disregarding constraints) + var outofbandVarianceMarkerHandler; + var reportUnreliableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); + } + return t; + }, function () { return "(unmeasurable reporter)"; }); + var reportUnmeasurableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); + } + return t; + }, function () { return "(unreliable reporter)"; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyJsxObjectType.objectFlags |= 2048 /* ObjectFlags.JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* SymbolFlags.TypeLiteral */, "__type" /* InternalSymbolName.Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray)]) : unknownType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyGenericType.instantiations = new ts.Map(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); @@ -48708,6 +49422,9 @@ var ts; var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); + var markerSuperTypeForCheck = createTypeParameter(); + var markerSubTypeForCheck = createTypeParameter(); + markerSubTypeForCheck.constraint = markerSuperTypeForCheck; var noTypePredicate = createTypePredicate(1 /* TypePredicateKind.Identifier */, "<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); @@ -48837,21 +49554,13 @@ var ts; var potentialNewTargetCollisions = []; var potentialWeakMapSetCollisions = []; var potentialReflectCollisions = []; + var potentialUnusedRenamedBindingElementsInTypes = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); - var typeofTypesByName = new ts.Map(ts.getEntries({ - string: stringType, - number: numberType, - bigint: bigintType, - boolean: booleanType, - symbol: esSymbolType, - undefined: undefinedType - })); var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var outofbandVarianceMarkerHandler; var subtypeRelation = new ts.Map(); var strictSubtypeRelation = new ts.Map(); var assignableRelation = new ts.Map(); @@ -48877,6 +49586,14 @@ var ts; ]; initializeTypeChecker(); return checker; + function getCachedType(key) { + return key ? cachedTypes.get(key) : undefined; + } + function setCachedType(key, type) { + if (key) + cachedTypes.set(key, type); + return type; + } function getJsxNamespace(location) { if (location) { var file = ts.getSourceFileOfNode(location); @@ -49741,6 +50458,7 @@ var ts; if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 111551 /* SymbolFlags.Value */)) { // Remember the property node, it will be used later to report appropriate error + ts.Debug.assertNode(location, ts.isPropertyDeclaration); propertyWithInvalidInitializer = location; } } @@ -49930,11 +50648,27 @@ var ts; } } } + // The invalid initializer error is needed in two situation: + // 1. When result is undefined, after checking for a missing "this." + // 2. When result is defined + function checkAndReportErrorForInvalidInitializer() { + if (propertyWithInvalidInitializer && !(useDefineForClassFields && ts.getEmitScriptTarget(compilerOptions) >= 9 /* ScriptTarget.ES2022 */)) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed + // with ESNext+useDefineForClassFields because the scope semantics are different. + error(errorLocation, errorLocation && propertyWithInvalidInitializer.type && ts.textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) + ? ts.Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor + : ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg)); + return true; + } + return false; + } if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(function () { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForInvalidInitializer() && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && @@ -49942,7 +50676,16 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { + var suggestedLib = void 0; + // Report missing lib first + if (nameArg) { + suggestedLib = getSuggestedLibForNonExistentName(nameArg); + if (suggestedLib) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib); + } + } + // then spelling suggestions + if (!suggestedLib && getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -49961,16 +50704,9 @@ var ts; } } } - if (!suggestion) { - if (nameArg) { - var lib = getSuggestedLibForNonExistentName(nameArg); - if (lib) { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib); - } - else { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); - } - } + // And then fall back to unspecified "not found" + if (!suggestion && !suggestedLib && nameArg) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); } suggestionCount++; } @@ -49978,12 +50714,7 @@ var ts; } return undefined; } - if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ScriptTarget.ESNext */ && useDefineForClassFields)) { - // We have a match, but the reference occurred within a property initializer and the identifier also binds - // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed - // with ESNext+useDefineForClassFields because the scope semantics are different. - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + else if (checkAndReportErrorForInvalidInitializer()) { return undefined; } // Perform extra checks only if error reporting was requested @@ -50085,7 +50816,7 @@ var ts; if (decl.kind === 163 /* SyntaxKind.TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); } } } @@ -50194,7 +50925,12 @@ var ts; function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { if (isPrimitiveTypeName(name)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(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)); + } + else { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + } return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); @@ -50214,6 +50950,16 @@ var ts; } return false; } + function isExtendedByInterface(node) { + var grandparent = node.parent.parent; + var parentOfGrandparent = grandparent.parent; + if (grandparent && parentOfGrandparent) { + var isExtending = ts.isHeritageClause(grandparent) && grandparent.token === 94 /* SyntaxKind.ExtendsKeyword */; + var isInterface = ts.isInterfaceDeclaration(parentOfGrandparent); + return isExtending && isInterface; + } + return false; + } function maybeMappedType(node, symbol) { var container = ts.findAncestor(node.parent, function (n) { return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit"; @@ -50345,7 +51091,8 @@ var ts; && isAliasableOrJsExpression(node.parent.right) || node.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || node.kind === 296 /* SyntaxKind.PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node); + || node.kind === 254 /* SyntaxKind.VariableDeclaration */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) + || node.kind === 203 /* SyntaxKind.BindingElement */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -50438,7 +51185,7 @@ var ts; return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker - return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); + return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { var _a; @@ -50716,10 +51463,6 @@ var ts; checkExpressionCached(expression); return getNodeLinks(expression).resolvedSymbol; } - function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) { - var expression = node.initializer; - return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve); - } function getTargetOfAccessExpression(node, dontRecursivelyResolve) { if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */)) { return undefined; @@ -50751,7 +51494,7 @@ var ts; case 297 /* SyntaxKind.ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); case 296 /* SyntaxKind.PropertyAssignment */: - return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); + return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); case 207 /* SyntaxKind.ElementAccessExpression */: case 206 /* SyntaxKind.PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); @@ -51156,7 +51899,40 @@ var ts; // An override clause will take effect for type-only imports and import types, and allows importing the types across formats, regardless of // normal mode restrictions if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext && !ts.getResolutionModeOverrideForClause(overrideClause)) { - error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); + if (ts.findAncestor(location, ts.isImportEqualsDeclaration)) { + // ImportEquals in a ESM file resolving to another ESM file + error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); + } + else { + // CJS file resolving to an ESM file + var diagnosticDetails = void 0; + var ext = ts.tryGetExtensionFromPath(currentSourceFile.fileName); + if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) { + var scope = currentSourceFile.packageJsonScope; + var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined; + if (scope && !scope.packageJsonContent.type) { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json")); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, ts.combinePaths(scope.packageDirectory, "package.json")); + } + } + else { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, targetExt); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module); + } + } + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(diagnosticDetails, ts.Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, moduleReference))); + } } } // merged symbol is module declaration symbol combined with all augmentations @@ -51665,8 +52441,9 @@ var ts; function getExportSymbolOfValueSymbolIfExported(symbol) { return getMergedSymbol(symbol && (symbol.flags & 1048576 /* SymbolFlags.ExportValue */) !== 0 && symbol.exportSymbol || symbol); } - function symbolIsValue(symbol) { - return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && !getTypeOnlyAliasDeclaration(symbol)); + function symbolIsValue(symbol, includeTypeOnlyMembers) { + return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || + symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -51706,7 +52483,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getStringLiteralType)); + return getUnionType(ts.arrayFrom(typeofNEFacts.keys(), getStringLiteralType)); } function createTypeParameter(symbol) { var type = createType(262144 /* TypeFlags.TypeParameter */); @@ -52115,13 +52892,25 @@ var ts; && isDeclarationVisible(declaration.parent)) { return addVisibleAlias(declaration, declaration); } - else if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isBindingElement(declaration) && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement - && ts.isVariableDeclaration(declaration.parent.parent) - && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) - && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) - && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) - && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { - return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + else if (ts.isBindingElement(declaration)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement + && ts.isVariableDeclaration(declaration.parent.parent) + && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) + && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) + && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) + && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + } + else if (symbol.flags & 2 /* SymbolFlags.BlockScopedVariable */) { + var variableStatement = ts.findAncestor(declaration, ts.isVariableStatement); + if (ts.hasSyntacticModifier(variableStatement, 1 /* ModifierFlags.Export */)) { + return true; + } + if (!isDeclarationVisible(variableStatement.parent)) { + return false; + } + return addVisibleAlias(declaration, variableStatement); + } } // Declaration is not visible return false; @@ -52163,6 +52952,9 @@ var ts; if (symbol && symbol.flags & 262144 /* SymbolFlags.TypeParameter */ && meaning & 788968 /* SymbolFlags.Type */) { return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; } + if (!symbol && ts.isThisIdentifier(firstIdentifier) && isSymbolAccessible(getSymbolOfNode(ts.getThisContainer(firstIdentifier, /*includeArrowFunctions*/ false)), firstIdentifier, meaning, /*computeAliases*/ false).accessibility === 0 /* SymbolAccessibility.Accessible */) { + return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; + } // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* SymbolAccessibility.NotAccessible */, @@ -52251,7 +53043,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* TypeFormatFlags.None */; } - return flags & 814775659 /* TypeFormatFlags.NodeBuilderFlagsMask */; + return flags & 848330091 /* TypeFormatFlags.NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { return !!type.symbol && !!(type.symbol.flags & 32 /* SymbolFlags.Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* TypeFlags.Object */) && !!(ts.getObjectFlags(type) & 16777216 /* ObjectFlags.IsClassInstanceClone */))); @@ -52353,6 +53145,12 @@ var ts; return context.truncating = context.approximateLength > ((context.flags & 1 /* NodeBuilderFlags.NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { + var savedFlags = context.flags; + var typeNode = typeToTypeNodeWorker(type, context); + context.flags = savedFlags; + return typeNode; + } + function typeToTypeNodeWorker(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); } @@ -52492,6 +53290,9 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* SymbolFlags.Class */)) return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes); + if (ts.length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) { + return ts.factory.createArrayTypeNode(typeArgumentNodes[0]); + } return symbolToTypeNode(type.aliasSymbol, context, 788968 /* SymbolFlags.Type */, typeArgumentNodes); } var objectFlags = ts.getObjectFlags(type); @@ -52528,8 +53329,8 @@ var ts; if (type.symbol) { return symbolToTypeNode(type.symbol, context, 788968 /* SymbolFlags.Type */); } - var name = (type === markerSuperType || type === markerSubType) && varianceTypeParameter && varianceTypeParameter.symbol ? - (type === markerSubType ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; + var name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? + (type === markerSubTypeForCheck ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name), /*typeArguments*/ undefined); } if (type.flags & 1048576 /* TypeFlags.Union */ && type.origin) { @@ -52595,7 +53396,7 @@ var ts; var name = typeParameterToName(newParam, context); var newTypeVariable = ts.factory.createTypeReferenceNode(name); context.approximateLength += 37; // 15 each for two added conditionals, 7 for an added infer type - var newMapper = prependTypeMapping(type.root.checkType, newParam, type.combinedMapper || type.mapper); + var newMapper = prependTypeMapping(type.root.checkType, newParam, type.mapper); var saveInferTypeParameters_1 = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode_1 = typeToTypeNodeHelper(instantiateType(type.root.extendsType, newMapper), context); @@ -52636,6 +53437,10 @@ var ts; } return typeToTypeNodeHelper(type, context); } + function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) { + return isMappedTypeWithKeyofConstraintDeclaration(type) + && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */); + } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 524288 /* TypeFlags.Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -52645,7 +53450,7 @@ var ts; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` - if (!(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { var newParam = createTypeParameter(createSymbol(262144 /* SymbolFlags.TypeParameter */, "T")); var name = typeParameterToName(newParam, context); newTypeVariable = ts.factory.createTypeReferenceNode(name); @@ -52661,11 +53466,12 @@ var ts; var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; var result = ts.setEmitFlags(mappedTypeNode, 1 /* EmitFlags.SingleLine */); - if (isMappedTypeWithKeyofConstraintDeclaration(type) && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { // homomorphic mapped type with a non-homomorphic naive inlining // wrap it with a conditional like `SomeModifiersType extends infer U ? {..the mapped type...} : never` to ensure the resulting // type stays homomorphic - return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); + var originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type.declaration.typeParameter.constraint.type)) || unknownType, type.mapper); + return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* TypeFlags.Unknown */ ? undefined : typeToTypeNodeHelper(originalConstraint, context))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); } return result; } @@ -52682,7 +53488,7 @@ var ts; // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* SymbolFlags.Class */ && !getBaseTypeVariableOfClass(symbol) - && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 226 /* SyntaxKind.ClassExpression */ && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */) || + && !(symbol.valueDeclaration && ts.isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */ && (!ts.isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*computeAliases*/ false).accessibility !== 0 /* SymbolAccessibility.Accessible */)) || symbol.flags & (384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -52948,7 +53754,7 @@ var ts; var id = ids_1[_i]; qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id; } - return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf); + return ts.factory.updateImportTypeNode(root, root.argument, root.assertions, qualifier, typeArguments, root.isTypeOf); } else { // first shift type arguments @@ -53052,7 +53858,7 @@ var ts; anyType : getNonMissingTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* CheckFlags.Late */ && isLateBoundName(propertySymbol.escapedName)) { + if (context.tracker.trackSymbol && isLateBoundName(propertySymbol.escapedName)) { if (propertySymbol.declarations) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { @@ -53197,7 +54003,6 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, @@ -53209,8 +54014,7 @@ var ts; context.encounteredError = true; } context.approximateLength += (name.length + 4); - return ts.factory.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + return ts.factory.createIndexSignature(indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { var _a, _b, _c, _d; @@ -53229,7 +54033,7 @@ var ts; var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* CheckFlags.RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 171 /* SyntaxKind.Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); - var thisParameter = tryGetThisParameterDeclaration(signature, context); + var thisParameter = context.flags & 33554432 /* NodeBuilderFlags.OmitThisParameter */ ? undefined : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { parameters.unshift(thisParameter); } @@ -53262,15 +54066,15 @@ var ts; var node = kind === 174 /* SyntaxKind.CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 175 /* SyntaxKind.ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 168 /* SyntaxKind.MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(modifiers, parameters, /*body*/ undefined) : + kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 317 /* SyntaxKind.JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 179 /* SyntaxKind.FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : kind === 180 /* SyntaxKind.ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : kind === 213 /* SyntaxKind.FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : kind === 214 /* SyntaxKind.ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); @@ -53287,7 +54091,6 @@ var ts; var thisTag = ts.getJSDocThisTag(signature.declaration); if (thisTag && thisTag.typeExpression) { return ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); @@ -53319,7 +54122,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); - var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined; + var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && ts.canHaveModifiers(parameterDeclaration) ? ts.map(ts.getModifiers(parameterDeclaration), ts.factory.cloneNode) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* CheckFlags.RestParameter */; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -53330,21 +54133,27 @@ var ts; ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* CheckFlags.OptionalParameter */; var questionToken = isOptional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined; - var parameterNode = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + var parameterNode = ts.factory.createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { - return elideInitializerAndSetEmitFlags(node); - function elideInitializerAndSetEmitFlags(node) { + return elideInitializerAndPropertyRenamingAndSetEmitFlags(node); + function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) { if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { trackComputedName(node.expression, context.enclosingDeclaration, context); } - var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags); if (ts.isBindingElement(visited)) { - visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, - /*initializer*/ undefined); + if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, + /* propertyName*/ undefined, visited.propertyName, + /*initializer*/ undefined); + } + else { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, + /*initializer*/ undefined); + } } if (!ts.nodeIsSynthesized(visited)) { visited = ts.factory.cloneNode(visited); @@ -53553,6 +54362,7 @@ var ts; return symbol.parent ? ts.factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var _a, _b, _c, _d; var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module var isTypeOf = meaning === 111551 /* SymbolFlags.Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { @@ -53570,6 +54380,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral("import")) ]))); + (_b = (_a = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _b === void 0 ? void 0 : _b.call(_a); } } if (!specifier) { @@ -53589,6 +54400,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral(swappedMode === ts.ModuleKind.ESNext ? "import" : "require")) ]))); + (_d = (_c = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _d === void 0 ? void 0 : _d.call(_c); } } if (!assertion) { @@ -53990,9 +54802,7 @@ var ts; } if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdotToken*/ undefined, "x", /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); @@ -54000,14 +54810,13 @@ var ts; if (ts.isJSDocFunctionType(node)) { if (ts.isJSDocConstructSignature(node)) { var newTypeNode_1; - return ts.factory.createConstructorTypeNode(node.modifiers, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createConstructorTypeNode( + /*modifiers*/ undefined, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } else { return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } @@ -54026,7 +54835,7 @@ var ts; !(ts.length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) { return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); } - return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.assertions, node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { var _a = trackExistingEntityName(node, context, includePrivateSymbol), introducesError = _a.introducesError, result = _a.node; @@ -54078,7 +54887,7 @@ var ts; } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 169 /* SyntaxKind.MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -54139,8 +54948,7 @@ var ts; var name_3 = ns.name; var body = ns.body; if (ts.length(excessExports)) { - ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, + ns = ts.factory.updateModuleDeclaration(ns, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, /*alias*/ undefined, id); })), /*moduleSpecifier*/ undefined)], false)))); @@ -54166,7 +54974,6 @@ var ts; if (ts.length(exports) > 1) { var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; }); statements = __spreadArray(__spreadArray([], nonExports, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), /*moduleSpecifier*/ undefined)], false); @@ -54181,7 +54988,6 @@ var ts; // remove group members from statements and then merge group members and add back to statements statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), true), [ ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier) ], false); @@ -54221,7 +55027,7 @@ var ts; } else { // some items filtered, others not - update the export declaration - statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); + statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); } } return statements; @@ -54286,12 +55092,11 @@ var ts; if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) { var oldContext = context; context = cloneNodeBuilderContext(context); - var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); + serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); if (context.reportedDiagnostic) { oldcontext.reportedDiagnostic = context.reportedDiagnostic; // hoist diagnostic result into outer context } context = oldContext; - return result; } } // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias @@ -54372,7 +55177,6 @@ var ts; && ((_d = type.symbol) === null || _d === void 0 ? void 0 : _d.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, alias, localName)])), 0 /* ModifierFlags.None */); context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* SymbolFlags.Value */); @@ -54405,7 +55209,6 @@ var ts; // ``` // To create an export named `g` that does _not_ shadow the local `g` addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name, localName)])), 0 /* ModifierFlags.None */); needsExportDeclaration = false; @@ -54454,16 +55257,15 @@ var ts; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); if (!resolvedModule) continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); } } } if (needsPostExportDefault) { - addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportAssignment(/*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); } else if (needsExportDeclaration) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* ModifierFlags.None */); } @@ -54531,7 +55333,7 @@ var ts; && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); - addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); + addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; context.enclosingDeclaration = oldEnclosingDecl; } @@ -54547,7 +55349,6 @@ var ts; var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* SymbolFlags.Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), constructSignatures, true), callSignatures, true), members, true)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { @@ -54573,7 +55374,6 @@ var ts; var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* InternalSymbolName.ExportEquals */; }), function (s) { var _a, _b; @@ -54590,13 +55390,11 @@ var ts; return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name === targetName ? undefined : targetName, name); })))]); addResult(ts.factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* NodeFlags.Namespace */), 0 /* ModifierFlags.None */); } } function serializeEnum(symbol, symbolName, modifierFlags) { - addResult(ts.factory.createEnumDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { + addResult(ts.factory.createEnumDeclaration(ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { // TODO: Handle computed names // I hate that to get the initialized value we need to walk back to the declarations here; but there's no // other way to get the possible const value of an enum member that I'm aware of, as the value is cached @@ -54657,7 +55455,7 @@ var ts; // emit akin to the above would be needed. // Add a namespace // Create namespace as non-synthetic so it is usable as an enclosing declaration - var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace, enclosingDeclaration); fakespace.locals = ts.createSymbolTable(props); fakespace.symbol = props[0].parent; @@ -54676,11 +55474,10 @@ var ts; results = oldResults; // replace namespace with synthetic version var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, d.expression, ts.factory.createIdentifier("default" /* InternalSymbolName.Default */))])) : d; }); var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* ModifierFlags.Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced; - fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); + fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); addResult(fakespace, modifierFlags); // namespaces can never be default exported } } @@ -54736,7 +55533,7 @@ var ts; ? getBaseConstructorTypeOfClass(staticType) : anyType; var heritageClauses = __spreadArray(__spreadArray([], !ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], true), !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(117 /* SyntaxKind.ImplementsKeyword */, implementsExpressions)], true); - var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); + var symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties @@ -54754,7 +55551,6 @@ var ts; // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? [ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -54771,12 +55567,11 @@ var ts; ts.isInJSFile(symbol.valueDeclaration) && !ts.some(getSignaturesOfType(staticType, 1 /* SignatureKind.Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? - [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : + [ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : serializeSignatures(1 /* SignatureKind.Construct */, staticType, staticBaseType, 171 /* SyntaxKind.Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), staticMembers, true), constructors, true), publicProperties, true), privateProperties, true)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags); } function getSomeTargetNameFromDeclarations(declarations) { @@ -54828,7 +55623,6 @@ var ts; var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier( /*isTypeOnly*/ false, propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1), /*importClause*/ undefined), 0 /* ModifierFlags.None */); @@ -54852,12 +55646,10 @@ var ts; var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); // 'y' // import _x = require('y'); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* ModifierFlags.None */); // import x = _x.z addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); break; @@ -54874,7 +55666,6 @@ var ts; // an external `import localName = require("whatever")` var isLocalImport = !(target.flags & 512 /* SymbolFlags.ValueModule */) && !ts.isVariableDeclaration(node); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), isLocalImport ? symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false) @@ -54888,7 +55679,6 @@ var ts; break; case 267 /* SyntaxKind.ImportClause */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag @@ -54898,19 +55688,16 @@ var ts; break; case 268 /* SyntaxKind.NamespaceImport */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), /*assertClause*/ undefined), 0 /* ModifierFlags.None */); break; case 274 /* SyntaxKind.NamespaceExport */: addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* ModifierFlags.None */); break; case 270 /* SyntaxKind.ImportSpecifier */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamedImports([ @@ -54949,7 +55736,6 @@ var ts; } function serializeExportSpecifier(localName, targetName, specifier) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* ModifierFlags.None */); } @@ -54990,7 +55776,6 @@ var ts; context.tracker.trackSymbol = function () { return false; }; if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* SymbolFlags.All */))); } else { @@ -55005,7 +55790,6 @@ var ts; // serialize as `import _Ref = t.arg.et; export { _Ref as name }` var varName = getUnusedName(name, symbol); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false)), 0 /* ModifierFlags.None */); serializeExportSpecifier(name, varName); @@ -55036,7 +55820,6 @@ var ts; } if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName))); return true; } @@ -55086,9 +55869,7 @@ var ts; if (p.flags & 98304 /* SymbolFlags.Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SymbolFlags.SetAccessor */) { - result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], @@ -55096,8 +55877,7 @@ var ts; } if (p.flags & 32768 /* SymbolFlags.GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* ModifierFlags.Private */; - result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; @@ -55105,8 +55885,7 @@ var ts; // This is an else/if as accessors and properties can't merge in TS, but might in JS // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* SymbolFlags.Property */ | 3 /* SymbolFlags.Variable */ | 98304 /* SymbolFlags.Accessor */)) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); @@ -55115,8 +55894,7 @@ var ts; var type = getTypeOfSymbol(p); var signatures = getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (flag & 8 /* ModifierFlags.Private */) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, /*type*/ undefined, /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } @@ -55174,8 +55952,7 @@ var ts; } } if (privateProtected) { - return [ts.setTextRange(ts.factory.createConstructorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), + return [ts.setTextRange(ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(privateProtected), /*parameters*/ [], /*body*/ undefined), signatures[0].declaration)]; } @@ -55874,7 +56651,7 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 32768 /* TypeFlags.Undefined */) ? getNonUndefinedType(type) : type; + return strictNullChecks && !(getTypeFacts(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 16777216 /* TypeFacts.IsUndefined */) ? getNonUndefinedType(type) : type; } return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)], 2 /* UnionReduction.Subtype */)); } @@ -56275,7 +57052,7 @@ var ts; (resolvedSymbol || symbol).exports.forEach(function (s, name) { var _a; var exportedMember = members_4.get(name); - if (exportedMember && exportedMember !== s) { + if (exportedMember && exportedMember !== s && !(s.flags & 2097152 /* SymbolFlags.Alias */)) { if (s.flags & 111551 /* SymbolFlags.Value */ && exportedMember.flags & 111551 /* SymbolFlags.Value */) { // If the member has an additional value-like declaration, union the types from the two declarations, // but issue an error if they occurred in two different files. The purpose is to support a JS file with @@ -56309,6 +57086,17 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.indexInfos); + if (initialSize === members_4.size) { + if (type.aliasSymbol) { + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = type.aliasTypeArguments; + } + if (ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */) { + result.aliasSymbol = type.symbol; + var args = getTypeArguments(type); + result.aliasTypeArguments = ts.length(args) ? args : undefined; + } + } result.objectFlags |= (ts.getObjectFlags(type) & 4096 /* ObjectFlags.JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* SymbolFlags.Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { result.objectFlags |= 16777216 /* ObjectFlags.IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type @@ -56360,11 +57148,7 @@ var ts; if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAny(element, anyType); } - // When we're including the pattern in the type (an indication we're obtaining a contextual type), we - // use the non-inferrable any type. Inference will never directly infer this type, but it is possible - // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases, - // widening of the binding pattern type substitutes a regular any for the non-inferrable any. - return includePatternInType ? nonInferrableAnyType : anyType; + return anyType; } // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { @@ -57365,7 +58149,7 @@ var ts; error(declaration.typeExpression.type, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } else { - error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + error(ts.isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } } links.declaredType = type; @@ -58669,6 +59453,9 @@ var ts; else if (type.objectFlags & 32 /* ObjectFlags.Mapped */) { resolveMappedTypeMembers(type); } + else { + ts.Debug.fail("Unhandled object type " + ts.Debug.formatObjectFlags(type.objectFlags)); + } } else if (type.flags & 1048576 /* TypeFlags.Union */) { resolveUnionTypeMembers(type); @@ -58676,6 +59463,9 @@ var ts; else if (type.flags & 2097152 /* TypeFlags.Intersection */) { resolveIntersectionTypeMembers(type); } + else { + ts.Debug.fail("Unhandled type " + ts.Debug.formatTypeFlags(type.flags)); + } } return type; } @@ -58863,7 +59653,7 @@ var ts; } } } - else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { hasDisjointDomainType = true; } } @@ -58875,12 +59665,13 @@ var ts; // intersection operation to reduce the union constraints. for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { var t = types_6[_a]; - if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { constraints = ts.append(constraints, t); } } } - return getIntersectionType(constraints); + // The source types were normalized; ensure the result is normalized too. + return getNormalizedType(getIntersectionType(constraints), /*writing*/ false); } return undefined; } @@ -58991,7 +59782,7 @@ var ts; } if (t.flags & 268435456 /* TypeFlags.StringMapping */) { var constraint = getBaseConstraint(t.type); - return constraint ? getStringMappingType(t.symbol, constraint) : stringType; + return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType; } if (t.flags & 8388608 /* TypeFlags.IndexedAccess */) { if (isMappedTypeGenericIndexedAccess(t)) { @@ -59077,7 +59868,7 @@ var ts; var objectType; return !!(type.flags & 8388608 /* TypeFlags.IndexedAccess */ && ts.getObjectFlags(objectType = type.objectType) & 32 /* ObjectFlags.Mapped */ && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && - !objectType.declaration.questionToken && !objectType.declaration.nameType); + !(getMappedTypeModifiers(objectType) & 8 /* MappedTypeModifiers.ExcludeOptional */) && !objectType.declaration.nameType); } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, @@ -59356,12 +60147,12 @@ var ts; * @param type a type to look up property from * @param name a name of property to look up in a given type */ - function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment) { + function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) { type = getReducedApparentType(type); if (type.flags & 524288 /* TypeFlags.Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { + if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) { return symbol; } if (skipObjectFunctionPropertyAugment) @@ -59467,12 +60258,15 @@ var ts; // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(declaration) { + var _a; var result; - for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { - var node = _a[_i]; + for (var _i = 0, _b = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _b.length; _i++) { + var node = _b[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); } - return result; + return (result === null || result === void 0 ? void 0 : result.length) ? result + : ts.isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) === null || _a === void 0 ? void 0 : _a.typeParameters + : undefined; } function symbolsToArray(symbols) { var result = []; @@ -60023,8 +60817,7 @@ var ts; var _a; var inferences; if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { - for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; + var _loop_15 = function (declaration) { if (declaration.parent.kind === 190 /* SyntaxKind.InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the @@ -60032,12 +60825,12 @@ var ts; // present, we form an intersection of the inferred constraint types. var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; if (grandParent.kind === 178 /* SyntaxKind.TypeReference */ && !omitTypeReferences) { - var typeReference = grandParent; - var typeParameters = getTypeParametersForTypeReference(typeReference); - if (typeParameters) { - var index = typeReference.typeArguments.indexOf(childTypeParameter); - if (index < typeParameters.length) { - var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + var typeReference_1 = grandParent; + var typeParameters_1 = getTypeParametersForTypeReference(typeReference_1); + if (typeParameters_1) { + var index = typeReference_1.typeArguments.indexOf(childTypeParameter); + if (index < typeParameters_1.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters_1[index]); if (declaredConstraint) { // Type parameter constraints can reference other type parameters so // constraints need to be instantiated. If instantiation produces the @@ -60045,7 +60838,9 @@ var ts; // type Foo = [T, U]; // type Bar = T extends Foo ? Foo : T; // the instantiated constraint for U is X, so we discard that inference. - var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var mapper = makeDeferredTypeMapper(typeParameters_1, typeParameters_1.map(function (_, index) { return function () { + return getEffectiveTypeArgumentAtIndex(typeReference_1, typeParameters_1, index); + }; })); var constraint = instantiateType(declaredConstraint, mapper); if (constraint !== typeParameter) { inferences = ts.append(inferences, constraint); @@ -60083,6 +60878,10 @@ var ts; inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); } } + }; + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + _loop_15(declaration); } } return inferences && getIntersectionType(inferences); @@ -60145,13 +60944,13 @@ var ts; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type - // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // of an object literal or a non-inferrable type. This is because there are operations in the type checker // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type = types_8[_i]; - if (!(type.flags & excludeKinds)) { + if (excludeKinds === undefined || !(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } } @@ -60163,7 +60962,7 @@ var ts; if (!type) { type = createObjectType(4 /* ObjectFlags.Reference */, target.symbol); target.instantiations.set(id, type); - type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0; type.target = target; type.resolvedTypeArguments = typeArguments; } @@ -60971,7 +61770,7 @@ var ts; var lastRequiredIndex = -1; var firstRestIndex = -1; var lastOptionalOrRestIndex = -1; - var _loop_15 = function (i) { + var _loop_16 = function (i) { var type = elementTypes[i]; var flags = target.elementFlags[i]; if (flags & 8 /* ElementFlags.Variadic */) { @@ -61001,7 +61800,7 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - var state_4 = _loop_15(i); + var state_4 = _loop_16(i); if (typeof state_4 === "object") return state_4.value; } @@ -61197,7 +61996,7 @@ var ts; var templates = ts.filter(types, isPatternLiteralType); if (templates.length) { var i = types.length; - var _loop_16 = function () { + var _loop_17 = function () { i--; var t = types[i]; if (t.flags & 128 /* TypeFlags.StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { @@ -61205,7 +62004,7 @@ var ts; } }; while (i > 0) { - _loop_16(); + _loop_17(); } } } @@ -61282,14 +62081,14 @@ var ts; var namedUnions = []; addNamedUnions(namedUnions, types); var reducedTypes = []; - var _loop_17 = function (t) { + var _loop_18 = function (t) { if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) { reducedTypes.push(t); } }; for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) { var t = typeSet_1[_i]; - _loop_17(t); + _loop_18(t); } if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) { return namedUnions[0]; @@ -61424,7 +62223,7 @@ var ts; } return includes; } - function removeRedundantPrimitiveTypes(types, includes) { + function removeRedundantSupertypes(types, includes) { var i = types.length; while (i > 0) { i--; @@ -61432,7 +62231,9 @@ var ts; var remove = t.flags & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || t.flags & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || t.flags & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */; + t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + t.flags & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + isEmptyAnonymousObjectType(t) && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -61554,7 +62355,7 @@ var ts; // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types, aliasSymbol, aliasTypeArguments, noSupertypeReduction) { var typeMembershipMap = new ts.Map(); var includes = addTypesToIntersection(typeMembershipMap, 0, types); var typeSet = ts.arrayFrom(typeMembershipMap.values()); @@ -61591,11 +62392,11 @@ var ts; if (includes & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || includes & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || includes & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */) { - removeRedundantPrimitiveTypes(typeSet, includes); - } - if (includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 524288 /* TypeFlags.Object */) { - ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + includes & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */) { + if (!noSupertypeReduction) + removeRedundantSupertypes(typeSet, includes); } if (includes & 262144 /* TypeFlags.IncludesMissingType */) { typeSet[typeSet.indexOf(undefinedType)] = missingType; @@ -61634,8 +62435,9 @@ var ts; } var constituents = getCrossProductIntersections(typeSet); // We attach a denormalized origin type when at least one constituent of the cross-product union is an - // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions). - var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; + // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions) and + // the denormalized origin has fewer constituents than the union itself. + var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; result = getUnionType(constituents, 1 /* UnionReduction.Literal */, aliasSymbol, aliasTypeArguments, origin); } } @@ -61678,11 +62480,21 @@ var ts; } return intersections; } + function getConstituentCount(type) { + return !(type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) || type.aliasSymbol ? 1 : + type.flags & 1048576 /* TypeFlags.Union */ && type.origin ? getConstituentCount(type.origin) : + getConstituentCountOfTypes(type.types); + } + function getConstituentCountOfTypes(types) { + return ts.reduceLeft(types, function (n, t) { return n + getConstituentCount(t); }, 0); + } function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var aliasSymbol = getAliasSymbolForTypeNode(node); - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var types = ts.map(node.types, getTypeFromTypeNode); + var noSupertypeReduction = types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType; + links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); } return links.resolvedType; } @@ -61810,19 +62622,22 @@ var ts; * to reduce the resulting type if possible (since only intersections with conflicting literal-typed properties are reducible). */ function isPossiblyReducibleByInstantiation(type) { - return ts.some(type.types, function (t) { - var uniqueFilled = getUniqueLiteralFilledInstantiation(t); - return getReducedType(uniqueFilled) !== uniqueFilled; - }); + var uniqueFilled = getUniqueLiteralFilledInstantiation(type); + return getReducedType(uniqueFilled) !== uniqueFilled; + } + function shouldDeferIndexType(type) { + return !!(type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || + isGenericTupleType(type) || + isGenericMappedType(type) && !hasDistributiveNameType(type) || + type.flags & 1048576 /* TypeFlags.Union */ && ts.some(type.types, isPossiblyReducibleByInstantiation) || + type.flags & 2097152 /* TypeFlags.Intersection */ && maybeTypeOfKind(type, 465829888 /* TypeFlags.Instantiable */) && ts.some(type.types, isEmptyAnonymousObjectType)); } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } type = getReducedType(type); - return type.flags & 1048576 /* TypeFlags.Union */ ? isPossiblyReducibleByInstantiation(type) - ? getIndexTypeForGenericType(type, stringsOnly) - : getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + return shouldDeferIndexType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + type.flags & 1048576 /* TypeFlags.Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : + type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ ? getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) : type === wildcardType ? wildcardType : type.flags & 2 /* TypeFlags.Unknown */ ? neverType : @@ -61948,9 +62763,12 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type; + // 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; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -61961,6 +62779,15 @@ var ts; } return str; } + function applyTemplateStringMapping(symbol, texts, types) { + switch (intrinsicTypeKinds.get(symbol.escapedName)) { + case 0 /* IntrinsicTypeKind.Uppercase */: return [texts.map(function (t) { return t.toUpperCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 1 /* IntrinsicTypeKind.Lowercase */: return [texts.map(function (t) { return t.toLowerCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 2 /* IntrinsicTypeKind.Capitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toUpperCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + case 3 /* IntrinsicTypeKind.Uncapitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toLowerCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + } + return [texts, types]; + } function getStringMappingTypeForGenericType(symbol, type) { var id = "".concat(getSymbolId(symbol), ",").concat(getTypeId(type)); var result = stringMappingTypes.get(id); @@ -62062,21 +62889,28 @@ var ts; getFlowTypeOfReference(accessExpression, propType) : propType; } - if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName) && +propName >= 0) { + if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName)) { + var index = +propName; if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 16 /* AccessFlags.NoTupleBoundsCheck */)) { var indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { + if (index < 0) { + error(indexNode, ts.Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); + return undefinedType; + } error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); } else { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } } - errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, function (t) { - var restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; - }); + if (index >= 0) { + errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); + return mapType(objectType, function (t) { + var restType = getRestTypeOfTupleType(t) || undefinedType; + return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; + }); + } } } if (!(indexType.flags & 98304 /* TypeFlags.Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* TypeFlags.StringLike */ | 296 /* TypeFlags.NumberLike */ | 12288 /* TypeFlags.ESSymbolLike */)) { @@ -62202,7 +63036,7 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -62340,7 +63174,7 @@ var ts; function substituteIndexedMappedType(objectType, index) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]); var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return instantiateType(getTemplateTypeFromMappedType(objectType.target || objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) { if (accessFlags === void 0) { accessFlags = 0 /* AccessFlags.None */; } @@ -62488,7 +63322,7 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_18 = function () { + var _loop_19 = function () { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; @@ -62609,7 +63443,7 @@ var ts; // 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_5 = _loop_18(); + var state_5 = _loop_19(); if (typeof state_5 === "object") return state_5.value; if (state_5 === "break") @@ -62710,6 +63544,7 @@ var ts; } } function getTypeFromImportTypeNode(node) { + var _a; var links = getNodeLinks(node); if (!links.resolvedType) { if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments @@ -62729,6 +63564,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } + var isExportEquals = !!((_a = innerModuleSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* InternalSymbolName.ExportEquals */)); var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); @@ -62740,9 +63576,11 @@ var ts; // That, in turn, ultimately uses `getPropertyOfType` on the type of the symbol, which differs slightly from // the `exports` lookup process that only looks up namespace members which is used for most type references var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace)); - var next = node.isTypeOf - ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText) - : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var symbolFromVariable = node.isTypeOf || ts.isInJSFile(node) && isExportEquals + ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ true) + : undefined; + var symbolFromModule = node.isTypeOf ? undefined : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var next = symbolFromModule !== null && symbolFromModule !== void 0 ? symbolFromModule : symbolFromVariable; if (!next) { error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); return links.resolvedType = errorType; @@ -63239,7 +64077,7 @@ var ts; switch (mapper.kind) { case 0 /* TypeMapKind.Simple */: return type === mapper.source ? mapper.target : type; - case 1 /* TypeMapKind.Array */: + case 1 /* TypeMapKind.Array */: { var sources = mapper.sources; var targets = mapper.targets; for (var i = 0; i < sources.length; i++) { @@ -63248,25 +64086,39 @@ var ts; } } return type; - case 2 /* TypeMapKind.Function */: + } + case 2 /* TypeMapKind.Deferred */: { + var sources = mapper.sources; + var targets = mapper.targets; + for (var i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets[i](); + } + } + return type; + } + case 3 /* TypeMapKind.Function */: return mapper.func(type); - case 3 /* TypeMapKind.Composite */: - case 4 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: + case 5 /* TypeMapKind.Merged */: var t1 = getMappedType(type, mapper.mapper1); - return t1 !== type && mapper.kind === 3 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); + return t1 !== type && mapper.kind === 4 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); } } function makeUnaryTypeMapper(source, target) { - return { kind: 0 /* TypeMapKind.Simple */, source: source, target: target }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 0 /* TypeMapKind.Simple */, source: source, target: target }); } function makeArrayTypeMapper(sources, targets) { - return { kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }); } - function makeFunctionTypeMapper(func) { - return { kind: 2 /* TypeMapKind.Function */, func: func }; + function makeFunctionTypeMapper(func, debugInfo) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 3 /* TypeMapKind.Function */, func: func, debugInfo: ts.Debug.isDebugging ? debugInfo : undefined }); + } + function makeDeferredTypeMapper(sources, targets) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 2 /* TypeMapKind.Deferred */, sources: sources, targets: targets }); } function makeCompositeTypeMapper(kind, mapper1, mapper2) { - return { kind: kind, mapper1: mapper1, mapper2: mapper2 }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: kind, mapper1: mapper1, mapper2: mapper2 }); } function createTypeEraser(sources) { return createTypeMapper(sources, /*targets*/ undefined); @@ -63276,19 +64128,20 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(context, index) { - return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; }); + var forwardInferences = context.inferences.slice(index); + return createTypeMapper(ts.map(forwardInferences, function (i) { return i.typeParameter; }), ts.map(forwardInferences, function () { return unknownType; })); } function combineTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(3 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; } function mergeTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; } function prependTypeMapping(source, target, mapper) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); } function appendTypeMapping(mapper, source, target) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); } function getRestrictiveTypeParameter(tp) { return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), @@ -63554,6 +64407,7 @@ var ts; result.mapper = mapper; result.aliasSymbol = aliasSymbol || type.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + result.objectFlags |= result.aliasTypeArguments ? getPropagatingFlagsOfTypes(result.aliasTypeArguments) : 0; return result; } function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { @@ -64202,7 +65056,7 @@ var ts; }); } function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; if (isTupleLikeType(source)) { return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); @@ -64269,7 +65123,7 @@ var ts; }); } function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); } @@ -64356,7 +65210,7 @@ var ts; var sourceSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && - (getFalsyFlags(sourceType) & 98304 /* TypeFlags.Nullable */) === (getFalsyFlags(targetType) & 98304 /* TypeFlags.Nullable */); + (getTypeFacts(sourceType) & 50331648 /* TypeFacts.IsUndefinedOrNull */) === (getTypeFacts(targetType) & 50331648 /* TypeFacts.IsUndefinedOrNull */); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* SignatureCheckMode.StrictArity */) | (strictVariance ? 2 /* SignatureCheckMode.StrictCallback */ : 1 /* SignatureCheckMode.BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* SignatureCheckMode.Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); @@ -64468,6 +65322,20 @@ var ts; return !!(ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && (type.members && isEmptyResolvedType(type) || type.symbol && type.symbol.flags & 2048 /* SymbolFlags.TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0)); } + function isUnknownLikeUnionType(type) { + if (strictNullChecks && type.flags & 1048576 /* TypeFlags.Union */) { + if (!(type.objectFlags & 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */)) { + var types = type.types; + type.objectFlags |= 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */ | (types.length >= 3 && types[0].flags & 32768 /* TypeFlags.Undefined */ && + types[1].flags & 65536 /* TypeFlags.Null */ && ts.some(types, isEmptyAnonymousObjectType) ? 67108864 /* ObjectFlags.IsUnknownLikeUnion */ : 0); + } + return !!(type.objectFlags & 67108864 /* ObjectFlags.IsUnknownLikeUnion */); + } + return false; + } + function containsUndefinedType(type) { + return !!((type.flags & 1048576 /* TypeFlags.Union */ ? type.types[0] : type).flags & 32768 /* TypeFlags.Undefined */); + } function isStringIndexSignatureOnlyType(type) { return type.flags & 524288 /* TypeFlags.Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) || @@ -64547,7 +65415,7 @@ var ts; return true; if (s & 65536 /* TypeFlags.Null */ && (!strictNullChecks && !(t & 3145728 /* TypeFlags.UnionOrIntersection */) || t & 65536 /* TypeFlags.Null */)) return true; - if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */) + if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(ts.getObjectFlags(source) & 8192 /* ObjectFlags.FreshLiteral */))) return true; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* TypeFlags.Any */) @@ -64557,6 +65425,9 @@ var ts; // bit-flag enum types sometimes look like literal enum types with numeric literal values. if (s & (8 /* TypeFlags.Number */ | 256 /* TypeFlags.NumberLiteral */) && !(s & 1024 /* TypeFlags.EnumLiteral */) && (t & 32 /* TypeFlags.Enum */ || relation === assignableRelation && t & 256 /* TypeFlags.NumberLiteral */ && t & 1024 /* TypeFlags.EnumLiteral */)) return true; + // Anything is assignable to a union containing undefined, null, and {} + if (isUnknownLikeUnionType(target)) + return true; } return false; } @@ -64599,16 +65470,27 @@ var ts; function getNormalizedType(type, writing) { while (true) { var t = isFreshLiteralType(type) ? type.regularType : - ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getReducedType(type) : + ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : + type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* TypeFlags.Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* TypeFlags.Simplifiable */ ? getSimplifiedType(type, writing) : type; - t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) - break; + return t; type = t; } + } + function getNormalizedUnionOrIntersectionType(type, writing) { + var reduced = getReducedType(type); + if (reduced !== type) { + return reduced; + } + if (type.flags & 2097152 /* TypeFlags.Intersection */) { + var normalizedTypes = ts.sameMap(type.types, function (t) { return getNormalizedType(t, writing); }); + if (normalizedTypes !== type.types) { + return getIntersectionType(normalizedTypes); + } + } return type; } /** @@ -64840,7 +65722,7 @@ var ts; ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable"); generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); } - if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperType && target !== markerSubType) { + if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperTypeForCheck && target !== markerSubTypeForCheck) { var constraint = getBaseConstraintOfType(target); var needsOriginalSource = void 0; if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) { @@ -65055,6 +65937,7 @@ var ts; return 0 /* Ternary.False */; } function reportErrorResults(originalSource, originalTarget, source, target, headMessage) { + var _a, _b; var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; @@ -65095,6 +65978,14 @@ var ts; return; } reportRelationError(headMessage, source, target); + if (source.flags & 262144 /* TypeFlags.TypeParameter */ && ((_b = (_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) === null || _b === void 0 ? void 0 : _b[0]) && !getConstraintOfType(source)) { + var syntheticParam = cloneTypeParameter(source); + syntheticParam.constraint = instantiateType(target, makeUnaryTypeMapper(source, syntheticParam)); + if (hasNonCircularBaseConstraint(syntheticParam)) { + var targetConstraintString = typeToString(target, source.symbol.declarations[0]); + associateRelatedInfo(ts.createDiagnosticForNode(source.symbol.declarations[0], ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint, targetConstraintString)); + } + } } function traceUnionsOrIntersectionsTooLarge(source, target) { if (!ts.tracing) { @@ -65147,7 +66038,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_19 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -65210,7 +66101,7 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_6 = _loop_19(prop); + var state_6 = _loop_20(prop); if (typeof state_6 === "object") return state_6.value; } @@ -65232,7 +66123,7 @@ var ts; return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* TypeFlags.Primitive */) && !(target.flags & 131068 /* TypeFlags.Primitive */)); } if (target.flags & 2097152 /* TypeFlags.Intersection */) { - return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* IntersectionState.Target */); + return typeRelatedToEachType(source, target, reportErrors, 2 /* IntersectionState.Target */); } // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the // constraints of all non-primitive types in the source into a new intersection. We do this because the @@ -65442,10 +66333,10 @@ var ts; // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component var saved = entry & 24 /* RelationComparisonResult.ReportsMask */; if (saved & 8 /* RelationComparisonResult.ReportsUnmeasurable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers)); + instantiateType(source, reportUnmeasurableMapper); } if (saved & 16 /* RelationComparisonResult.ReportsUnreliable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } } return entry & 1 /* RelationComparisonResult.Succeeded */ ? -1 /* Ternary.True */ : 0 /* Ternary.False */; @@ -65545,13 +66436,40 @@ var ts; return result; } 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 */)) { + // 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 + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + // This also handles type parameters, as a type parameter with a union constraint compared against a union + // 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 && 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) { + resetErrorInfo(saveErrorInfo); + } + 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; - var saveErrorInfo = captureErrorCalculationState(); var sourceFlags = source.flags; var targetFlags = target.flags; if (relation === identityRelation) { @@ -65597,29 +66515,6 @@ var ts; if (result = unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState)) { return result; } - if (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */) { - // 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 - // when the target is a union type. Another is when the intersection contains types belonging - // to one of the disjoint domains. For example, given type variables T and U, each with the - // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and - // we need to check this constraint against a union on the target side. Also, given a type - // variable V constrained to 'string | number', 'V & number' has a combined constraint of - // 'string & number | number & number' which reduces to just 'number'. - // This also handles type parameters, as a type parameter with a union constraint compared against a union - // 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 && 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 - if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - } // The ordered decomposition above doesn't handle all cases. Specifically, we also need to handle: // Source is instantiable (e.g. source has union or intersection constraint). // Source is an object, target is a union (e.g. { a, b: boolean } <=> { a, b: true } | { a, b: false }). @@ -65663,6 +66558,20 @@ var ts; } } } + if (relation === comparableRelation && sourceFlags & 262144 /* TypeFlags.TypeParameter */) { + // This is a carve-out in comparability to essentially forbid comparing a type parameter + // 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 */) { + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { + return result; + } + constraint = getConstraintOfTypeParameter(constraint); + } + } + return 0 /* Ternary.False */; + } } else if (targetFlags & 4194304 /* TypeFlags.Index */) { var targetType_1 = target.type; @@ -65726,7 +66635,6 @@ var ts; result &= isRelatedTo(source.indexType, target.indexType, 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } if (reportErrors) { @@ -65829,7 +66737,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } var c = target; @@ -65844,7 +66751,6 @@ var ts; if (result = skipTrue ? -1 /* Ternary.True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false)) { result &= skipFalse ? -1 /* Ternary.True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false); if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65857,31 +66763,29 @@ var ts; } // Report unreliable variance for type variables referenced in template literal type placeholders. // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* Ternary.True */; } } + else if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + if (!(source.flags & 268435456 /* TypeFlags.StringMapping */)) { + if (isMemberOfStringMapping(source, target)) { + return -1 /* Ternary.True */; + } + } + } if (sourceFlags & 8650752 /* TypeFlags.TypeVariable */) { // IndexedAccess comparisons are handled above in the `targetFlags & TypeFlage.IndexedAccess` branch if (!(sourceFlags & 8388608 /* TypeFlags.IndexedAccess */ && targetFlags & 8388608 /* TypeFlags.IndexedAccess */)) { - var constraint = getConstraintOfType(source); - if (!constraint || (sourceFlags & 262144 /* TypeFlags.TypeParameter */ && constraint.flags & 1 /* TypeFlags.Any */)) { - // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* TypeFlags.NonPrimitive */), 3 /* RecursionFlags.Both */)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } + var constraint = getConstraintOfType(source) || unknownType; // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed - else if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && constraint !== unknownType && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { return result; } if (isMappedTypeGenericIndexedAccess(source)) { @@ -65890,7 +66794,6 @@ var ts; var indexConstraint = getConstraintOfType(source.indexType); if (indexConstraint) { if (result = isRelatedTo(getIndexedAccessType(source.objectType, indexConstraint), target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65899,7 +66802,6 @@ var ts; } else if (sourceFlags & 4194304 /* TypeFlags.Index */) { if (result = isRelatedTo(keyofConstraintType, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65907,22 +66809,22 @@ var ts; if (!(targetFlags & 134217728 /* TypeFlags.TemplateLiteral */)) { var constraint = getBaseConstraintOfType(source); if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } } else if (sourceFlags & 268435456 /* TypeFlags.StringMapping */) { - if (targetFlags & 268435456 /* TypeFlags.StringMapping */ && source.symbol === target.symbol) { + if (targetFlags & 268435456 /* TypeFlags.StringMapping */) { + if (source.symbol !== target.symbol) { + return 0 /* Ternary.False */; + } if (result = isRelatedTo(source.type, target.type, 3 /* RecursionFlags.Both */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } else { var constraint = getBaseConstraintOfType(source); if (constraint && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65931,7 +66833,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } if (targetFlags & 16777216 /* TypeFlags.Conditional */) { @@ -65954,7 +66855,6 @@ var ts; result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65965,7 +66865,6 @@ var ts; var distributiveConstraint = hasNonCircularBaseConstraint(source) ? getConstraintOfDistributiveConditionalType(source) : undefined; if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65975,7 +66874,6 @@ var ts; var defaultConstraint = getDefaultConstraintOfConditionalType(source); if (defaultConstraint) { if (result = isRelatedTo(defaultConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65988,7 +66886,6 @@ var ts; if (isGenericMappedType(target)) { if (isGenericMappedType(source)) { if (result = mappedTypeRelatedTo(source, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -66126,18 +67023,6 @@ var ts; } } } - function reportUnmeasurableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); - } - return p; - } - function reportUnreliableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); - } - return p; - } // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice // that S and T are contra-variant whereas X and Y are co-variant. @@ -66147,7 +67032,7 @@ var ts; if (modifiersRelated) { var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); - var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); + var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMapper : reportUnreliableMapper); if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* RecursionFlags.Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { @@ -66201,11 +67086,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_20 = 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_21 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -66221,7 +67106,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_8 = _loop_21(i); + var state_8 = _loop_22(i); switch (state_8) { case "continue-outer": continue outer; } @@ -66235,7 +67120,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_7 = _loop_20(combination); + var state_7 = _loop_21(combination); if (typeof state_7 === "object") return state_7.value; } @@ -66683,7 +67568,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, makeFunctionTypeMapper(reportUnreliableMarkers)); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, reportUnreliableMapper); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -66838,7 +67723,7 @@ var ts; return typeCouldHaveTopLevelSingletonTypes(constraint); } } - return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */); + return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */); } function getExactOptionalUnassignableProperties(source, target) { if (isTupleType(source) && isTupleType(target)) @@ -66942,7 +67827,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_22 = 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 */ : @@ -66978,12 +67863,12 @@ var ts; } variances.push(variance); }; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - _loop_22(tp); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var tp = typeParameters_2[_i]; + _loop_23(tp); } links.variances = variances; - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); } return links.variances; } @@ -67321,35 +68206,33 @@ var ts; var commonBaseType; for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { var t = types_13[_i]; - var baseType = getBaseTypeOfLiteralType(t); - if (!commonBaseType) { - commonBaseType = baseType; - } - if (baseType === t || baseType !== commonBaseType) { - return false; + if (!(t.flags & 131072 /* TypeFlags.Never */)) { + var baseType = getBaseTypeOfLiteralType(t); + commonBaseType !== null && commonBaseType !== void 0 ? commonBaseType : (commonBaseType = baseType); + if (baseType === t || baseType !== commonBaseType) { + return false; + } } } return true; } - // When the candidate types are all literal types with the same base type, return a union - // of those literal types. Otherwise, return the leftmost type for which no type to the - // right is a supertype. - function getSupertypeOrUnion(types) { - if (types.length === 1) { - return types[0]; - } - return literalTypesWithSameBaseType(types) ? - getUnionType(types) : - ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + function getCombinedTypeFlags(types) { + return ts.reduceLeft(types, function (flags, t) { return flags | (t.flags & 1048576 /* TypeFlags.Union */ ? getCombinedTypeFlags(t.types) : t.flags); }, 0); } function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); + if (types.length === 1) { + return types[0]; } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* TypeFlags.Nullable */); }); - return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* TypeFlags.Nullable */) : - getUnionType(types, 2 /* UnionReduction.Subtype */); + // Remove nullable types from each of the candidates. + var primaryTypes = strictNullChecks ? ts.sameMap(types, function (t) { return filterType(t, function (u) { return !(u.flags & 98304 /* TypeFlags.Nullable */); }); }) : types; + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + var superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? + getUnionType(primaryTypes) : + ts.reduceLeft(primaryTypes, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + // Add any nullable types that occurred in the candidates back to the result. + return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & 98304 /* TypeFlags.Nullable */); } // Return the leftmost type for which no type to the right is a subtype. function getCommonSubtype(types) { @@ -67453,9 +68336,14 @@ var ts; type.flags & 256 /* TypeFlags.NumberLiteral */ ? numberType : type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? bigintType : type.flags & 512 /* TypeFlags.BooleanLiteral */ ? booleanType : - type.flags & 1048576 /* TypeFlags.Union */ ? mapType(type, getBaseTypeOfLiteralType) : + type.flags & 1048576 /* TypeFlags.Union */ ? getBaseTypeOfLiteralTypeUnion(type) : type; } + function getBaseTypeOfLiteralTypeUnion(type) { + var _a; + var key = "B".concat(getTypeId(type)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); + } function getWidenedLiteralType(type) { return type.flags & 1024 /* TypeFlags.EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : type.flags & 128 /* TypeFlags.StringLiteral */ && isFreshLiteralType(type) ? stringType : @@ -67536,29 +68424,8 @@ var ts; var value = _a.value; return value.base10Value === "0"; } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - result |= getFalsyFlags(t); - } - return result; - } - // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null - // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns - // no flags for all other types (including non-falsy literal types). - function getFalsyFlags(type) { - return type.flags & 1048576 /* TypeFlags.Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? type.value === "" ? 128 /* TypeFlags.StringLiteral */ : 0 : - type.flags & 256 /* TypeFlags.NumberLiteral */ ? type.value === 0 ? 256 /* TypeFlags.NumberLiteral */ : 0 : - type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* TypeFlags.BigIntLiteral */ : 0 : - type.flags & 512 /* TypeFlags.BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* TypeFlags.BooleanLiteral */ : 0 : - type.flags & 117724 /* TypeFlags.PossiblyFalsy */; - } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 117632 /* TypeFlags.DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* TypeFlags.DefinitelyFalsy */); }) : - type; + return filterType(type, function (t) { return !!(getTypeFacts(t) & 4194304 /* TypeFacts.Truthy */); }); } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); @@ -67593,20 +68460,15 @@ var ts; return type.flags & 32768 /* TypeFlags.Undefined */ ? type : getUnionType([type, isProperty ? missingType : undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { - // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates - // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' - // that isn't eliminated by a NonNullable instantiation. - var reducedType = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* SymbolFlags.TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? - getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : - reducedType; + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : + getIntersectionType([type, emptyObjectType]); } function getNonNullableType(type) { - return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + return strictNullChecks ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; @@ -67660,12 +68522,13 @@ var ts; * with no call or construct signatures. */ function isObjectTypeWithInferableIndex(type) { + var objectFlags = ts.getObjectFlags(type); return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* SymbolFlags.ObjectLiteral */ | 2048 /* SymbolFlags.TypeLiteral */ | 384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */)) !== 0 && !(type.symbol.flags & 32 /* SymbolFlags.Class */) - && !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & 4194304 /* ObjectFlags.ObjectRestType */) || !!(objectFlags & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* CheckFlags.Readonly */); @@ -67998,27 +68861,29 @@ var ts; signature: signature, flags: flags, compareTypes: compareTypes, - mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }), - nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }), + mapper: reportUnmeasurableMapper, + nonFixingMapper: reportUnmeasurableMapper, }; + context.mapper = makeFixingMapperForContext(context); + context.nonFixingMapper = makeNonFixingMapperForContext(context); return context; } - function mapToInferredType(context, t, fix) { - var inferences = context.inferences; - for (var i = 0; i < inferences.length; i++) { - var inference = inferences[i]; - if (t === inference.typeParameter) { - if (fix && !inference.isFixed) { - // Before we commit to a particular inference (and thus lock out any further inferences), - // we infer from any intra-expression inference sites we have collected. - inferFromIntraExpressionSites(context); - clearCachedInferences(inferences); - inference.isFixed = true; - } - return getInferredType(context, i); + function makeFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (inference, i) { return function () { + if (!inference.isFixed) { + // Before we commit to a particular inference (and thus lock out any further inferences), + // we infer from any intra-expression inference sites we have collected. + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; } - } - return t; + return getInferredType(context, i); + }; })); + } + function makeNonFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (_, i) { return function () { + return getInferredType(context, i); + }; })); } function clearCachedInferences(inferences) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { @@ -68287,13 +69152,40 @@ var ts; return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen); } - function isValidBigIntString(s) { + /** + * Tests whether the provided string can be parsed as a number. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting number matches the input when converted back to a string. + */ + function isValidNumberString(s, roundTripOnly) { + if (s === "") + return false; + var n = +s; + return isFinite(n) && (!roundTripOnly || "" + n === s); + } + /** + * @param text a valid bigint string excluding a trailing `n`, but including a possible prefix `-`. Use `isValidBigIntString(text, roundTripOnly)` before calling this function. + */ + function parseBigIntLiteralType(text) { + var negative = text.startsWith("-"); + var base10Value = ts.parsePseudoBigInt("".concat(negative ? text.slice(1) : text, "n")); + return getBigIntLiteralType({ negative: negative, base10Value: base10Value }); + } + /** + * Tests whether the provided string can be parsed as a bigint. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting bigint matches the input when converted back to a string. + */ + function isValidBigIntString(s, roundTripOnly) { + if (s === "") + return false; var scanner = ts.createScanner(99 /* ScriptTarget.ESNext */, /*skipTrivia*/ false); var success = true; scanner.setOnError(function () { return success = false; }); scanner.setText(s + "n"); var result = scanner.scan(); - if (result === 40 /* SyntaxKind.MinusToken */) { + var negative = result === 40 /* SyntaxKind.MinusToken */; + if (negative) { result = scanner.scan(); } var flags = scanner.getTokenFlags(); @@ -68302,7 +69194,33 @@ var ts; // * a bigint can be scanned, and that when it is scanned, it is // * the full length of the input string (so the scanner is one character beyond the augmented input length) // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) - return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */); + return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */) + && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); + } + function isMemberOfStringMapping(source, target) { + if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + return true; + } + if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { + return isTypeAssignableTo(source, target); + } + if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + // We need to see whether applying the same mappings of the target + // onto the source would produce an identical type *and* that + // it's compatible with the inner-most non-string-mapped type. + // + // The intuition here is that if same mappings don't affect the source at all, + // and the source is compatible with the unmapped target, then they must + // still reside in the same domain. + var mappingStack = []; + while (target.flags & 268435456 /* TypeFlags.StringMapping */) { + mappingStack.unshift(target.symbol); + target = target.type; + } + var mappedSource = ts.reduceLeft(mappingStack, function (memo, value) { return getStringMappingType(value, memo); }, source); + return mappedSource === source && isMemberOfStringMapping(source, target); + } + return false; } function isValidTypeForTemplateLiteralPlaceholder(source, target) { if (source === target || target.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */)) { @@ -68310,9 +69228,10 @@ var ts; } if (source.flags & 128 /* TypeFlags.StringLiteral */) { var value = source.value; - return !!(target.flags & 8 /* TypeFlags.Number */ && value !== "" && isFinite(+value) || - target.flags & 64 /* TypeFlags.BigInt */ && value !== "" && isValidBigIntString(value) || - target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName); + return !!(target.flags & 8 /* TypeFlags.Number */ && isValidNumberString(value, /*roundTripOnly*/ false) || + target.flags & 64 /* TypeFlags.BigInt */ && isValidBigIntString(value, /*roundTripOnly*/ false) || + target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName || + target.flags & 268435456 /* TypeFlags.StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target)); } if (source.flags & 134217728 /* TypeFlags.TemplateLiteral */) { var texts = source.texts; @@ -68435,10 +69354,13 @@ var ts; propagationType = savePropagationType; return; } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - // Source and target are types originating in the same generic type alias declaration. - // Simply infer from source type arguments to target type arguments. - inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + if (source.aliasSymbol && source.aliasSymbol === target.aliasSymbol) { + if (source.aliasTypeArguments) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + } + // And if there weren't any type arguments, there's no reason to run inference as the types must be the same. return; } if (source === target && source.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { @@ -68494,18 +69416,26 @@ var ts; target = getActualTypeVariable(target); } if (target.flags & 8650752 /* TypeFlags.TypeVariable */) { - // If target is a type parameter, make an inference, unless the source type contains - // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). - // Because the anyFunctionType is internal, it should not be exposed to the user by adding - // it as an inference candidate. Hopefully, a better candidate will come along that does - // not contain anyFunctionType when we come back to this argument for its second round - // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard - // when constructing types from type parameters that had no inference candidates). - if (source === nonInferrableAnyType || source === silentNeverType || (priority & 128 /* InferencePriority.ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + // Skip inference if the source is "blocked", which is used by the language service to + // prevent inference on nodes currently being edited. + if (isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); if (inference) { + // If target is a type parameter, make an inference, unless the source type contains + // a "non-inferrable" type. Types with this flag set are markers used to prevent inference. + // + // For example: + // - anyFunctionType is a wildcard type that's used to avoid contextually typing functions; + // it's internal, so should not be exposed to the user by adding it as a candidate. + // - autoType (and autoArrayType) is a special "any" used in control flow; like anyFunctionType, + // it's internal and should not be observable. + // - silentNeverType is returned by getInferredType when instantiating a generic function for + // inference (and a type variable has no mapping). + // + // This flag is infectious; if we produce Box (where never is silentNeverType), Box is + // also non-inferrable. if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) { return; } @@ -68562,15 +69492,11 @@ var ts; inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target)); } else if (source.flags & 4194304 /* TypeFlags.Index */ && target.flags & 4194304 /* TypeFlags.Index */) { - contravariant = !contravariant; - inferFromTypes(source.type, target.type); - contravariant = !contravariant; + inferFromContravariantTypes(source.type, target.type); } else if ((isLiteralType(source) || source.flags & 4 /* TypeFlags.String */) && target.flags & 4194304 /* TypeFlags.Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - contravariant = !contravariant; - inferWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); - contravariant = !contravariant; + inferFromContravariantTypesWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); } else if (source.flags & 8388608 /* TypeFlags.IndexedAccess */ && target.flags & 8388608 /* TypeFlags.IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -68583,10 +69509,7 @@ var ts; } else if (source.flags & 33554432 /* TypeFlags.Substitution */) { inferFromTypes(source.baseType, target); - var oldPriority = priority; - priority |= 4 /* InferencePriority.SubstituteSource */; - inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority - priority = oldPriority; + inferWithPriority(source.substitute, target, 4 /* InferencePriority.SubstituteSource */); // Make substitute inference at a lower priority } else if (target.flags & 16777216 /* TypeFlags.Conditional */) { invokeOnce(source, target, inferToConditionalType); @@ -68636,6 +69559,18 @@ var ts; inferFromTypes(source, target); priority = savePriority; } + function inferFromContravariantTypesWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromContravariantTypes(source, target); + priority = savePriority; + } + function inferToMultipleTypesWithPriority(source, targets, targetFlags, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferToMultipleTypes(source, targets, targetFlags); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -68700,10 +69635,13 @@ var ts; } } function inferFromContravariantTypes(source, target) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + function inferFromContravariantTypesIfStrictFunctionTypes(source, target) { if (strictFunctionTypes || priority & 1024 /* InferencePriority.AlwaysStrict */) { - contravariant = !contravariant; - inferFromTypes(source, target); - contravariant = !contravariant; + inferFromContravariantTypes(source, target); } else { inferFromTypes(source, target); @@ -68722,8 +69660,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var type = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* TypeFlags.Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -68867,11 +69805,8 @@ var ts; inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else { - var savePriority = priority; - priority |= contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; - inferToMultipleTypes(source, targetTypes, target.flags); - priority = savePriority; + inferToMultipleTypesWithPriority(source, targetTypes, target.flags, contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0); } } function inferToTemplateLiteralType(source, target) { @@ -68884,8 +69819,57 @@ 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_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 + // allowed template literal placeholder types, infer from a literal type corresponding to the constraint. + if (source_1.flags & 128 /* TypeFlags.StringLiteral */ && target_3.flags & 8650752 /* TypeFlags.TypeVariable */) { + var inferenceContext = getInferenceInfoForType(target_3); + var constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : undefined; + if (constraint && !isTypeAny(constraint)) { + var constraintTypes = constraint.flags & 1048576 /* TypeFlags.Union */ ? constraint.types : [constraint]; + var allTypeFlags_1 = ts.reduceLeft(constraintTypes, function (flags, t) { return flags | t.flags; }, 0); + // If the constraint contains `string`, we don't need to look for a more preferred type + if (!(allTypeFlags_1 & 4 /* TypeFlags.String */)) { + var str_1 = source_1.value; + // If the type contains `number` or a number literal and the string isn't a valid number, exclude numbers + if (allTypeFlags_1 & 296 /* TypeFlags.NumberLike */ && !isValidNumberString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~296 /* TypeFlags.NumberLike */; + } + // If the type contains `bigint` or a bigint literal and the string isn't a valid bigint, exclude bigints + if (allTypeFlags_1 & 2112 /* TypeFlags.BigIntLike */ && !isValidBigIntString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~2112 /* TypeFlags.BigIntLike */; + } + // for each type in the constraint, find the highest priority matching type + var matchingType = ts.reduceLeft(constraintTypes, function (left, right) { + return !(right.flags & allTypeFlags_1) ? left : + left.flags & 4 /* TypeFlags.String */ ? left : right.flags & 4 /* TypeFlags.String */ ? source_1 : + left.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? left : right.flags & 134217728 /* TypeFlags.TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source_1, right) ? source_1 : + left.flags & 268435456 /* TypeFlags.StringMapping */ ? left : right.flags & 268435456 /* TypeFlags.StringMapping */ && str_1 === applyStringMapping(right.symbol, str_1) ? source_1 : + left.flags & 128 /* TypeFlags.StringLiteral */ ? left : right.flags & 128 /* TypeFlags.StringLiteral */ && right.value === str_1 ? right : + left.flags & 8 /* TypeFlags.Number */ ? left : right.flags & 8 /* TypeFlags.Number */ ? getNumberLiteralType(+str_1) : + left.flags & 32 /* TypeFlags.Enum */ ? left : right.flags & 32 /* TypeFlags.Enum */ ? getNumberLiteralType(+str_1) : + left.flags & 256 /* TypeFlags.NumberLiteral */ ? left : right.flags & 256 /* TypeFlags.NumberLiteral */ && right.value === +str_1 ? right : + left.flags & 64 /* TypeFlags.BigInt */ ? left : right.flags & 64 /* TypeFlags.BigInt */ ? parseBigIntLiteralType(str_1) : + left.flags & 2048 /* TypeFlags.BigIntLiteral */ ? left : right.flags & 2048 /* TypeFlags.BigIntLiteral */ && ts.pseudoBigIntToString(right.value) === str_1 ? right : + left.flags & 16 /* TypeFlags.Boolean */ ? left : right.flags & 16 /* TypeFlags.Boolean */ ? str_1 === "true" ? trueType : str_1 === "false" ? falseType : booleanType : + left.flags & 512 /* TypeFlags.BooleanLiteral */ ? left : right.flags & 512 /* TypeFlags.BooleanLiteral */ && right.intrinsicName === str_1 ? right : + left.flags & 32768 /* TypeFlags.Undefined */ ? left : right.flags & 32768 /* TypeFlags.Undefined */ && right.intrinsicName === str_1 ? right : + left.flags & 65536 /* TypeFlags.Null */ ? left : right.flags & 65536 /* TypeFlags.Null */ && right.intrinsicName === str_1 ? right : + left; + }, neverType); + if (!(matchingType.flags & 131072 /* TypeFlags.Never */)) { + inferFromTypes(matchingType, target_3); + return "continue"; + } + } + } + } + inferFromTypes(source_1, target_3); + }; for (var i = 0; i < types.length; i++) { - inferFromTypes(matches ? matches[i] : neverType, types[i]); + _loop_24(i); } } } @@ -68999,20 +69983,17 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } - function inferFromSignature(source, target, skipParameters) { - if (!skipParameters) { - var saveBivariant = bivariant; - var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; - // Once we descend into a bivariant signature we remain bivariant for all nested inferences - bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; - applyToParameterTypes(source, target, inferFromContravariantTypes); - bivariant = saveBivariant; - } + function inferFromSignature(source, target) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; + applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); + bivariant = saveBivariant; applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { @@ -69259,6 +70240,15 @@ var ts; var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); return key && key + "." + propName; } + break; + case 201 /* SyntaxKind.ObjectBindingPattern */: + case 202 /* SyntaxKind.ArrayBindingPattern */: + case 256 /* SyntaxKind.FunctionDeclaration */: + case 213 /* SyntaxKind.FunctionExpression */: + case 214 /* SyntaxKind.ArrowFunction */: + case 169 /* SyntaxKind.MethodDeclaration */: + // Handle pseudo-references originating in getNarrowedTypeOfSymbol. + return "".concat(getNodeId(node), "#").concat(getTypeId(declaredType)); } return undefined; } @@ -69403,7 +70393,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_23 = 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) { @@ -69427,9 +70417,9 @@ var ts; } } }; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - var state_9 = _loop_23(type); + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var type = types_15[_i]; + var state_9 = _loop_25(type); if (typeof state_9 === "object") return state_9.value; } @@ -69518,23 +70508,25 @@ var ts; // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 131072 /* TypeFlags.Never */) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType)) { - reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types - } - // Our crude heuristic produces an invalid result in some cases: see GH#26130. - // For now, when that happens, we give up and don't narrow at all. (This also - // means we'll never narrow for erroneous assignments where the assigned type - // is not assignable to the declared type.) - if (isTypeAssignableTo(assignedType, reducedType)) { - return reducedType; - } + var _a; + if (declaredType === assignedType) { + return declaredType; } - return declaredType; + if (assignedType.flags & 131072 /* TypeFlags.Never */) { + return assignedType; + } + var key = "A".concat(getTypeId(declaredType), ",").concat(getTypeId(assignedType)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); + } + function getAssignmentReducedTypeWorker(declaredType, assignedType) { + var filteredType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + // Ensure that we narrow to fresh types if the assignment is a fresh boolean literal type. + var reducedType = assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType; + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType; } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype @@ -69543,14 +70535,16 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type, ignoreObjects) { - if (ignoreObjects === void 0) { ignoreObjects = false; } + function getTypeFacts(type) { + if (type.flags & (2097152 /* TypeFlags.Intersection */ | 465829888 /* TypeFlags.Instantiable */)) { + type = getBaseConstraintOfType(type) || unknownType; + } var flags = type.flags; - if (flags & 4 /* TypeFlags.String */) { + if (flags & (4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */)) { return strictNullChecks ? 16317953 /* TypeFacts.StringStrictFacts */ : 16776705 /* TypeFacts.StringFacts */; } - if (flags & 128 /* TypeFlags.StringLiteral */) { - var isEmpty = type.value === ""; + if (flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */)) { + var isEmpty = flags & 128 /* TypeFlags.StringLiteral */ && type.value === ""; return strictNullChecks ? isEmpty ? 12123649 /* TypeFacts.EmptyStringStrictFacts */ : 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* TypeFacts.EmptyStringFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; @@ -69582,20 +70576,20 @@ var ts; (type === falseType || type === regularFalseType) ? 12580616 /* TypeFacts.FalseFacts */ : 16774920 /* TypeFacts.TrueFacts */; } if (flags & 524288 /* TypeFlags.Object */) { - if (ignoreObjects) { - return 16768959 /* TypeFacts.AndFactsMask */; // This is the identity element for computing type facts of intersection. - } return ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && isEmptyObjectType(type) ? - strictNullChecks ? 16318463 /* TypeFacts.EmptyObjectStrictFacts */ : 16777215 /* TypeFacts.EmptyObjectFacts */ : + strictNullChecks ? 83427327 /* TypeFacts.EmptyObjectStrictFacts */ : 83886079 /* TypeFacts.EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* TypeFacts.FunctionStrictFacts */ : 16728000 /* TypeFacts.FunctionFacts */ : strictNullChecks ? 7888800 /* TypeFacts.ObjectStrictFacts */ : 16736160 /* TypeFacts.ObjectFacts */; } - if (flags & (16384 /* TypeFlags.Void */ | 32768 /* TypeFlags.Undefined */)) { - return 9830144 /* TypeFacts.UndefinedFacts */; + if (flags & 16384 /* TypeFlags.Void */) { + return 9830144 /* TypeFacts.VoidFacts */; + } + if (flags & 32768 /* TypeFlags.Undefined */) { + return 26607360 /* TypeFacts.UndefinedFacts */; } if (flags & 65536 /* TypeFlags.Null */) { - return 9363232 /* TypeFacts.NullFacts */; + return 42917664 /* TypeFacts.NullFacts */; } if (flags & 12288 /* TypeFlags.ESSymbolLike */) { return strictNullChecks ? 7925520 /* TypeFacts.SymbolStrictFacts */ : 16772880 /* TypeFacts.SymbolFacts */; @@ -69606,37 +70600,56 @@ var ts; if (flags & 131072 /* TypeFlags.Never */) { return 0 /* TypeFacts.None */; } - if (flags & 465829888 /* TypeFlags.Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : - strictNullChecks ? 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; - } if (flags & 1048576 /* TypeFlags.Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* TypeFacts.None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* TypeFacts.None */); } if (flags & 2097152 /* TypeFlags.Intersection */) { - // When an intersection contains a primitive type we ignore object type constituents as they are - // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. - ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */)); - return getIntersectionTypeFacts(type, ignoreObjects); + return getIntersectionTypeFacts(type); } - return 16777215 /* TypeFacts.All */; + return 83886079 /* TypeFacts.UnknownFacts */; } - function getIntersectionTypeFacts(type, ignoreObjects) { + function getIntersectionTypeFacts(type) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + var ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */); // When computing the type facts of an intersection type, certain type facts are computed as `and` // and others are computed as `or`. var oredFacts = 0 /* TypeFacts.None */; - var andedFacts = 16777215 /* TypeFacts.All */; + var andedFacts = 134217727 /* TypeFacts.All */; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - var f = getTypeFacts(t, ignoreObjects); - oredFacts |= f; - andedFacts &= f; + if (!(ignoreObjects && t.flags & 524288 /* TypeFlags.Object */)) { + var f = getTypeFacts(t); + oredFacts |= f; + andedFacts &= f; + } } - return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 16768959 /* TypeFacts.AndFactsMask */; + return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 134209471 /* TypeFacts.AndFactsMask */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } + // This function is similar to getTypeWithFacts, except that in strictNullChecks mode it replaces type + // unknown with the union {} | null | undefined (and reduces that accordingly), and it intersects remaining + // instantiable types with {}, {} | null, or {} | undefined in order to remove null and/or undefined. + function getAdjustedTypeWithFacts(type, facts) { + var reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 /* TypeFlags.Unknown */ ? unknownUnionType : type, facts)); + if (strictNullChecks) { + switch (facts) { + case 524288 /* TypeFacts.NEUndefined */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ ? getIntersectionType([t, getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ && !maybeTypeOfKind(reduced, 65536 /* TypeFlags.Null */) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t; }); + case 1048576 /* TypeFacts.NENull */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ ? getIntersectionType([t, getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ && !maybeTypeOfKind(reduced, 32768 /* TypeFlags.Undefined */) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t; }); + case 2097152 /* TypeFacts.NEUndefinedOrNull */: + case 4194304 /* TypeFacts.Truthy */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 262144 /* TypeFacts.EQUndefinedOrNull */ ? getGlobalNonNullableTypeInstantiation(t) : t; }); + } + } + return reduced; + } + function recombineUnknownType(type) { + return type === unknownUnionType ? unknownType : type; + } function getTypeWithDefault(type, defaultExpression) { return defaultExpression ? getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : @@ -69791,19 +70804,17 @@ var ts; } return links.switchTypes; } - function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) { + // Get the type names from all cases in a switch on `typeof`. The default clause and/or duplicate type names are + // represented as undefined. Return undefined if one or more case clause expressions are not string literals. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + if (ts.some(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 289 /* SyntaxKind.CaseClause */ && !ts.isStringLiteralLike(clause.expression); })) { + return undefined; + } var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 289 /* SyntaxKind.CaseClause */) { - if (ts.isStringLiteralLike(clause.expression)) { - witnesses.push(clause.expression.text); - continue; - } - return ts.emptyArray; - } - if (retainDefault) - witnesses.push(/*explicitDefaultStatement*/ undefined); + var text = clause.kind === 289 /* SyntaxKind.CaseClause */ ? clause.expression.text : undefined; + witnesses.push(text && !ts.contains(witnesses, text) ? text : undefined); } return witnesses; } @@ -69885,8 +70896,8 @@ var ts; var types = origin && origin.flags & 1048576 /* TypeFlags.Union */ ? origin.types : type.types; var mappedTypes; var changed = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; var mapped = t.flags & 1048576 /* TypeFlags.Union */ ? mapType(t, mapper, noReductions) : mapper(t); changed || (changed = t !== mapped); if (mapped) { @@ -69972,8 +70983,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (!(t.flags & 131072 /* TypeFlags.Never */)) { if (!(ts.getObjectFlags(t) & 256 /* ObjectFlags.EvolvingArray */)) { return false; @@ -70434,7 +71445,7 @@ var ts; } // for (const _ in ref) acts as a nonnull on ref if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 243 /* SyntaxKind.ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { - return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); } // Assignment doesn't affect reference return undefined; @@ -70694,7 +71705,7 @@ var ts; if (isEvolvingArrayTypeList(types)) { return getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))); } - var result = getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + var result = recombineUnknownType(getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction)); if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* TypeFlags.Union */ && ts.arraysEqual(result.types, declaredType.types)) { return declaredType; } @@ -70796,11 +71807,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return type.flags & 2 /* TypeFlags.Unknown */ && assumeTrue ? nonNullUnknownType : - getTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); + return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -70922,7 +71932,7 @@ var ts; var targetType = ts.hasStaticModifier(ts.Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows: @@ -70940,7 +71950,7 @@ var ts; // Note that we include any and unknown in the exclusion test because their domain includes null and undefined. var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) || equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* TypeFlags.AnyOrUnknown */ | nullableFlags)); }); - return removeNullable ? getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; + return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* TypeFlags.Any */) { @@ -70950,9 +71960,6 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (assumeTrue && (type.flags & 2 /* TypeFlags.Unknown */) && (operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 35 /* SyntaxKind.ExclamationEqualsToken */) && (valueType.flags & 65536 /* TypeFlags.Null */)) { - return getUnionType([nullType, undefinedType]); - } if ((type.flags & 2 /* TypeFlags.Unknown */) && assumeTrue && (operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */ || operator === 37 /* SyntaxKind.ExclamationEqualsEqualsToken */)) { if (valueType.flags & (131068 /* TypeFlags.Primitive */ | 67108864 /* TypeFlags.NonPrimitive */)) { return valueType; @@ -70972,7 +71979,7 @@ var ts; valueType.flags & 65536 /* TypeFlags.Null */ ? assumeTrue ? 131072 /* TypeFacts.EQNull */ : 1048576 /* TypeFacts.NENull */ : assumeTrue ? 65536 /* TypeFacts.EQUndefined */ : 524288 /* TypeFacts.NEUndefined */; - return type.flags & 2 /* TypeFlags.Unknown */ && facts & (1048576 /* TypeFacts.NENull */ | 2097152 /* TypeFacts.NEUndefinedOrNull */) ? nonNullUnknownType : getTypeWithFacts(type, facts); + return getAdjustedTypeWithFacts(type, facts); } if (assumeTrue) { var filterFn = operator === 34 /* SyntaxKind.EqualsEqualsToken */ ? @@ -70993,24 +72000,13 @@ var ts; var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } - if (type.flags & 1 /* TypeFlags.Any */ && literal.text === "function") { - return type; - } - if (assumeTrue && type.flags & 2 /* TypeFlags.Unknown */ && literal.text === "object") { - // The non-null unknown type is used to track whether a previous narrowing operation has removed the null type - // from the unknown type. For example, the expression `x && typeof x === 'object'` first narrows x to the non-null - // unknown type, and then narrows that to the non-primitive type. - return type === nonNullUnknownType ? nonPrimitiveType : getUnionType([nonPrimitiveType, nullType]); - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 128 /* TypeFacts.TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */; - var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text); - return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts); + return assumeTrue ? + narrowTypeByTypeName(type, literal.text) : + getTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */); } function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); @@ -71057,97 +72053,52 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* TypeFlags.Never */ ? defaultType : getUnionType([caseType, defaultType]); } - function getImpliedTypeFromTypeofGuard(type, text) { - switch (text) { - case "function": - return type.flags & 1 /* TypeFlags.Any */ ? type : globalFunctionType; - case "object": - return type.flags & 2 /* TypeFlags.Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; - default: - return typeofTypesByName.get(text); - } - } - // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are - // super-types of the implied guard will be retained in the final type: this is because type-facts only - // filter. Instead, we would like to replace those union constituents with the more precise type implied by - // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not - // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to - // filtering by type-facts. - function narrowUnionMemberByTypeof(candidate) { - return function (type) { - if (isTypeSubtypeOf(type, candidate)) { - return type; - } - if (isTypeSubtypeOf(candidate, type)) { - return candidate; - } - if (type.flags & 465829888 /* TypeFlags.Instantiable */) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(candidate, constraint)) { - return getIntersectionType([type, candidate]); - } - } - return type; - }; + function narrowTypeByTypeName(type, typeName) { + switch (typeName) { + case "string": return narrowTypeByTypeFacts(type, stringType, 1 /* TypeFacts.TypeofEQString */); + case "number": return narrowTypeByTypeFacts(type, numberType, 2 /* TypeFacts.TypeofEQNumber */); + case "bigint": return narrowTypeByTypeFacts(type, bigintType, 4 /* TypeFacts.TypeofEQBigInt */); + case "boolean": return narrowTypeByTypeFacts(type, booleanType, 8 /* TypeFacts.TypeofEQBoolean */); + case "symbol": return narrowTypeByTypeFacts(type, esSymbolType, 16 /* TypeFacts.TypeofEQSymbol */); + case "object": return type.flags & 1 /* TypeFlags.Any */ ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32 /* TypeFacts.TypeofEQObject */), narrowTypeByTypeFacts(type, nullType, 131072 /* TypeFacts.EQNull */)]); + case "function": return type.flags & 1 /* TypeFlags.Any */ ? type : narrowTypeByTypeFacts(type, globalFunctionType, 64 /* TypeFacts.TypeofEQFunction */); + case "undefined": return narrowTypeByTypeFacts(type, undefinedType, 65536 /* TypeFacts.EQUndefined */); + } + return narrowTypeByTypeFacts(type, nonPrimitiveType, 128 /* TypeFacts.TypeofEQHostObject */); + } + function narrowTypeByTypeFacts(type, impliedType, facts) { + return mapType(type, function (t) { + // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate + // the constituent based on its type facts. We use the strict subtype relation because it treats `object` + // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, + // but are classified as "function" according to `typeof`. + return isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? getTypeFacts(t) & facts ? t : neverType : + // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied + // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. + isTypeSubtypeOf(impliedType, t) ? impliedType : + // Neither the constituent nor the implied type is a subtype of the other, however their domains may still + // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate + // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. + getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : + neverType; + }); } function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { - var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true); - if (!switchWitnesses.length) { + var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!witnesses) { return type; } - // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause - var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); - var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); - var clauseWitnesses; - var switchFacts; - if (defaultCaseLocation > -1) { - // We no longer need the undefined denoting an explicit default case. Remove the undefined and - // fix-up clauseStart and clauseEnd. This means that we don't have to worry about undefined in the - // witness array. - var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); - // The adjusted clause start and end after removing the `default` statement. - var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; - var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; - clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); - switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); - } - else { - clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); - switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); - } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause. + var defaultIndex = ts.findIndex(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 290 /* SyntaxKind.DefaultClause */; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultIndex >= clauseStart && defaultIndex < clauseEnd); if (hasDefaultClause) { - return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + // In the default clause we filter constituents down to those that are not-equal to all handled cases. + var notEqualFacts_1 = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); + return filterType(type, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }); } - /* - The implied type is the raw type suggested by a - value being caught in this clause. - - When the clause contains a default case we ignore - the implied type and try to narrow using any facts - we can learn: see `switchFacts`. - - Example: - switch (typeof x) { - case 'number': - case 'string': break; - default: break; - case 'number': - case 'boolean': break - } - - In the first clause (case `number` and `string`) the - implied type is number | string. - - In the default clause we de not compute an implied type. - - In the third clause (case `number` and `boolean`) - the naive implied type is number | boolean, however - we use the type facts to narrow the implied type to - boolean. We know that number cannot be selected - because it is caught in the first clause. - */ - var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts); - return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts); + // In the non-default cause we create a union of the type narrowed by each of the listed cases. + var clauseWitnesses = witnesses.slice(clauseStart, clauseEnd); + return getUnionType(ts.map(clauseWitnesses, function (text) { return text ? narrowTypeByTypeName(type, text) : neverType; })); } function isMatchingConstructorReference(expr) { return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || @@ -71198,7 +72149,7 @@ var ts; var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } @@ -71232,29 +72183,48 @@ var ts; if (!nonConstructorTypeInUnion) return type; } - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { + function getNarrowedType(type, candidate, assumeTrue, checkDerived) { + var _a; + var key = type.flags & 1048576 /* TypeFlags.Union */ ? "N".concat(getTypeId(type), ",").concat(getTypeId(candidate), ",").concat((assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)) : undefined; + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); + } + function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) { + var isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf; if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - // If the current type is a union type, remove all constituents that couldn't be instances of - // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 1048576 /* TypeFlags.Union */) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 131072 /* TypeFlags.Never */)) { - return assignableType; - } + if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { + return candidate; } - // If the candidate type is a subtype of the target type, narrow to the candidate type. - // Otherwise, if the target type is assignable to the candidate type, keep the target type. - // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate - // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the - // two types. - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); + // We first attempt to filter the current type, narrowing constituents as appropriate and removing + // constituents that are unrelated to the candidate. + var keyPropertyName = type.flags & 1048576 /* TypeFlags.Union */ ? getKeyPropertyName(type) : undefined; + var narrowedType = mapType(candidate, function (c) { + // If a discriminant property is available, use that to reduce the type. + var discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName); + var matching = discriminant && getConstituentTypeForKeyType(type, discriminant); + // For each constituent t in the current type, if t and and c are directly related, pick the most + // specific of the two. When t and c are related in both directions, we prefer c for type predicates + // because that is the asserted type, but t for `instanceof` because generics aren't reflected in + // prototype object types. + var directlyRelated = mapType(matching || type, checkDerived ? + function (t) { return isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType; } : + function (t) { return isTypeSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : neverType; }); + // If no constituents are directly related, create intersections for any generic constituents that + // are related by constraint. + return directlyRelated.flags & 131072 /* TypeFlags.Never */ ? + mapType(type, function (t) { return maybeTypeOfKind(t, 465829888 /* TypeFlags.Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType; }) : + directlyRelated; + }); + // If filtering produced a non-empty type, return that. Otherwise, pick the most specific of the two + // based on assignability, or as a last resort produce an intersection. + return !(narrowedType.flags & 131072 /* TypeFlags.Never */) ? narrowedType : + isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -71282,15 +72252,15 @@ var ts; var predicateArgument = getTypePredicateArgument(predicate, callExpression); if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + return getNarrowedType(type, predicate.type, assumeTrue, /*checkDerived*/ false); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && !(getTypeFacts(predicate.type) & 65536 /* TypeFacts.EQUndefined */)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(predicateArgument, type); if (access) { - return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); + return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, /*checkDerived*/ false); }); } } } @@ -71343,7 +72313,7 @@ var ts; } function narrowTypeByOptionality(type, expr, assumePresent) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -71429,8 +72399,8 @@ var ts; var annotationIncludesUndefined = strictNullChecks && declaration.kind === 164 /* SyntaxKind.Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 32768 /* TypeFlags.Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* TypeFlags.Undefined */); + getTypeFacts(declaredType) & 16777216 /* TypeFacts.IsUndefined */ && + !(getTypeFacts(checkExpression(declaration.initializer)) & 16777216 /* TypeFacts.IsUndefined */); popTypeResolution(); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* TypeFacts.NEUndefined */) : declaredType; } @@ -71451,7 +72421,9 @@ var ts; !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { - return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); + return type.flags & 2097152 /* TypeFlags.Intersection */ ? + ts.some(type.types, isGenericTypeWithUnionConstraint) : + !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); } function isGenericTypeWithoutNullableConstraint(type) { return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* TypeFlags.Nullable */)); @@ -71465,7 +72437,7 @@ var ts; !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 64 /* CheckMode.RestBindingElement */ ? getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) - : getContextualType(node)); + : getContextualType(node, /*contextFlags*/ undefined)); return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { @@ -71479,7 +72451,7 @@ var ts; var substituteConstraints = !(checkMode && checkMode & 2 /* CheckMode.Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); - return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* TypeFlags.Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (n) { @@ -71627,9 +72599,7 @@ var ts; getNodeLinks(container).flags |= 8192 /* NodeCheckFlags.CaptureArguments */; return getTypeOfSymbol(symbol); } - // We should only mark aliases as referenced if there isn't a local value declaration - // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that - if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + if (shouldMarkIdentifierAliasReferenced(node)) { markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); @@ -71756,13 +72726,32 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function shouldMarkIdentifierAliasReferenced(node) { + var _a; + var parent = node.parent; + if (parent) { + // A property access expression LHS? checkPropertyAccessExpression will handle that. + if (ts.isPropertyAccessExpression(parent) && parent.expression === node) { + return false; + } + // Next two check for an identifier inside a type only export. + if (ts.isExportSpecifier(parent) && parent.isTypeOnly) { + return false; + } + var greatGrandparent = (_a = parent.parent) === null || _a === void 0 ? void 0 : _a.parent; + if (greatGrandparent && ts.isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) { + return false; + } + } + return true; + } function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } @@ -71890,7 +72879,7 @@ var ts; } function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) { if (ts.isPropertyDeclaration(container) && ts.hasStaticModifier(container) && - container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.length(container.parent.decorators)) { + container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.hasDecorators(container.parent)) { error(thisExpression, ts.Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); } } @@ -72312,7 +73301,7 @@ var ts; // We have an object literal method. Check if the containing object literal has a contextual type // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in // any directly enclosing object literals. - var contextualType = getApparentTypeOfContextualType(containingLiteral); + var contextualType = getApparentTypeOfContextualType(containingLiteral, /*contextFlags*/ undefined); var literal = containingLiteral; var type = contextualType; while (type) { @@ -72324,7 +73313,7 @@ var ts; break; } literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); + type = getApparentTypeOfContextualType(literal, /*contextFlags*/ undefined); } // There was no contextual ThisType for the containing object literal, so the contextual type // for 'this' is the non-null form of the contextual type for the containing object literal or @@ -72381,7 +73370,7 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } - function getContextualTypeForVariableLikeDeclaration(declaration) { + function getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -72390,18 +73379,18 @@ var ts; case 164 /* SyntaxKind.Parameter */: return getContextuallyTypedParameterType(declaration); case 203 /* SyntaxKind.BindingElement */: - return getContextualTypeForBindingElement(declaration); + return getContextualTypeForBindingElement(declaration, contextFlags); case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isStatic(declaration)) { - return getContextualTypeForStaticPropertyDeclaration(declaration); + return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); } // By default, do nothing and return undefined - only the above cases have context implied by a parent } } - function getContextualTypeForBindingElement(declaration) { + function getContextualTypeForBindingElement(declaration, contextFlags) { var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - var parentType = getContextualTypeForVariableLikeDeclaration(parent) || + var parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== 203 /* SyntaxKind.BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 64 /* CheckMode.RestBindingElement */ : 0 /* CheckMode.Normal */); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; @@ -72417,8 +73406,8 @@ var ts; return getTypeOfPropertyOfType(parentType, text); } } - function getContextualTypeForStaticPropertyDeclaration(declaration) { - var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent); + function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) { + var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags); if (!parentType) return undefined; return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName); @@ -72434,29 +73423,32 @@ var ts; function getContextualTypeForInitializerExpression(node, contextFlags) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var result = getContextualTypeForVariableLikeDeclaration(declaration); + var result = getContextualTypeForVariableLikeDeclaration(declaration, contextFlags); if (result) { return result; } - if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable + if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name) && declaration.name.elements.length > 0) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } } return undefined; } - function getContextualTypeForReturnExpression(node) { + function getContextualTypeForReturnExpression(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { var functionFlags = ts.getFunctionFlags(func); if (functionFlags & 1 /* FunctionFlags.Generator */) { // Generator or AsyncGenerator function - var use = functionFlags & 2 /* FunctionFlags.Async */ ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; - var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined); - if (!iterationTypes) { + var isAsyncGenerator_1 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_1); }); + } + var iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + if (!iterationReturnType) { return undefined; } - contextualReturnType = iterationTypes.returnType; + contextualReturnType = iterationReturnType; // falls through to unwrap Promise for AsyncGenerators } if (functionFlags & 2 /* FunctionFlags.Async */) { // Async function or AsyncGenerator function @@ -72477,15 +73469,19 @@ var ts; } return undefined; } - function getContextualTypeForYieldOperand(node) { + function getContextualTypeForYieldOperand(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { + var isAsyncGenerator_2 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_2); }); + } return node.asteriskToken ? contextualReturnType - : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, isAsyncGenerator_2); } } return undefined; @@ -72505,14 +73501,14 @@ var ts; } function getContextualIterationType(kind, functionDecl) { var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* FunctionFlags.Async */); - var contextualReturnType = getContextualReturnType(functionDecl); + var contextualReturnType = getContextualReturnType(functionDecl, /*contextFlags*/ undefined); if (contextualReturnType) { return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || undefined; } return undefined; } - function getContextualReturnType(functionDecl) { + function getContextualReturnType(functionDecl, contextFlags) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed var returnType = getReturnTypeFromAnnotation(functionDecl); @@ -72527,7 +73523,7 @@ var ts; } var iife = ts.getImmediatelyInvokedFunctionExpression(functionDecl); if (iife) { - return getContextualType(iife); + return getContextualType(iife, contextFlags); } return undefined; } @@ -72601,6 +73597,14 @@ var ts; var lhsType = getTypeOfExpression(e.expression); return ts.isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText); } + if (ts.isElementAccessExpression(e)) { + var propType = checkExpressionCached(e.argumentExpression); + if (!isTypeUsableAsPropertyName(propType)) { + return undefined; + } + var lhsType = getTypeOfExpression(e.expression); + return getPropertyOfType(lhsType, getPropertyNameFromType(propType)); + } return undefined; function tryGetPrivateIdentifierPropertyOfType(type, id) { var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id); @@ -72622,7 +73626,7 @@ var ts; if (decl && (ts.isPropertyDeclaration(decl) || ts.isPropertySignature(decl))) { var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); return (overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper)) || - (decl.initializer && getTypeOfExpression(binaryExpression.left)); + (ts.isPropertyDeclaration(decl) ? decl.initializer && getTypeOfExpression(binaryExpression.left) : undefined); } if (kind === 0 /* AssignmentDeclarationKind.None */) { return getTypeOfExpression(binaryExpression.left); @@ -72755,7 +73759,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; - var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element, contextFlags); if (propertyAssignmentType) { return propertyAssignmentType; } @@ -72790,8 +73794,8 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined; } - function getContextualTypeForChildJsxExpression(node, child) { - var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + function getContextualTypeForChildJsxExpression(node, child, contextFlags) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); // JSX expression is in children of JSX Element, we will look for an "children" attribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { @@ -72809,27 +73813,27 @@ var ts; } }, /*noReductions*/ true)); } - function getContextualTypeForJsxExpression(node) { + function getContextualTypeForJsxExpression(node, contextFlags) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) - ? getContextualType(node) + ? getContextualType(node, contextFlags) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent, node) + ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) : undefined; } - function getContextualTypeForJsxAttribute(attribute) { + function getContextualTypeForJsxAttribute(attribute, contextFlags) { // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName if (ts.isJsxAttribute(attribute)) { - var attributesType = getApparentTypeOfContextualType(attribute.parent); + var attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return getContextualType(attribute.parent); + return getContextualType(attribute.parent, contextFlags); } } // Return true if the given expression is possibly a discriminant value. We limit the kinds of @@ -72882,22 +73886,20 @@ var ts; 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 && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { // 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. - if (contextFlags && contextFlags & 1 /* ContextFlags.Signature */) { - return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); - } + return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); + } + if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.returnMapper) { // For other purposes (e.g. determining whether to produce literal types) we only // incorporate inferences made from the return type in a function call. We remove // the 'boolean' type from the contextual type such that contextually typed boolean // literals actually end up widening to 'boolean' (see #48363). - if (inferenceContext.returnMapper) { - var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); - return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? - filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : - type; - } + var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); + return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? + filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : + type; } } return contextualType; @@ -72952,9 +73954,9 @@ var ts; return getContextualTypeForInitializerExpression(node, contextFlags); case 214 /* SyntaxKind.ArrowFunction */: case 247 /* SyntaxKind.ReturnStatement */: - return getContextualTypeForReturnExpression(node); + return getContextualTypeForReturnExpression(node, contextFlags); case 224 /* SyntaxKind.YieldExpression */: - return getContextualTypeForYieldOperand(parent); + return getContextualTypeForYieldOperand(parent, contextFlags); case 218 /* SyntaxKind.AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); case 208 /* SyntaxKind.CallExpression */: @@ -72992,17 +73994,17 @@ var ts; case 271 /* SyntaxKind.ExportAssignment */: return tryGetTypeFromEffectiveTypeNode(parent); case 288 /* SyntaxKind.JsxExpression */: - return getContextualTypeForJsxExpression(parent); + return getContextualTypeForJsxExpression(parent, contextFlags); case 285 /* SyntaxKind.JsxAttribute */: case 287 /* SyntaxKind.JsxSpreadAttribute */: - return getContextualTypeForJsxAttribute(parent); + return getContextualTypeForJsxAttribute(parent, contextFlags); case 280 /* SyntaxKind.JsxOpeningElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; function tryFindWhenConstTypeReference(node) { - return getContextualType(node); + return getContextualType(node, contextFlags); } } function getInferenceContext(node) { @@ -73262,8 +74264,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var current = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var current = types_18[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -73304,7 +74306,7 @@ var ts; var elementCount = elements.length; var elementTypes = []; var elementFlags = []; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var inDestructuringPattern = ts.isAssignmentTarget(node); var inConstContext = isConstContext(node); var hasOmittedExpression = false; @@ -73475,7 +74477,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 201 /* SyntaxKind.ObjectBindingPattern */ || contextualType.pattern.kind === 205 /* SyntaxKind.ObjectLiteralExpression */); var inConstContext = isConstContext(node); @@ -73814,7 +74816,7 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes, /*contextFlags*/ undefined); var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* SymbolFlags.Property */, jsxChildrenPropertyName); @@ -74425,19 +75427,19 @@ var ts; return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { - return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */); + return !!(getTypeFacts(type) & 50331648 /* TypeFacts.IsUndefinedOrNull */); } function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function reportObjectPossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportObjectPossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); } - function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); @@ -74447,9 +75449,9 @@ var ts; error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */; - if (kind) { - reportError(node, kind); + var facts = getTypeFacts(type); + if (facts & 50331648 /* TypeFacts.IsUndefinedOrNull */) { + reportError(node, facts); var t = getNonNullableType(type); return t.flags & (98304 /* TypeFlags.Nullable */ | 131072 /* TypeFlags.Never */) ? errorType : t; } @@ -74618,9 +75620,8 @@ var ts; markAliasReferenced(parentSymbol, node); } return isErrorType(apparentType) ? errorType : apparentType; - ; } - prop = getPropertyOfType(apparentType, right.escapedText); + prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ node.kind === 161 /* SyntaxKind.QualifiedName */); } // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. // `Foo` is also not referenced in `enum FooCopy { Bar = Foo.Bar }`, because the enum member value gets inlined @@ -74745,7 +75746,7 @@ var ts; assumeUninitialized = true; } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) { error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -74928,9 +75929,9 @@ var ts; function getSuggestedSymbolForNonexistentProperty(name, containingType) { var props = getPropertiesOfType(containingType); if (typeof name !== "string") { - var parent_2 = name.parent; - if (ts.isPropertyAccessExpression(parent_2)) { - props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + var parent_3 = name.parent; + if (ts.isPropertyAccessExpression(parent_3)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_3, containingType, prop); }); } name = ts.idText(name); } @@ -75432,29 +76433,43 @@ var ts; // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. if (node.kind !== 165 /* SyntaxKind.Decorator */) { - var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); + var skipBindingPatterns = ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }); + var contextualType = getContextualType(node, skipBindingPatterns ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); if (contextualType) { var inferenceTargetType = getReturnTypeOfSignature(signature); if (couldContainTypeVariables(inferenceTargetType)) { - // We clone the inference context to avoid disturbing a resolution in progress for an - // outer call expression. Effectively we just want a snapshot of whatever has been - // inferred for any outer call expression so far. var outerContext = getInferenceContext(node); - var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); - var instantiatedType = instantiateType(contextualType, outerMapper); - // If the contextual type is a generic function type with a single call signature, we - // instantiate the type with its own type parameters and type arguments. This ensures that - // the type parameters are not erased to type any during type inference such that they can - // be inferred as actual types from the contextual type. For example: - // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; - // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); - // Above, the type of the 'value' parameter is inferred to be 'A'. - var contextualSignature = getSingleCallSignature(instantiatedType); - var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : - instantiatedType; - // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + var isFromBindingPattern = !skipBindingPatterns && getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) !== contextualType; + // A return type inference from a binding pattern can be used in instantiating the contextual + // type of an argument later in inference, but cannot stand on its own as the final return type. + // It is incorporated into `context.returnMapper` which is used in `instantiateContextualType`, + // but doesn't need to go into `context.inferences`. This allows a an array binding pattern to + // produce a tuple for `T` in + // declare function f(cb: () => T): T; + // const [e1, e2, e3] = f(() => [1, "hi", true]); + // but does not produce any inference for `T` in + // declare function f(): T; + // const [e1, e2, e3] = f(); + if (!isFromBindingPattern) { + // We clone the inference context to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); + var instantiatedType = instantiateType(contextualType, outerMapper); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + } // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -75781,7 +76796,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_24 = 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 === 225 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -75798,7 +76813,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_24(i); + _loop_26(i); } return effectiveArgs_1; } @@ -76005,7 +77020,7 @@ var ts; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray; var typeArguments; - if (!isDecorator) { + if (!isDecorator && !ts.isSuperCall(node)) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 106 /* SyntaxKind.SuperKeyword */) { @@ -76084,6 +77099,15 @@ var ts; if (result) { return result; } + result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + // Preemptively cache the result; getResolvedSignature will do this after we return, but + // we need to ensure that the result is present for the error checks below so that if + // this signature is encountered again, we handle the circularity (rather than producing a + // different result which may produce no errors and assert). Callers of getResolvedSignature + // don't hit this issue because they only observe this result after it's had a chance to + // be cached, but the error reporting code below executes before getResolvedSignature sets + // resolvedSignature. + getNodeLinks(node).resolvedSignature = result; // No signatures were applicable. Now report errors based on the last applicable signature with // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, @@ -76118,7 +77142,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_25 = 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) { @@ -76136,7 +77160,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_25(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"); @@ -76175,7 +77199,7 @@ var ts; } } } - return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + return result; function addImplementationSuccessElaboration(failed, diagnostic) { var _a, _b; var oldCandidatesForArgumentError = candidatesForArgumentError; @@ -76255,7 +77279,7 @@ var ts; argCheckMode = checkMode & 32 /* CheckMode.IsForStringLiteralArgumentCompletions */; if (inferenceContext) { var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -76294,7 +77318,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_26 = 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; }); @@ -76302,7 +77326,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_26(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -76470,7 +77494,7 @@ var ts; // returns a function type, we choose to defer processing. This narrowly permits function composition // operators to flow inferences through return types, but otherwise processes calls right away. We // use the resolvingSignature singleton to indicate that we deferred processing. This result will be - // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and + // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and // from which we never make inferences). if (checkMode & 8 /* CheckMode.SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) { skippedGenericFunction(node, checkMode); @@ -76647,8 +77671,8 @@ var ts; if (apparentType.flags & 1048576 /* TypeFlags.Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var constituent = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var constituent = types_19[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -76814,7 +77838,7 @@ var ts; // file would probably be preferable. var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* SymbolFlags.Type */); var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* SymbolFlags.Type */, node); - var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); var parameterSymbol = createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, "props"); parameterSymbol.type = result; return createSignature(declaration, @@ -77023,8 +78047,8 @@ var ts; var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode); if (signature === resolvingSignature) { // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that - // returns a function type. We defer checking and return nonInferrableType. - return nonInferrableType; + // returns a function type. We defer checking and return silentNeverType. + return silentNeverType; } checkDeprecatedSignature(signature, node); if (node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { @@ -77632,17 +78656,6 @@ var ts; } } } - var restType = getEffectiveRestType(context); - if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { - // The contextual signature has a generic rest parameter. We first instantiate the contextual - // signature (without fixing type parameters) and assign types to contextually typed parameters. - var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper); - assignContextualParameterTypes(signature, instantiatedContext); - // We then infer from a tuple type representing the parameters that correspond to the contextual - // rest parameter. - var restPos = getParameterCount(context) - 1; - inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType); - } } function assignContextualParameterTypes(signature, context) { if (context.typeParameters) { @@ -77835,7 +78848,7 @@ var ts; var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : - instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); + instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func, /*contextFlags*/ undefined); if (isGenerator) { yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* IterationTypeKind.Yield */, isAsync); returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* IterationTypeKind.Return */, isAsync); @@ -77906,7 +78919,7 @@ var ts; nextType = iterationTypes && iterationTypes.nextType; } else { - nextType = getContextualType(yieldExpression); + nextType = getContextualType(yieldExpression, /*contextFlags*/ undefined); } if (nextType) ts.pushIfUnique(nextTypes, nextType); @@ -77921,45 +78934,12 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - /** - * Collect the TypeFacts learned from a typeof switch with - * total clauses `witnesses`, and the active clause ranging - * from `start` to `end`. Parameter `hasDefault` denotes - * whether the active clause contains a default clause. - */ - function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + // Return the combined not-equal type facts for all cases except those between the start and end indices. + function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) { var facts = 0 /* TypeFacts.None */; - // When in the default we only collect inequality facts - // because default is 'in theory' a set of infinite - // equalities. - if (hasDefault) { - // Value is not equal to any types after the active clause. - for (var i = end; i < witnesses.length; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - // Remove inequalities for types that appear in the - // active clause because they appear before other - // types collected so far. - for (var i = start; i < end; i++) { - facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); - } - // Add inequalities for types before the active clause unconditionally. - for (var i = 0; i < start; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - } - // When in an active clause without default the set of - // equalities is finite. - else { - // Add equalities for all types in the active clause. - for (var i = start; i < end; i++) { - facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeFacts.TypeofEQHostObject */; - } - // Remove equalities for types that appear before the - // active clause. - for (var i = 0; i < start; i++) { - facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); - } + for (var i = 0; i < witnesses.length; i++) { + var witness = i < start || i >= end ? witnesses[i] : undefined; + facts |= witness !== undefined ? typeofNEFacts.get(witness) || 32768 /* TypeFacts.TypeofNEHostObject */ : 0; } return facts; } @@ -77969,16 +78949,19 @@ var ts; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 216 /* SyntaxKind.TypeOfExpression */) { - var operandType = getTypeOfExpression(node.expression.expression); - var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); - // notEqualFacts states that the type of the switched value is not equal to every type in the switch. - var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_6 = getBaseConstraintOfType(operandType) || operandType; - // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_6.flags & 3 /* TypeFlags.AnyOrUnknown */) { - return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_1) === 556800 /* TypeFacts.AllTypeofNE */; + var witnesses = getSwitchClauseTypeOfWitnesses(node); + if (!witnesses) { + return false; } - return !!(filterType(type_6, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* TypeFlags.Never */); + var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(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 */) { + // We special case the top types to be exhaustive when all cases are handled. + return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_2) === 556800 /* TypeFacts.AllTypeofNE */; + } + // 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); if (!isLiteralType(type)) { @@ -78145,11 +79128,16 @@ var ts; if (isContextSensitive(node)) { if (contextualSignature) { var inferenceContext = getInferenceContext(node); + var instantiatedContextualSignature = void 0; if (checkMode && checkMode & 2 /* CheckMode.Inferential */) { inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); + var restType = getEffectiveRestType(contextualSignature); + if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { + instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper); + } } - var instantiatedContextualSignature = inferenceContext ? - instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature; + instantiatedContextualSignature || (instantiatedContextualSignature = inferenceContext ? + instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature); assignContextualParameterTypes(signature, instantiatedContextualSignature); } else { @@ -78339,7 +79327,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks && !(type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 131072 /* TypeFlags.Never */)) && - !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getTypeFacts(type) & 16777216 /* TypeFacts.IsUndefined */)) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); } } @@ -78448,7 +79436,7 @@ var ts; error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } if (node.operator === 39 /* SyntaxKind.PlusToken */) { - if (maybeTypeOfKind(operandType, 2112 /* TypeFlags.BigIntLike */)) { + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* TypeFlags.BigIntLike */)) { error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType))); } return numberType; @@ -78507,8 +79495,8 @@ var ts; } if (type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { - var t = types_21[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var t = types_20[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -78735,7 +79723,7 @@ var ts; // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* TypeFlags.Undefined */)) { + !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & 16777216 /* TypeFacts.IsUndefined */)) { sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -78748,6 +79736,10 @@ var ts; if (target.kind === 221 /* SyntaxKind.BinaryExpression */ && target.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; + // A default value is specified, so remove undefined from the final type. + if (strictNullChecks) { + sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); + } } if (target.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); @@ -78888,7 +79880,11 @@ var ts; var operator = operatorToken.kind; if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */ || operator === 56 /* SyntaxKind.BarBarToken */ || operator === 60 /* SyntaxKind.QuestionQuestionToken */) { if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); + var parent = node.parent; + while (parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */ + || ts.isBinaryExpression(parent) && (parent.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ || parent.operatorToken.kind === 56 /* SyntaxKind.BarBarToken */)) { + parent = parent.parent; + } checkTestingKnownTruthyCallableOrAwaitableType(node.left, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } checkTruthinessOfType(leftType, node.left); @@ -79112,6 +80108,10 @@ var ts; case 35 /* SyntaxKind.ExclamationEqualsToken */: case 36 /* SyntaxKind.EqualsEqualsEqualsToken */: case 37 /* SyntaxKind.ExclamationEqualsEqualsToken */: + if (ts.isLiteralExpressionOfObject(left) || ts.isLiteralExpressionOfObject(right)) { + var eqType = operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */; + error(errorNode, ts.Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); + } reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); }); return booleanType; case 102 /* SyntaxKind.InstanceOfKeyword */: @@ -79131,7 +80131,7 @@ var ts; case 56 /* SyntaxKind.BarBarToken */: case 75 /* SyntaxKind.BarBarEqualsToken */: { var resultType_3 = getTypeFacts(leftType) & 8388608 /* TypeFacts.Falsy */ ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* UnionReduction.Subtype */) : + getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* UnionReduction.Subtype */) : leftType; if (operator === 75 /* SyntaxKind.BarBarEqualsToken */) { checkAssignmentOperator(rightType); @@ -79383,7 +80383,7 @@ var ts; type = anyType; addLazyDiagnostic(function () { if (noImplicitAny && !ts.expressionResultIsUnused(node)) { - var contextualType = getContextualType(node); + var contextualType = getContextualType(node, /*contextFlags*/ undefined); if (!contextualType || isTypeAny(contextualType)) { error(node, ts.Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); } @@ -79424,7 +80424,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node, /*contextFlags*/ undefined) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; } function isTemplateLiteralContextualType(type) { return !!(type.flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */) || @@ -79452,7 +80452,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node, /*contextFlags*/ undefined)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -79567,7 +80567,7 @@ var ts; var type = checkExpression(node, checkMode, forceTuple); return isConstContext(node) || ts.isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : - getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node)); + getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node, /*contextFlags*/ undefined) : contextualType, node, /*contextFlags*/ undefined)); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. @@ -79677,8 +80677,8 @@ var ts; var result = []; var oldTypeParameters; var newTypeParameters; - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var tp = typeParameters_2[_i]; + for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { + var tp = typeParameters_3[_i]; var name = tp.symbol.escapedName; if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) { var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name); @@ -80000,12 +81000,14 @@ var ts; error(node, ts.Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); } else if (modifiers === 32768 /* ModifierFlags.In */ || modifiers === 65536 /* ModifierFlags.Out */) { - var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubType : markerSuperType); - var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperType : markerSubType); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); + var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck); + var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck); var saveVarianceTypeParameter = typeParameter; varianceTypeParameter = typeParameter; checkTypeAssignableTo(source, target, node, ts.Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation); varianceTypeParameter = saveVarianceTypeParameter; + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } } @@ -80026,7 +81028,7 @@ var ts; error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + if ((node.questionToken || isJSDocOptionalParameter(node)) && ts.isBindingPattern(node.name) && func.body) { error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { @@ -80355,7 +81357,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_27 = 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)); @@ -80370,7 +81372,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_27(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -80403,6 +81405,9 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); + if (ts.isMethodDeclaration(node) && node.asteriskToken && ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_a_generator); + } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // method signatures already report "implementation not allowed in ambient context" elsewhere @@ -80530,6 +81535,9 @@ var ts; return !!ts.forEachChild(node, nodeImmediatelyReferencesSuperOrThis); } function checkAccessorDeclaration(node) { + if (ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_an_accessor); + } addLazyDiagnostic(checkAccessorDeclarationDiagnostics); checkSourceElement(node.body); setNodeLinksForPrivateIdentifierScope(node); @@ -80587,6 +81595,12 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) { + if (index < typeParameters.length) { + return getTypeFromTypeNode(node.typeArguments[index]); + } + return getEffectiveTypeArguments(node, typeParameters)[index]; + } function getEffectiveTypeArguments(node, typeParameters) { return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } @@ -80828,8 +81842,11 @@ var ts; if (node.assertions) { var override = ts.getResolutionModeOverrideForClause(node.assertions.assertClause, grammarErrorOnNode); if (override) { + if (!ts.isNightly()) { + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } } } @@ -81214,7 +82231,7 @@ var ts; * @param type The type of the promise. * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. */ - function getPromisedTypeOfPromise(type, errorNode) { + function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) { // // { // type // then( // thenFunction @@ -81249,7 +82266,29 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); + var thisTypeForError; + var candidates; + for (var _i = 0, thenSignatures_1 = thenSignatures; _i < thenSignatures_1.length; _i++) { + var thenSignature = thenSignatures_1[_i]; + var thisType = getThisTypeOfSignature(thenSignature); + if (thisType && thisType !== voidType && !isTypeRelatedTo(type, thisType, subtypeRelation)) { + thisTypeForError = thisType; + } + else { + candidates = ts.append(candidates, thenSignature); + } + } + if (!candidates) { + ts.Debug.assertIsDefined(thisTypeForError); + if (thisTypeForErrorOut) { + thisTypeForErrorOut.value = thisTypeForError; + } + if (errorNode) { + error(errorNode, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError)); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(candidates, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -81303,6 +82342,34 @@ var ts; isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : type; } + function isAwaitedTypeNeeded(type) { + // If this is already an `Awaited`, we shouldn't wrap it. This helps to avoid `Awaited>` in higher-order. + if (isTypeAny(type) || isAwaitedTypeInstantiation(type)) { + return false; + } + // We only need `Awaited` if `T` contains possibly non-primitive types. + if (isGenericObjectType(type)) { + var baseConstraint = getBaseConstraintOfType(type); + // 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) : + maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { + return true; + } + } + return false; + } + function tryCreateAwaitedType(type) { + // Nothing to do if `Awaited` doesn't exist + var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); + if (awaitedSymbol) { + // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where + // an `Awaited` would suffice. + return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); + } + return undefined; + } function createAwaitedTypeIfNeeded(type) { // We wrap type `T` in `Awaited` based on the following conditions: // - `T` is not already an `Awaited`, and @@ -81311,26 +82378,10 @@ var ts; // - `T` has no base constraint, or // - The base constraint of `T` is `any`, `unknown`, `object`, or `{}`, or // - The base constraint of `T` is an object type with a callable `then` method. - if (isTypeAny(type)) { - return type; - } - // If this is already an `Awaited`, just return it. This helps to avoid `Awaited>` in higher-order. - if (isAwaitedTypeInstantiation(type)) { - return type; - } - // Only instantiate `Awaited` if `T` contains possibly non-primitive types. - if (isGenericObjectType(type)) { - var baseConstraint = getBaseConstraintOfType(type); - // Only instantiate `Awaited` if `T` 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)) { - // Nothing to do if `Awaited` doesn't exist - var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); - if (awaitedSymbol) { - // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where - // an `Awaited` would suffice. - return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); - } + if (isAwaitedTypeNeeded(type)) { + var awaitedType = tryCreateAwaitedType(type); + if (awaitedType) { + return awaitedType; } } ts.Debug.assert(getPromisedTypeOfPromise(type) === undefined, "type provided should not be a non-generic 'promise'-like."); @@ -81370,10 +82421,24 @@ var ts; } // For a union, get a union of the awaited types of each constituent. if (type.flags & 1048576 /* TypeFlags.Union */) { + if (awaitedTypeStack.lastIndexOf(type.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } var mapper = errorNode ? function (constituentType) { return getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeNoAlias; - return typeAsAwaitable.awaitedTypeOfType = mapType(type, mapper); + awaitedTypeStack.push(type.id); + var mapped = mapType(type, mapper); + awaitedTypeStack.pop(); + return typeAsAwaitable.awaitedTypeOfType = mapped; + } + // If `type` is generic and should be wrapped in `Awaited`, return it. + if (isAwaitedTypeNeeded(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; } - var promisedType = getPromisedTypeOfPromise(type); + var thisTypeForErrorOut = { value: undefined }; + var promisedType = getPromisedTypeOfPromise(type, /*errorNode*/ undefined, thisTypeForErrorOut); if (promisedType) { if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose @@ -81442,7 +82507,12 @@ var ts; if (isThenableType(type)) { if (errorNode) { ts.Debug.assertIsDefined(diagnosticMessage); - error(errorNode, diagnosticMessage, arg0); + var chain = void 0; + if (thisTypeForErrorOut.value) { + chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value)); + } + chain = ts.chainDiagnosticMessages(chain, diagnosticMessage, arg0); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, chain)); } return undefined; } @@ -81638,8 +82708,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { - var typeNode = types_22[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */ || typeNode.kind === 197 /* SyntaxKind.NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } @@ -81679,18 +82749,18 @@ var ts; } /** Check the decorators of a node */ function checkDecorators(node) { - if (!node.decorators) { - return; - } // skip this check for nodes that cannot have decorators. These should have already had an error reported by // checkGrammarDecorators. - if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node) || !node.modifiers || !ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning); } - var firstDecorator = node.decorators[0]; + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (!firstDecorator) { + return; + } checkExternalEmitHelpers(firstDecorator, 8 /* ExternalEmitHelpers.Decorate */); if (node.kind === 164 /* SyntaxKind.Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* ExternalEmitHelpers.Param */); @@ -81734,7 +82804,12 @@ var ts; break; } } - ts.forEach(node.decorators, checkDecorator); + for (var _f = 0, _g = node.modifiers; _f < _g.length; _f++) { + var modifier = _g[_f]; + if (ts.isDecorator(modifier)) { + checkDecorator(modifier); + } + } } function checkFunctionDeclaration(node) { addLazyDiagnostic(checkFunctionDeclarationDiagnostics); @@ -81765,6 +82840,11 @@ var ts; function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } + function checkJSDocLinkLikeTag(node) { + if (node.name) { + resolveJSDocMemberName(node.name, /*ignoreErrors*/ true); + } + } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); } @@ -82004,8 +83084,8 @@ var ts; return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); - for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { - var typeParameter = typeParameters_3[_i]; + for (var _i = 0, typeParameters_4 = typeParameters; _i < typeParameters_4.length; _i++) { + var typeParameter = typeParameters_4[_i]; if (!isTypeParameterUnused(typeParameter)) continue; var name = ts.idText(typeParameter.name); @@ -82165,6 +83245,22 @@ var ts; } }); } + function checkPotentialUncheckedRenamedBindingElementsInTypes() { + var _a; + for (var _i = 0, potentialUnusedRenamedBindingElementsInTypes_1 = potentialUnusedRenamedBindingElementsInTypes; _i < potentialUnusedRenamedBindingElementsInTypes_1.length; _i++) { + var node = potentialUnusedRenamedBindingElementsInTypes_1[_i]; + if (!((_a = getSymbolOfNode(node)) === null || _a === void 0 ? void 0 : _a.isReferenced)) { + var wrappingDeclaration = ts.walkUpBindingElementsAndPatterns(node); + ts.Debug.assert(ts.isParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here"); + var diagnostic = ts.createDiagnosticForNode(node.name, ts.Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, ts.declarationNameToString(node.name), ts.declarationNameToString(node.propertyName)); + if (!wrappingDeclaration.type) { + // entire parameter does not have type annotation, suggest adding an annotation + ts.addRelatedInfo(diagnostic, ts.createFileDiagnostic(ts.getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, ts.Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, ts.declarationNameToString(node.propertyName))); + } + diagnostics.add(diagnostic); + } + } + } function bindingNameText(name) { switch (name.kind) { case 79 /* SyntaxKind.Identifier */: @@ -82461,11 +83557,22 @@ var ts; // well known symbols. if (node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.name); - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkExpressionCached(node.initializer); } } if (ts.isBindingElement(node)) { + if (node.propertyName && + ts.isIdentifier(node.name) && + ts.isParameterDeclaration(node) && + ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + // type F = ({a: string}) => void; + // ^^^^^^ + // variable renaming in function type notation is confusing, + // so we forbid it even if noUnusedLocals is not enabled + potentialUnusedRenamedBindingElementsInTypes.push(node); + return; + } if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ScriptTarget.ES2018 */) { checkExternalEmitHelpers(node, 4 /* ExternalEmitHelpers.Rest */); } @@ -82498,14 +83605,14 @@ var ts; ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (ts.isParameter(node) && node.initializer && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; - var needCheckWidenedType = node.name.elements.length === 0; + var needCheckInitializer = ts.hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; + var needCheckWidenedType = !ts.some(node.name.elements, ts.not(ts.isOmittedExpression)); if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error var widenedType = getWidenedTypeForVariableLikeDeclaration(node); @@ -82532,7 +83639,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.kind === 203 /* SyntaxKind.BindingElement */ ? node.parent.parent : node)) { checkAliasSymbol(node); return; } @@ -82540,7 +83647,7 @@ var ts; if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - var initializer = ts.getEffectiveInitializer(node); + var initializer = ts.hasOnlyExpressionInitializer(node) && ts.getEffectiveInitializer(node); if (initializer) { var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && @@ -82565,7 +83672,7 @@ var ts; !(symbol.flags & 67108864 /* SymbolFlags.Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); } - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { @@ -82658,7 +83765,7 @@ var ts; return; var type = checkTruthinessExpression(location); var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) && isTypeAssertion(location.expression); - if (getFalsyFlags(type) || isPropertyExpressionCast) + if (!(getTypeFacts(type) & 4194304 /* TypeFacts.Truthy */) || isPropertyExpressionCast) return; // While it technically should be invalid for any known-truthy value // to be tested, we de-scope to functions and Promises unreferenced in @@ -83124,17 +84231,28 @@ var ts; * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. */ function getIterationTypesOfIterable(type, use, errorNode) { + var _a, _b; if (isTypeAny(type)) { return anyIterationTypes; } if (!(type.flags & 1048576 /* TypeFlags.Union */)) { - var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode); + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); if (iterationTypes_1 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } return undefined; } + else if ((_a = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _a === void 0 ? void 0 : _a.length) { + for (var _i = 0, _c = errorOutputContainer.errors; _i < _c.length; _i++) { + var diag = _c[_i]; + diagnostics.add(diag); + } + } return iterationTypes_1; } var cacheKey = use & 2 /* IterationUse.AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; @@ -83142,19 +84260,27 @@ var ts; if (cachedTypes) return cachedTypes === noIterationTypes ? undefined : cachedTypes; var allIterationTypes; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituent = _a[_i]; - var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode); + for (var _d = 0, _e = type.types; _d < _e.length; _d++) { + var constituent = _e[_d]; + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer); if (iterationTypes_2 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } setCachedIterationTypes(type, cacheKey, noIterationTypes); return undefined; } - else { - allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); + else if ((_b = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _b === void 0 ? void 0 : _b.length) { + for (var _f = 0, _g = errorOutputContainer.errors; _f < _g.length; _f++) { + var diag = _g[_f]; + diagnostics.add(diag); + } } + allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); } var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes; setCachedIterationTypes(type, cacheKey, iterationTypes); @@ -83182,47 +84308,62 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableWorker(type, use, errorNode) { + function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) { if (isTypeAny(type)) { return anyIterationTypes; } + // If we are reporting errors and encounter a cached `noIterationTypes`, we should ignore the cached value and continue as if nothing was cached. + // In addition, we should not cache any new results for this call. + var noCache = false; if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver); if (iterationTypes) { - return use & 8 /* IterationUse.ForOfFlag */ ? - getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : - iterationTypes; + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; + } + else { + return use & 8 /* IterationUse.ForOfFlag */ ? + getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : + iterationTypes; + } } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver); if (iterationTypes) { - if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - // for a sync iterable in an async context, only use the cached types if they are valid. - if (iterationTypes !== noIterationTypes) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode)); - } + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; } else { - return iterationTypes; + if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { + // for a sync iterable in an async context, only use the cached types if they are valid. + if (iterationTypes !== noIterationTypes) { + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); + } + } + else { + return iterationTypes; + } } } } if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { return iterationTypes; } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes - ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) - : noIterationTypes); + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); } else { return iterationTypes; @@ -83243,7 +84384,7 @@ var ts; } function getIterationTypesOfGlobalIterableType(globalType, resolver) { var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || - getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; } /** @@ -83297,40 +84438,56 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableSlow(type, resolver, errorNode) { + function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var _a; var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* SymbolFlags.Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); + return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); } var signatures = methodType ? getSignaturesOfType(methodType, 0 /* SignatureKind.Call */) : undefined; if (!ts.some(signatures)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); + return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); } var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature)); - var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes; - return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); + var iterationTypes = (_a = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache)) !== null && _a !== void 0 ? _a : noIterationTypes; + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { 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; - errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + } + /** + * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. + * + * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` + * record is returned. Otherwise, `undefined` is returned. + */ + function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { + return getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, /*noCache*/ false); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. * * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, `undefined` is returned. + * + * NOTE: You probably don't want to call this directly and should be calling + * `getIterationTypesOfIterator` instead. */ - function getIterationTypesOfIterator(type, resolver, errorNode) { + function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) { if (isTypeAny(type)) { return anyIterationTypes; } var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || - getIterationTypesOfIteratorFast(type, resolver) || - getIterationTypesOfIteratorSlow(type, resolver, errorNode); + getIterationTypesOfIteratorFast(type, resolver); + if (iterationTypes === noIterationTypes && errorNode) { + iterationTypes = undefined; + noCache = true; + } + iterationTypes !== null && iterationTypes !== void 0 ? iterationTypes : (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache)); return iterationTypes === noIterationTypes ? undefined : iterationTypes; } /** @@ -83368,7 +84525,7 @@ var ts; // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any` // and `undefined` in our libs by default, a custom lib *could* use different definitions. var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || - getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType; return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } @@ -83438,8 +84595,8 @@ var ts; * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, we return `undefined`. */ - function getIterationTypesOfMethod(type, resolver, methodName, errorNode) { - var _a, _b, _c, _d; + function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) { + var _a, _b, _c, _d, _e, _f; var method = getPropertyOfType(type, methodName); // Ignore 'return' or 'throw' if they are missing. if (!method && methodName !== "next") { @@ -83459,9 +84616,15 @@ var ts; var diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic; - error(errorNode, diagnostic, methodName); + if (errorOutputContainer) { + (_a = errorOutputContainer.errors) !== null && _a !== void 0 ? _a : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, diagnostic, methodName)); + } + else { + error(errorNode, diagnostic, methodName); + } } - return methodName === "next" ? anyIterationTypes : undefined; + return methodName === "next" ? noIterationTypes : undefined; } // If the method signature comes exclusively from the global iterator or generator type, // create iteration types from its type arguments like `getIterationTypesOfIteratorFast` @@ -83473,8 +84636,8 @@ var ts; if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) { var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false); var globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false); - var isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) === null || _a === void 0 ? void 0 : _a.members) === null || _b === void 0 ? void 0 : _b.get(methodName)) === methodType.symbol; - var isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) === null || _c === void 0 ? void 0 : _c.members) === null || _d === void 0 ? void 0 : _d.get(methodName)) === methodType.symbol; + var isGeneratorMethod = ((_c = (_b = globalGeneratorType.symbol) === null || _b === void 0 ? void 0 : _b.members) === null || _c === void 0 ? void 0 : _c.get(methodName)) === methodType.symbol; + var isIteratorMethod = !isGeneratorMethod && ((_e = (_d = globalIteratorType.symbol) === null || _d === void 0 ? void 0 : _d.members) === null || _e === void 0 ? void 0 : _e.get(methodName)) === methodType.symbol; if (isGeneratorMethod || isIteratorMethod) { var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType; var mapper = methodType.mapper; @@ -83514,7 +84677,13 @@ var ts; var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType); if (iterationTypes === noIterationTypes) { if (errorNode) { - error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + if (errorOutputContainer) { + (_f = errorOutputContainer.errors) !== null && _f !== void 0 ? _f : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName)); + } + else { + error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + } } yieldType = anyType; returnTypes = ts.append(returnTypes, anyType); @@ -83535,13 +84704,13 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterator` instead. */ - function getIterationTypesOfIteratorSlow(type, resolver, errorNode) { + function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var iterationTypes = combineIterationTypes([ - getIterationTypesOfMethod(type, resolver, "next", errorNode), - getIterationTypesOfMethod(type, resolver, "return", errorNode), - getIterationTypesOfMethod(type, resolver, "throw", errorNode), + getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer), ]); - return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); } /** * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like, @@ -83562,7 +84731,7 @@ var ts; var use = isAsyncGenerator ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) || - getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined); } function checkBreakOrContinueStatement(node) { // Grammar checking @@ -83573,9 +84742,14 @@ var ts; function unwrapReturnType(returnType, functionFlags) { var isGenerator = !!(functionFlags & 1 /* FunctionFlags.Generator */); var isAsync = !!(functionFlags & 2 /* FunctionFlags.Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync) || errorType : - isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : - returnType; + if (isGenerator) { + var returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync); + if (!returnIterationType) { + return errorType; + } + return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType; + } + return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func)); @@ -83795,9 +84969,10 @@ var ts; } var indexInfos = getApplicableIndexInfos(type, propNameType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; - var localPropDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || - name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ || getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_28 = function (info) { + var propDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || + name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; + var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; + 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 @@ -83805,12 +84980,16 @@ var ts; var errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !ts.some(getBaseTypes(type), function (base) { return !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType); }) ? interfaceDeclaration : undefined); if (errorNode && !isTypeAssignableTo(propType, info.type)) { - error(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + var diagnostic = createError(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + if (propDeclaration && errorNode !== propDeclaration) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(propDeclaration, ts.Diagnostics._0_is_declared_here, symbolToString(prop))); + } + diagnostics.add(diagnostic); } }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_28(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -83818,7 +84997,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_29 = 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; @@ -83833,7 +85012,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_29(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -84022,8 +85201,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { - grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (firstDecorator && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(firstDecorator, ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -84152,7 +85332,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_30 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -84169,7 +85349,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_30(member); + _loop_32(member); } } /** @@ -84257,7 +85437,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_31 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -84276,7 +85456,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_31(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -84344,18 +85524,17 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. - var _a, _b; + var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { - continue; + return "continue"; } var baseSymbol = getPropertyOfObjectType(type, base.escapedName); if (!baseSymbol) { - continue; + return "continue"; } var derived = getTargetSymbol(baseSymbol); var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); @@ -84373,14 +85552,14 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { - var otherBaseType = _d[_c]; + for (var _e = 0, _f = getBaseTypes(type); _e < _f.length; _e++) { + var otherBaseType = _f[_e]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1); if (derivedElsewhere && derivedElsewhere !== base) { - continue basePropertyCheck; + return "continue-basePropertyCheck"; } } if (derivedClassDecl.kind === 226 /* SyntaxKind.ClassExpression */) { @@ -84395,20 +85574,19 @@ var ts; // derived overrides base. var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* ModifierFlags.Private */ || derivedDeclarationFlags & 8 /* ModifierFlags.Private */) { - // either base or derived property is private - not override, skip it - continue; + return "continue"; } var errorMessage = void 0; var basePropertyFlags = base.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; var derivedPropertyFlags = derived.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor - if (baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */ + if ((ts.getCheckFlags(base) & 6 /* CheckFlags.Synthetic */ + ? (_a = base.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); }) + : (_b = base.declarations) === null || _b === void 0 ? void 0 : _b.every(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); })) + || ts.getCheckFlags(base) & 262144 /* CheckFlags.Mapped */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { - // when the base property is abstract or from an interface, base/derived flags don't need to match - // same when the derived property is from an assignment - continue; + return "continue"; } var overriddenInstanceProperty = basePropertyFlags !== 4 /* SymbolFlags.Property */ && derivedPropertyFlags === 4 /* SymbolFlags.Property */; var overriddenInstanceAccessor = basePropertyFlags === 4 /* SymbolFlags.Property */ && derivedPropertyFlags !== 4 /* SymbolFlags.Property */; @@ -84419,12 +85597,12 @@ var ts; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { - var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); + var uninitialized = (_c = derived.declarations) === null || _c === void 0 ? void 0 : _c.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* SymbolFlags.Transient */) && !(baseDeclarationFlags & 128 /* ModifierFlags.Abstract */) && !(derivedDeclarationFlags & 128 /* ModifierFlags.Abstract */) - && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { + && !((_d = derived.declarations) === null || _d === void 0 ? void 0 : _d.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -84437,13 +85615,11 @@ var ts; } } } - // correct case - continue; + return "continue"; } else if (isPrototypeProperty(base)) { if (isPrototypeProperty(derived) || derived.flags & 4 /* SymbolFlags.Property */) { - // method is overridden with method or property -- correct case - continue; + return "continue"; } else { ts.Debug.assert(!!(derived.flags & 98304 /* SymbolFlags.Accessor */)); @@ -84458,9 +85634,20 @@ var ts; } error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } + }; + basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var state_10 = _loop_34(baseProperty); + switch (state_10) { + case "continue-basePropertyCheck": continue basePropertyCheck; + } } } - function getNonInterhitedProperties(type, baseTypes, properties) { + function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { + return baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && (!ts.isPropertyDeclaration(declaration) || !declaration.initializer) + || ts.isInterfaceDeclaration(declaration.parent); + } + function getNonInheritedProperties(type, baseTypes, properties) { if (!ts.length(baseTypes)) { return properties; } @@ -84529,7 +85716,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName) || ts.isComputedPropertyName(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || containsUndefinedType(type))) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -84554,7 +85741,7 @@ var ts; ts.setParent(reference, staticBlock); reference.flowNode = staticBlock.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - if (!(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */)) { + if (!containsUndefinedType(flowType)) { return true; } } @@ -84569,7 +85756,7 @@ var ts; ts.setParent(reference, constructor); reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */); + return !containsUndefinedType(flowType); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -85085,6 +86272,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a, _b, _c, _d, _e; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -85095,6 +86283,31 @@ var ts; // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). symbol = getMergedSymbol(symbol.exportSymbol || symbol); + // A type-only import/export will already have a grammar error in a JS file, so no need to issue more errors within + if (ts.isInJSFile(node) && !(target.flags & 111551 /* SymbolFlags.Value */) && !ts.isTypeOnlyImportOrExportDeclaration(node)) { + var errorNode = ts.isImportOrExportSpecifier(node) ? node.propertyName || node.name : + ts.isNamedDeclaration(node) ? node.name : + node; + ts.Debug.assert(node.kind !== 274 /* SyntaxKind.NamespaceExport */); + if (node.kind === 275 /* SyntaxKind.ExportSpecifier */) { + var diag = error(errorNode, ts.Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); + var alreadyExportedSymbol = (_b = (_a = ts.getSourceFileOfNode(node).symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.get((node.propertyName || node.name).escapedText); + if (alreadyExportedSymbol === target) { + var exportingDeclaration = (_c = alreadyExportedSymbol.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isJSDocNode); + if (exportingDeclaration) { + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(exportingDeclaration, ts.Diagnostics._0_is_automatically_exported_here, ts.unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName))); + } + } + } + else { + ts.Debug.assert(node.kind !== 254 /* SyntaxKind.VariableDeclaration */); + var importDeclaration = ts.findAncestor(node, ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration)); + var moduleSpecifier = (_e = (importDeclaration && ((_d = ts.tryGetModuleSpecifierFromDeclaration(importDeclaration)) === null || _d === void 0 ? void 0 : _d.text))) !== null && _e !== void 0 ? _e : "..."; + var importedIdentifier = ts.unescapeLeadingUnderscores(ts.isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); + error(errorNode, ts.Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, "import(\"".concat(moduleSpecifier, "\").").concat(importedIdentifier)); + } + return; + } 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); @@ -85200,10 +86413,10 @@ var ts; var override = ts.getResolutionModeOverrideForClause(declaration.assertClause, validForTypeAssertions ? grammarErrorOnNode : undefined); if (validForTypeAssertions && override) { if (!ts.isNightly()) { - grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } return; // Other grammar checks do not apply to type-only imports with resolution mode assertions } @@ -85410,7 +86623,9 @@ var ts; error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { - markExportAsReferenced(node); + if (!node.isTypeOnly && !node.parent.parent.isTypeOnly) { + markExportAsReferenced(node); + } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); @@ -85552,12 +86767,16 @@ var ts; } } function checkSourceElementWorker(node) { - if (ts.isInJSFile(node)) { - ts.forEach(node.jsDoc, function (_a) { - var tags = _a.tags; - return ts.forEach(tags, checkSourceElement); + ts.forEach(node.jsDoc, function (_a) { + var comment = _a.comment, tags = _a.tags; + checkJSDocCommentWorker(comment); + ts.forEach(tags, function (tag) { + checkJSDocCommentWorker(tag.comment); + if (ts.isInJSFile(node)) { + checkSourceElement(tag); + } }); - } + }); var kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessively @@ -85643,6 +86862,10 @@ var ts; return checkJSDocTemplateTag(node); case 343 /* SyntaxKind.JSDocTypeTag */: return checkJSDocTypeTag(node); + case 324 /* SyntaxKind.JSDocLink */: + case 325 /* SyntaxKind.JSDocLinkCode */: + case 326 /* SyntaxKind.JSDocLinkPlain */: + return checkJSDocLinkLikeTag(node); case 340 /* SyntaxKind.JSDocParameterTag */: return checkJSDocParameterTag(node); case 347 /* SyntaxKind.JSDocPropertyTag */: @@ -85737,6 +86960,15 @@ var ts; return checkMissingDeclaration(node); } } + function checkJSDocCommentWorker(node) { + if (ts.isArray(node)) { + ts.forEach(node, function (tag) { + if (ts.isJSDocLinkLike(tag)) { + checkSourceElement(tag); + } + }); + } + } function checkJSDocTypeIsInJsFile(node) { if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); @@ -85904,6 +87136,7 @@ var ts; ts.clear(potentialNewTargetCollisions); ts.clear(potentialWeakMapSetCollisions); ts.clear(potentialReflectCollisions); + ts.clear(potentialUnusedRenamedBindingElementsInTypes); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -85919,6 +87152,9 @@ var ts; } }); } + if (!node.isDeclarationFile) { + checkPotentialUncheckedRenamedBindingElementsInTypes(); + } }); if (compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ && !node.isDeclarationFile && @@ -86292,7 +87528,7 @@ var ts; if (!result && isJSDoc_1) { var container = ts.findAncestor(name, ts.or(ts.isClassLike, ts.isInterfaceDeclaration)); if (container) { - return resolveJSDocMemberName(name, getSymbolOfNode(container)); + return resolveJSDocMemberName(name, /*ignoreErrors*/ false, getSymbolOfNode(container)); } } return result; @@ -86338,11 +87574,11 @@ var ts; * * For unqualified names, a container K may be provided as a second argument. */ - function resolveJSDocMemberName(name, container) { + function resolveJSDocMemberName(name, ignoreErrors, container) { if (ts.isEntityName(name)) { // resolve static values first var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */ | 111551 /* SymbolFlags.Value */; - var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, ignoreErrors, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); if (!symbol && ts.isIdentifier(name) && container) { symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning)); } @@ -86350,7 +87586,7 @@ var ts; return symbol; } } - var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left); + var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container); var right = ts.isIdentifier(name) ? name.escapedText : name.right.escapedText; if (left) { var proto = left.flags & 111551 /* SymbolFlags.Value */ && getPropertyOfType(getTypeOfSymbol(left), "prototype"); @@ -87341,13 +88577,20 @@ var ts; if (!fileToDirective) { return undefined; } + // computed property name should use node as value // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; - if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + var meaning; + if (node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) { meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; } + else { + meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; + if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; + } + } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -87631,7 +88874,10 @@ var ts; return checkGrammarDecorators(node) || checkGrammarModifiers(node); } function checkGrammarDecorators(node) { - if (!node.decorators) { + if (ts.canHaveIllegalDecorators(node) && ts.some(node.illegalDecorators)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node)) { return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { @@ -87644,7 +88890,7 @@ var ts; } else if (node.kind === 172 /* SyntaxKind.GetAccessor */ || node.kind === 173 /* SyntaxKind.SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + if (ts.hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } } @@ -87659,6 +88905,8 @@ var ts; var flags = 0 /* ModifierFlags.None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; if (modifier.kind !== 145 /* SyntaxKind.ReadonlyKeyword */) { if (node.kind === 166 /* SyntaxKind.PropertySignature */ || node.kind === 168 /* SyntaxKind.MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); @@ -87944,6 +89192,13 @@ var ts; case 164 /* SyntaxKind.Parameter */: case 163 /* SyntaxKind.TypeParameter */: return false; + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 179 /* SyntaxKind.FunctionType */: + case 276 /* SyntaxKind.MissingDeclaration */: + return true; default: if (node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 305 /* SyntaxKind.SourceFile */) { return false; @@ -87954,20 +89209,26 @@ var ts; case 257 /* SyntaxKind.ClassDeclaration */: case 180 /* SyntaxKind.ConstructorType */: return nodeHasAnyModifiersExcept(node, 126 /* SyntaxKind.AbstractKeyword */); + case 226 /* SyntaxKind.ClassExpression */: case 258 /* SyntaxKind.InterfaceDeclaration */: case 237 /* SyntaxKind.VariableStatement */: case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: return true; case 260 /* SyntaxKind.EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 85 /* SyntaxKind.ConstKeyword */); default: - ts.Debug.fail(); + ts.Debug.assertNever(node); } } } function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; + return modifier.kind !== allowedModifier; + } + return false; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { @@ -88259,14 +89520,20 @@ var ts; grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration - if (prop.modifiers) { + if (ts.canHaveModifiers(prop) && prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */) { + if (ts.isModifier(mod) && (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */)) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } + else if (ts.canHaveIllegalModifiers(prop) && prop.modifiers) { + for (var _d = 0, _e = prop.modifiers; _d < _e.length; _d++) { + var mod = _e[_d]; + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and @@ -88278,10 +89545,9 @@ var ts; var currentKind = void 0; switch (prop.kind) { case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); - // falls through case 296 /* SyntaxKind.PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* SyntaxKind.NumericLiteral */) { checkGrammarNumericLiteral(name); @@ -88720,9 +89986,6 @@ var ts; else { return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (!isConstOrReadonly || isInvalidInitializer) { - return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } } } function checkGrammarVariableDeclaration(node) { @@ -88889,7 +90152,7 @@ var ts; } } function checkGrammarConstructorTypeAnnotation(node) { - var type = ts.getEffectiveReturnTypeNode(node); + var type = node.type || ts.getEffectiveReturnTypeNode(node); if (type) { return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } @@ -88913,6 +90176,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Interfaces cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } @@ -88921,6 +90186,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Type literals cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } @@ -89295,7 +90562,6 @@ var ts; if (nodes === undefined || visitor === undefined) { return nodes; } - var updated; // Ensure start and count have valid values var length = nodes.length; if (start === undefined || start < 0) { @@ -89308,12 +90574,49 @@ var ts; var pos = -1; var end = -1; if (start > 0 || count < length) { - // If we are not visiting all of the original nodes, we must always create a new array. // Since this is a fragment of a node array, we do not copy over the previous location // and will only copy over `hasTrailingComma` if we are including the last element. - updated = []; hasTrailingComma = nodes.hasTrailingComma && start + count === length; } + else { + pos = nodes.pos; + end = nodes.end; + hasTrailingComma = nodes.hasTrailingComma; + } + var updated = visitArrayWorker(nodes, visitor, test, start, count); + if (updated !== nodes) { + // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. + var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); + ts.setTextRangePosEnd(updatedArray, pos, end); + return updatedArray; + } + return nodes; + } + ts.visitNodes = visitNodes; + /* @internal */ + function visitArray(nodes, visitor, test, start, count) { + if (nodes === undefined) { + return nodes; + } + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + return visitArrayWorker(nodes, visitor, test, start, count); + } + ts.visitArray = visitArray; + /* @internal */ + function visitArrayWorker(nodes, visitor, test, start, count) { + var updated; + var length = nodes.length; + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + updated = []; + } // Visit each original node. for (var i = 0; i < count; i++) { var node = nodes[i + start]; @@ -89322,9 +90625,6 @@ var ts; if (updated === undefined) { // Ensure we have a copy of `nodes`, up to the current index. updated = nodes.slice(0, i); - hasTrailingComma = nodes.hasTrailingComma; - pos = nodes.pos; - end = nodes.end; } if (visited) { if (ts.isArray(visited)) { @@ -89341,15 +90641,8 @@ var ts; } } } - if (updated) { - // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. - var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); - ts.setTextRangePosEnd(updatedArray, pos, end); - return updatedArray; - } - return nodes; + return updated !== null && updated !== void 0 ? updated : nodes; } - ts.visitNodes = visitNodes; /** * Starts a new lexical environment and visits a statement list, ending the lexical environment * and merging hoisted declarations upon completion. @@ -89421,7 +90714,7 @@ var ts; /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) : factory.getGeneratedNameForNode(parameter)), ]))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, /*initializer*/ undefined); } function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { @@ -89429,7 +90722,7 @@ var ts; context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([ factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(ts.setEmitFlags(factory.cloneNode(name), 48 /* EmitFlags.NoSourceMap */), ts.setEmitFlags(initializer, 48 /* EmitFlags.NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* EmitFlags.NoComments */)), parameter), 1536 /* EmitFlags.NoComments */)) ]), parameter), 1 /* EmitFlags.SingleLine */ | 32 /* EmitFlags.NoTrailingSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */ | 1536 /* EmitFlags.NoComments */))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, /*initializer*/ undefined); } function visitFunctionBody(node, visitor, context, nodeVisitor) { @@ -89495,7 +90788,7 @@ var ts; return factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); case 164 /* SyntaxKind.Parameter */: ts.Debug.type(node); - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + return factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 165 /* SyntaxKind.Decorator */: ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -89505,7 +90798,7 @@ var ts; return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 167 /* SyntaxKind.PropertyDeclaration */: ts.Debug.type(node); - return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), + return factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 168 /* SyntaxKind.MethodSignature */: @@ -89513,21 +90806,21 @@ var ts; return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 169 /* SyntaxKind.MethodDeclaration */: ts.Debug.type(node); - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 171 /* SyntaxKind.Constructor */: ts.Debug.type(node); - return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 172 /* SyntaxKind.GetAccessor */: ts.Debug.type(node); - return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 173 /* SyntaxKind.SetAccessor */: ts.Debug.type(node); - return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: ts.Debug.type(node); context.startLexicalEnvironment(); context.suspendLexicalEnvironment(); - return factory.updateClassStaticBlockDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 174 /* SyntaxKind.CallSignature */: ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -89536,7 +90829,7 @@ var ts; return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 176 /* SyntaxKind.IndexSignature */: ts.Debug.type(node); - return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types case 177 /* SyntaxKind.TypePredicate */: ts.Debug.type(node); @@ -89582,13 +90875,13 @@ var ts; return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); case 200 /* SyntaxKind.ImportType */: ts.Debug.type(node); - return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); case 295 /* SyntaxKind.ImportTypeAssertionContainer */: ts.Debug.type(node); return factory.updateImportTypeAssertionContainer(node, nodeVisitor(node.assertClause, visitor, ts.isNode), node.multiLine); case 197 /* SyntaxKind.NamedTupleMember */: ts.Debug.type(node); - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + return factory.updateNamedTupleMember(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 191 /* SyntaxKind.ParenthesizedType */: ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -89653,7 +90946,7 @@ var ts; return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 210 /* SyntaxKind.TaggedTemplateExpression */: ts.Debug.type(node); - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); case 211 /* SyntaxKind.TypeAssertionExpression */: ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -89701,7 +90994,7 @@ var ts; return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 226 /* SyntaxKind.ClassExpression */: ts.Debug.type(node); - return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 228 /* SyntaxKind.ExpressionWithTypeArguments */: ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); @@ -89782,22 +91075,22 @@ var ts; return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 256 /* SyntaxKind.FunctionDeclaration */: ts.Debug.type(node); - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 257 /* SyntaxKind.ClassDeclaration */: ts.Debug.type(node); - return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 258 /* SyntaxKind.InterfaceDeclaration */: ts.Debug.type(node); - return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + return factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 259 /* SyntaxKind.TypeAliasDeclaration */: ts.Debug.type(node); - return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 260 /* SyntaxKind.EnumDeclaration */: ts.Debug.type(node); - return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + return factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 261 /* SyntaxKind.ModuleDeclaration */: ts.Debug.type(node); - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + return factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); case 262 /* SyntaxKind.ModuleBlock */: ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); @@ -89809,10 +91102,10 @@ var ts; return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); case 265 /* SyntaxKind.ImportEqualsDeclaration */: ts.Debug.type(node); - return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); + return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); case 266 /* SyntaxKind.ImportDeclaration */: ts.Debug.type(node); - return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 293 /* SyntaxKind.AssertClause */: ts.Debug.type(node); return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); @@ -89836,10 +91129,10 @@ var ts; return factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); case 271 /* SyntaxKind.ExportAssignment */: ts.Debug.type(node); - return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); + return factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); case 272 /* SyntaxKind.ExportDeclaration */: ts.Debug.type(node); - return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 273 /* SyntaxKind.NamedExports */: ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); @@ -90932,6 +92225,126 @@ var ts; return !ts.isStatic(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); } ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; + if (decorators || ts.hasDecorators(parameter)) { + if (!decorators) { + decorators = new Array(numParameters); + } + decorators[i] = ts.getDecorators(parameter); + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfClass(node) { + var decorators = ts.getDecorators(node); + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + ts.getAllDecoratorsOfClass = getAllDecoratorsOfClass; + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param parent The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(member, parent) { + switch (member.kind) { + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: + return getAllDecoratorsOfAccessors(member, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 167 /* SyntaxKind.PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + ts.getAllDecoratorsOfClassElement = getAllDecoratorsOfClassElement; + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param parent The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(accessor, parent) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(parent.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = ts.hasDecorators(firstAccessor) ? firstAccessor : + secondAccessor && ts.hasDecorators(secondAccessor) ? secondAccessor : + undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = ts.getDecorators(firstAccessorWithDecorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters, + getDecorators: getAccessor && ts.getDecorators(getAccessor), + setDecorators: setAccessor && ts.getDecorators(setAccessor) + }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = ts.getDecorators(method); + var parameters = getDecoratorsOfParameters(method); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = ts.getDecorators(property); + if (!ts.some(decorators)) { + return undefined; + } + return { decorators: decorators }; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -91205,8 +92618,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */ - && !(element.transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -91272,7 +92685,7 @@ var ts; if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -91494,8 +92907,6 @@ var ts; var USE_NEW_TYPE_METADATA_FORMAT = false; var TypeScriptSubstitutionFlags; (function (TypeScriptSubstitutionFlags) { - /** Enables substitutions for decorated classes. */ - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; /** Enables substitutions for namespace exports. */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; /* Enables substitutions for unqualified enum members */ @@ -91521,9 +92932,9 @@ var ts; var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); - var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var typeSerializer = compilerOptions.emitDecoratorMetadata ? ts.createRuntimeTypeSerializer(context) : undefined; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -91538,7 +92949,6 @@ var ts; var currentNamespace; var currentNamespaceContainerName; var currentLexicalScope; - var currentNameScope; var currentScopeFirstDeclarationsOfName; var currentClassHasParameterProperties; /** @@ -91546,11 +92956,6 @@ var ts; * They are persisted between each SourceFile transformation and should not be reset. */ var enabledSubstitutions; - /** - * A map that keeps track of aliases created for classes with decorators to avoid issues - * with the double-binding behavior of classes. - */ - var classAliases; /** * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. @@ -91594,7 +92999,6 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentLexicalScope; - var savedCurrentNameScope = currentNameScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties; // Handle state changes before visiting a node. @@ -91605,7 +93009,6 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } currentLexicalScope = savedCurrentScope; - currentNameScope = savedCurrentNameScope; currentClassHasParameterProperties = savedCurrentClassHasParameterProperties; return visited; } @@ -91621,7 +93024,6 @@ var ts; case 262 /* SyntaxKind.ModuleBlock */: case 235 /* SyntaxKind.Block */: currentLexicalScope = node; - currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; case 257 /* SyntaxKind.ClassDeclaration */: @@ -91639,10 +93041,6 @@ var ts; // programs may also have an undefined name. ts.Debug.assert(node.kind === 257 /* SyntaxKind.ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)); } - if (ts.isClassDeclaration(node)) { - // XXX: should probably also cover interfaces and type aliases that can have type variables? - currentNameScope = node; - } break; } } @@ -91744,40 +93142,73 @@ var ts; return node; } /** - * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * Gets a specialized visitor that visits the immediate children of a class with TypeScript syntax. * - * @param node The node to visit. + * @param parent The class containing the elements to visit. */ - function classElementVisitor(node) { - return saveStateAndInvoke(node, classElementVisitorWorker); + function getClassElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return classElementVisitorWorker(n, parent); }); }; } /** * Specialized visitor that visits the immediate children of a class with TypeScript syntax. * * @param node The node to visit. */ - function classElementVisitorWorker(node) { + function classElementVisitorWorker(node, parent) { switch (node.kind) { case 171 /* SyntaxKind.Constructor */: return visitConstructor(node); case 167 /* SyntaxKind.PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. - return visitPropertyDeclaration(node); - case 176 /* SyntaxKind.IndexSignature */: + return visitPropertyDeclaration(node, parent); case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - // Fallback to the default visit behavior. - return visitorWorker(node); + return ts.visitEachChild(node, visitor, context); case 234 /* SyntaxKind.SemicolonClassElement */: return node; + case 176 /* SyntaxKind.IndexSignature */: + // Index signatures are elided + return; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function getObjectLiteralElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return objectLiteralElementVisitorWorker(n, parent); }); }; + } + function objectLiteralElementVisitorWorker(node, parent) { + switch (node.kind) { + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 298 /* SyntaxKind.SpreadAssignment */: + return visitor(node); + case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); + case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { + if (ts.isDecorator(node)) + return undefined; if (ts.modifierToFlag(node.kind) & 116958 /* ModifierFlags.TypeScriptModifier */) { return undefined; } @@ -91845,22 +93276,14 @@ var ts; // TypeScript type nodes are elided. // falls through case 176 /* SyntaxKind.IndexSignature */: - // TypeScript index signatures are elided. - // falls through - case 165 /* SyntaxKind.Decorator */: - // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + // TypeScript index signatures are elided. return undefined; case 259 /* SyntaxKind.TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return factory.createNotEmittedStatement(node); - case 167 /* SyntaxKind.PropertyDeclaration */: - // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects - return visitPropertyDeclaration(node); case 264 /* SyntaxKind.NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 171 /* SyntaxKind.Constructor */: - return visitConstructor(node); case 258 /* SyntaxKind.InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. @@ -91894,16 +93317,15 @@ var ts; case 228 /* SyntaxKind.ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); + case 205 /* SyntaxKind.ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 171 /* SyntaxKind.Constructor */: + case 167 /* SyntaxKind.PropertyDeclaration */: case 169 /* SyntaxKind.MethodDeclaration */: - // TypeScript method declarations may have decorators, modifiers - // or type annotations. - return visitMethodDeclaration(node); case 172 /* SyntaxKind.GetAccessor */: - // Get Accessors can have TypeScript modifiers, decorators, and type annotations. - return visitGetAccessor(node); case 173 /* SyntaxKind.SetAccessor */: - // Set Accessors can have TypeScript modifiers and type annotations. - return visitSetAccessor(node); + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + return ts.Debug.fail("Class and object literal elements must be visited with their respective visitors"); case 256 /* SyntaxKind.FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); @@ -91969,6 +93391,9 @@ var ts; !ts.isJsonSourceFile(node); return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } + function visitObjectLiteralExpression(node) { + return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, getObjectLiteralElementVisitor(node), ts.isObjectLiteralElement)); + } function getClassFacts(node, staticProperties) { var facts = 0 /* ClassFacts.None */; if (ts.some(staticProperties)) @@ -91991,17 +93416,18 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { - return ts.some(node.decorators) + return ts.hasDecorators(node) || ts.some(node.typeParameters) || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) || ts.some(node.members, hasTypeScriptClassSyntax); } function visitClassDeclaration(node) { if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */))) { - return ts.visitEachChild(node, visitor, context); + return factory.updateClassDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); var facts = getClassFacts(node, staticProperties); @@ -92009,14 +93435,25 @@ var ts; context.startLexicalEnvironment(); } var name = node.name || (facts & 5 /* ClassFacts.NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined); - var classStatement = facts & 2 /* ClassFacts.HasConstructorDecorators */ - ? createClassDeclarationHeadWithDecorators(node, name) - : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : ts.elideNodes(factory, node.modifiers); // preserve positions, if available + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var classStatement = factory.updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { + emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; + } + ts.setEmitFlags(classStatement, emitFlags); var statements = [classStatement]; - // Write any decorators of the node. - addClassElementDecorationStatements(statements, node, /*isStatic*/ false); - addClassElementDecorationStatements(statements, node, /*isStatic*/ true); - addConstructorDecorationStatement(statements, node); if (facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) { // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the // 'es2015' transformer can properly nest static initializers and decorators. The result @@ -92076,164 +93513,13 @@ var ts; } return ts.singleOrMany(statements); } - /** - * Transforms a non-decorated class declaration and appends the resulting statements. - * - * @param node A ClassDeclaration node. - * @param name The name of the class. - * @param facts Precomputed facts about the class. - */ - function createClassDeclarationHeadWithoutDecorators(node, name, facts) { - // ${modifiers} class ${name} ${heritageClauses} { - // ${members} - // } - // we do not emit modifiers on the declaration if we are emitting an IIFE - var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) - ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) - : undefined; - var classDeclaration = factory.createClassDeclaration( - /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - // To better align with the old emitter, we should not emit a trailing source map - // entry if the class has static properties. - var emitFlags = ts.getEmitFlags(node); - if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { - emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; - } - ts.setTextRange(classDeclaration, node); - ts.setOriginalNode(classDeclaration, node); - ts.setEmitFlags(classDeclaration, emitFlags); - return classDeclaration; - } - /** - * Transforms a decorated class declaration and appends the resulting statements. If - * the class requires an alias to avoid issues with double-binding, the alias is returned. - */ - function createClassDeclarationHeadWithDecorators(node, name) { - // When we emit an ES6 class that has a class decorator, we must tailor the - // emit to certain specific cases. - // - // In the simplest case, we emit the class declaration as a let declaration, and - // evaluate decorators after the close of the class body: - // - // [Example 1] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // class C { | } - // } | C = __decorate([dec], C); - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | } - // } | C = __decorate([dec], C); - // | export { C }; - // --------------------------------------------------------------------- - // - // If a class declaration contains a reference to itself *inside* of the class body, - // this introduces two bindings to the class: One outside of the class body, and one - // inside of the class body. If we apply decorators as in [Example 1] above, there - // is the possibility that the decorator `dec` will return a new value for the - // constructor, which would result in the binding inside of the class no longer - // pointing to the same reference as the binding outside of the class. - // - // As a result, we must instead rewrite all references to the class *inside* of the - // class body to instead point to a local temporary alias for the class: - // - // [Example 2] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = C_1 = class C { - // class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | var C_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export { C }; - // | var C_1; - // --------------------------------------------------------------------- - // - // If a class declaration is the default export of a module, we instead emit - // the export after the decorated declaration: - // - // [Example 3] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let default_1 = class { - // export default class { | } - // } | default_1 = __decorate([dec], default_1); - // | export default default_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | } - // } | C = __decorate([dec], C); - // | export default C; - // --------------------------------------------------------------------- - // - // If the class declaration is the default export and a reference to itself - // inside of the class body, we must emit both an alias for the class *and* - // move the export after the declaration: - // - // [Example 4] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export default C; - // | var C_1; - // --------------------------------------------------------------------- - // - var location = ts.moveRangePastDecorators(node); - var classAlias = getClassAliasIfNeeded(node); - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - // ... = class ${name} ${heritageClauses} { - // ${members} - // } - var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node); - var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, location); - // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference - // or decoratedClassAlias if the class contain self-reference. - var statement = factory.createVariableStatement( - /*modifiers*/ undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(declName, - /*exclamationToken*/ undefined, - /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) - ], 1 /* NodeFlags.Let */)); - ts.setOriginalNode(statement, node); - ts.setTextRange(statement, location); - ts.setCommentRange(statement, node); - return statement; - } function visitClassExpression(node) { - if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { - return ts.visitEachChild(node, visitor, context); - } - var classExpression = factory.createClassExpression( - /*decorators*/ undefined, - /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, node); - return classExpression; + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + return factory.updateClassExpression(node, decorators, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), isClassLikeDeclarationWithTypeScriptSyntax(node) ? + transformClassMembers(node) : + ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } /** * Transforms the members of a class. @@ -92250,7 +93536,6 @@ var ts; var parameter = parametersWithPropertyAssignments_1[_i]; if (ts.isIdentifier(parameter.name)) { members.push(ts.setOriginalNode(factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameter.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -92258,159 +93543,9 @@ var ts; } } } - ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + ts.addRange(members, ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - /** - * Gets either the static or instance members of a class that are decorated, or have - * parameters that are decorated. - * - * @param node The class containing the member. - * @param isStatic A value indicating whether to retrieve static or instance members of - * the class. - */ - function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); - } - /** - * Determines whether a class member is a static member of a class that is decorated, or - * has parameters that are decorated. - * - * @param member The class member. - */ - function isStaticDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ true, parent); - } - /** - * Determines whether a class member is an instance member of a class that is decorated, - * or has parameters that are decorated. - * - * @param member The class member. - */ - function isInstanceDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ false, parent); - } - /** - * Determines whether a class member is either a static or an instance member of a class - * that is decorated, or has parameters that are decorated. - * - * @param member The class member. - */ - function isDecoratedClassElement(member, isStaticElement, parent) { - return ts.nodeOrChildIsDecorated(member, parent) - && isStaticElement === ts.isStatic(member); - } - /** - * Gets an array of arrays of decorators for the parameters of a function-like node. - * The offset into the result array should correspond to the offset of the parameter. - * - * @param node The function-like node. - */ - function getDecoratorsOfParameters(node) { - var decorators; - if (node) { - var parameters = node.parameters; - var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); - var firstParameterOffset = firstParameterIsThis ? 1 : 0; - var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i + firstParameterOffset]; - if (decorators || parameter.decorators) { - if (!decorators) { - decorators = new Array(numParameters); - } - decorators[i] = parameter.decorators; - } - } - } - return decorators; - } - /** - * Gets an AllDecorators object containing the decorators for the class and the decorators for the - * parameters of the constructor of the class. - * - * @param node The class node. - */ - function getAllDecoratorsOfConstructor(node) { - var decorators = node.decorators; - var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); - if (!decorators && !parameters) { - return undefined; - } - return { - decorators: decorators, - parameters: parameters - }; - } - /** - * Gets an AllDecorators object containing the decorators for the member and its parameters. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function getAllDecoratorsOfClassElement(node, member) { - switch (member.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - return getAllDecoratorsOfAccessors(node, member); - case 169 /* SyntaxKind.MethodDeclaration */: - return getAllDecoratorsOfMethod(member); - case 167 /* SyntaxKind.PropertyDeclaration */: - return getAllDecoratorsOfProperty(member); - default: - return undefined; - } - } - /** - * Gets an AllDecorators object containing the decorators for the accessor and its parameters. - * - * @param node The class node that contains the accessor. - * @param accessor The class accessor member. - */ - function getAllDecoratorsOfAccessors(node, accessor) { - if (!accessor.body) { - return undefined; - } - var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; - if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { - return undefined; - } - var decorators = firstAccessorWithDecorators.decorators; - var parameters = getDecoratorsOfParameters(setAccessor); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the method and its parameters. - * - * @param method The class method member. - */ - function getAllDecoratorsOfMethod(method) { - if (!method.body) { - return undefined; - } - var decorators = method.decorators; - var parameters = getDecoratorsOfParameters(method); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the property. - * - * @param property The class property member. - */ - function getAllDecoratorsOfProperty(property) { - var decorators = property.decorators; - if (!decorators) { - return undefined; - } - return { decorators: decorators }; - } /** * Transforms all of the decorators for a declaration into an array of expressions. * @@ -92418,212 +93553,89 @@ var ts; * @param allDecorators An object containing all of the decorators for the declaration. */ function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + var _a, _b, _c, _d; if (!allDecorators) { return undefined; } - var decoratorExpressions = []; - ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); - ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, container, decoratorExpressions); - return decoratorExpressions; - } - /** - * Generates statements used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate statements for static or - * instance members. - */ - function addClassElementDecorationStatements(statements, node, isStatic) { - ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); - } - /** - * Generates expressions used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate expressions for static or - * instance members. - */ - function generateClassElementDecorationExpressions(node, isStatic) { - var members = getDecoratedClassElements(node, isStatic); - var expressions; - for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { - var member = members_8[_i]; - var expression = generateClassElementDecorationExpression(node, member); - if (expression) { - if (!expressions) { - expressions = [expression]; - } - else { - expressions.push(expression); - } - } - } - return expressions; - } - /** - * Generates an expression used to evaluate class element decorators at runtime. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function generateClassElementDecorationExpression(node, member) { - var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - // Emit the call to __decorate. Given the following: - // - // class C { - // @dec method(@dec2 x) {} - // @dec get accessor() {} - // @dec prop; - // } - // - // The emit for a method is: - // - // __decorate([ - // dec, - // __param(0, dec2), - // __metadata("design:type", Function), - // __metadata("design:paramtypes", [Object]), - // __metadata("design:returntype", void 0) - // ], C.prototype, "method", null); - // - // The emit for an accessor is: - // - // __decorate([ - // dec - // ], C.prototype, "accessor", null); - // - // The emit for a property is: - // - // __decorate([ - // dec - // ], C.prototype, "prop"); - // - var prefix = getClassMemberPrefix(node, member); - var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); - var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ - ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ - // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it - // should not invoke `Object.getOwnPropertyDescriptor`. - ? factory.createVoidZero() - // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. - // We have this extra argument here so that we can inject an explicit property descriptor at a later date. - : factory.createNull() - : undefined; - var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); - ts.setTextRange(helper, ts.moveRangePastDecorators(member)); - ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - return helper; - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function addConstructorDecorationStatement(statements, node) { - var expression = generateConstructorDecorationExpression(node); - if (expression) { - statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); - } - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function generateConstructorDecorationExpression(node) { - var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); - var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); - ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); - ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); - return expression; - } - /** - * Transforms a decorator into an expression. - * - * @param decorator The decorator node. - */ - function transformDecorator(decorator) { - return ts.visitNode(decorator.expression, visitor, ts.isExpression); + var decorators = ts.visitArray(allDecorators.decorators, visitor, ts.isDecorator); + var parameterDecorators = ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter); + var metadataDecorators = ts.some(decorators) || ts.some(parameterDecorators) ? getTypeMetadata(node, container) : undefined; + var result = factory.createNodeArray(ts.concatenate(ts.concatenate(decorators, parameterDecorators), metadataDecorators)); + var pos = (_b = (_a = ts.firstOrUndefined(allDecorators.decorators)) === null || _a === void 0 ? void 0 : _a.pos) !== null && _b !== void 0 ? _b : -1; + var end = (_d = (_c = ts.lastOrUndefined(allDecorators.decorators)) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : -1; + ts.setTextRangePosEnd(result, pos, end); + return result; } /** - * Transforms the decorators of a parameter. + * Transforms the decorators of a parameter into decorators of the class/method. * - * @param decorators The decorators for the parameter at the provided offset. + * @param parameterDecorators The decorators for the parameter at the provided offset. * @param parameterOffset The offset of the parameter. */ - function transformDecoratorsOfParameter(decorators, parameterOffset) { - var expressions; - if (decorators) { - expressions = []; - for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { - var decorator = decorators_1[_i]; - var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); - ts.setTextRange(helper, decorator.expression); + function transformDecoratorsOfParameter(parameterDecorators, parameterOffset) { + if (parameterDecorators) { + var decorators = []; + for (var _i = 0, parameterDecorators_1 = parameterDecorators; _i < parameterDecorators_1.length; _i++) { + var parameterDecorator = parameterDecorators_1[_i]; + var expression = ts.visitNode(parameterDecorator.expression, visitor, ts.isExpression); + var helper = emitHelpers().createParamHelper(expression, parameterOffset); + ts.setTextRange(helper, parameterDecorator.expression); ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - expressions.push(helper); + var decorator = factory.createDecorator(helper); + ts.setSourceMapRange(decorator, parameterDecorator.expression); + ts.setCommentRange(decorator, parameterDecorator.expression); + ts.setEmitFlags(decorator, 1536 /* EmitFlags.NoComments */); + decorators.push(decorator); } + return decorators; } - return expressions; } /** - * Adds optional type metadata for a declaration. + * Gets optional type metadata for a declaration. * * @param node The declaration node. - * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node, container, decoratorExpressions) { - if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, container, decoratorExpressions); - } - else { - addOldTypeMetadata(node, container, decoratorExpressions); - } + function getTypeMetadata(node, container) { + return USE_NEW_TYPE_METADATA_FORMAT ? + getNewTypeMetadata(node, container) : + getOldTypeMetadata(node, container); } - function addOldTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getOldTypeMetadata(node, container) { + if (typeSerializer) { + var decorators = void 0; if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node))); + var typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(typeMetadata)); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container))); + var paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container)); + decorators = ts.append(decorators, factory.createDecorator(paramTypesMetadata)); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node))); + var returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(returnTypeMetadata)); } + return decorators; } } - function addNewTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getNewTypeMetadata(node, container) { + if (typeSerializer) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + var typeProperty = factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, typeProperty); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + var paramTypeProperty = factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container))); + properties = ts.append(properties, paramTypeProperty); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + var returnTypeProperty = factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, returnTypeProperty); } if (properties) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true))); + var typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)); + return [factory.createDecorator(typeInfoMetadata)]; } } } @@ -92670,347 +93682,6 @@ var ts; } return false; } - function getAccessorTypeNode(node) { - var accessors = resolver.getAllAccessorDeclarations(node); - return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) - || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); - } - /** - * Serializes the type of a node for use with decorator type metadata. - * - * @param node The node that should have its type serialized. - */ - function serializeTypeOfNode(node) { - switch (node.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 164 /* SyntaxKind.Parameter */: - return serializeTypeNode(node.type); - case 173 /* SyntaxKind.SetAccessor */: - case 172 /* SyntaxKind.GetAccessor */: - return serializeTypeNode(getAccessorTypeNode(node)); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - return factory.createIdentifier("Function"); - default: - return factory.createVoidZero(); - } - } - /** - * Serializes the types of the parameters of a node for use with decorator type metadata. - * - * @param node The node that should have its parameter types serialized. - */ - function serializeParameterTypesOfNode(node, container) { - var valueDeclaration = ts.isClassLike(node) - ? ts.getFirstConstructorWithBody(node) - : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) - ? node - : undefined; - var expressions = []; - if (valueDeclaration) { - var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); - var numParameters = parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { - continue; - } - if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); - } - else { - expressions.push(serializeTypeOfNode(parameter)); - } - } - } - return factory.createArrayLiteralExpression(expressions); - } - function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { - var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; - if (setAccessor) { - return setAccessor.parameters; - } - } - return node.parameters; - } - /** - * Serializes the return type of a node for use with decorator type metadata. - * - * @param node The node that should have its return type serialized. - */ - function serializeReturnTypeOfNode(node) { - if (ts.isFunctionLike(node) && node.type) { - return serializeTypeNode(node.type); - } - else if (ts.isAsyncFunction(node)) { - return factory.createIdentifier("Promise"); - } - return factory.createVoidZero(); - } - /** - * Serializes a type node for use with decorator type metadata. - * - * Types are serialized in the following fashion: - * - Void types point to "undefined" (e.g. "void 0") - * - Function and Constructor types point to the global "Function" constructor. - * - Interface types with a call or construct signature types point to the global - * "Function" constructor. - * - Array and Tuple types point to the global "Array" constructor. - * - Type predicates and booleans point to the global "Boolean" constructor. - * - String literal types and strings point to the global "String" constructor. - * - Enum and number types point to the global "Number" constructor. - * - Symbol types point to the global "Symbol" constructor. - * - Type references to classes (or class-like variables) point to the constructor for the class. - * - Anything else points to the global "Object" constructor. - * - * @param node The type node to serialize. - */ - function serializeTypeNode(node) { - if (node === undefined) { - return factory.createIdentifier("Object"); - } - switch (node.kind) { - case 114 /* SyntaxKind.VoidKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - return factory.createVoidZero(); - case 191 /* SyntaxKind.ParenthesizedType */: - return serializeTypeNode(node.type); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - return factory.createIdentifier("Function"); - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: - return factory.createIdentifier("Array"); - case 177 /* SyntaxKind.TypePredicate */: - case 133 /* SyntaxKind.BooleanKeyword */: - return factory.createIdentifier("Boolean"); - case 198 /* SyntaxKind.TemplateLiteralType */: - case 150 /* SyntaxKind.StringKeyword */: - return factory.createIdentifier("String"); - case 148 /* SyntaxKind.ObjectKeyword */: - return factory.createIdentifier("Object"); - case 196 /* SyntaxKind.LiteralType */: - switch (node.literal.kind) { - case 10 /* SyntaxKind.StringLiteral */: - case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: - return factory.createIdentifier("String"); - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 8 /* SyntaxKind.NumericLiteral */: - return factory.createIdentifier("Number"); - case 9 /* SyntaxKind.BigIntLiteral */: - return getGlobalBigIntNameWithFallback(); - case 110 /* SyntaxKind.TrueKeyword */: - case 95 /* SyntaxKind.FalseKeyword */: - return factory.createIdentifier("Boolean"); - case 104 /* SyntaxKind.NullKeyword */: - return factory.createVoidZero(); - default: - return ts.Debug.failBadSyntaxKind(node.literal); - } - case 147 /* SyntaxKind.NumberKeyword */: - return factory.createIdentifier("Number"); - case 158 /* SyntaxKind.BigIntKeyword */: - return getGlobalBigIntNameWithFallback(); - case 151 /* SyntaxKind.SymbolKeyword */: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case 178 /* SyntaxKind.TypeReference */: - return serializeTypeReferenceNode(node); - case 188 /* SyntaxKind.IntersectionType */: - case 187 /* SyntaxKind.UnionType */: - return serializeTypeList(node.types); - case 189 /* SyntaxKind.ConditionalType */: - return serializeTypeList([node.trueType, node.falseType]); - case 193 /* SyntaxKind.TypeOperator */: - if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { - return serializeTypeNode(node.type); - } - break; - case 181 /* SyntaxKind.TypeQuery */: - case 194 /* SyntaxKind.IndexedAccessType */: - case 195 /* SyntaxKind.MappedType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 192 /* SyntaxKind.ThisType */: - case 200 /* SyntaxKind.ImportType */: - break; - // handle JSDoc types from an invalid parse - case 312 /* SyntaxKind.JSDocAllType */: - case 313 /* SyntaxKind.JSDocUnknownType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 318 /* SyntaxKind.JSDocVariadicType */: - case 319 /* SyntaxKind.JSDocNamepathType */: - break; - case 314 /* SyntaxKind.JSDocNullableType */: - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 316 /* SyntaxKind.JSDocOptionalType */: - return serializeTypeNode(node.type); - default: - return ts.Debug.failBadSyntaxKind(node); - } - return factory.createIdentifier("Object"); - } - function serializeTypeList(types) { - // Note when updating logic here also update getEntityNameForDecoratorMetadata - // so that aliases can be marked as referenced - var serializedUnion; - for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { - var typeNode = types_23[_i]; - while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 196 /* SyntaxKind.LiteralType */ && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */ || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { - // One of the individual is global object, return immediately - return serializedIndividual; - } - // If there exists union that is not void 0 expression, check if the the common type is identifier. - // anything more complex and we will just default to Object - else if (serializedUnion) { - // Different types - if (!ts.isIdentifier(serializedUnion) || - !ts.isIdentifier(serializedIndividual) || - serializedUnion.escapedText !== serializedIndividual.escapedText) { - return factory.createIdentifier("Object"); - } - } - else { - // Initialize the union type - serializedUnion = serializedIndividual; - } - } - // If we were able to find common type, use it - return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never - } - /** - * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with - * decorator type metadata. - * - * @param node The type reference node. - */ - function serializeTypeReferenceNode(node) { - var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); - switch (kind) { - case ts.TypeReferenceSerializationKind.Unknown: - // From conditional type type reference that cannot be resolved is Similar to any or unknown - if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { - return factory.createIdentifier("Object"); - } - var serialized = serializeEntityNameAsExpressionFallback(node.typeName); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), - /*questionToken*/ undefined, temp, - /*colonToken*/ undefined, factory.createIdentifier("Object")); - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName); - case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: - return factory.createVoidZero(); - case ts.TypeReferenceSerializationKind.BigIntLikeType: - return getGlobalBigIntNameWithFallback(); - case ts.TypeReferenceSerializationKind.BooleanType: - return factory.createIdentifier("Boolean"); - case ts.TypeReferenceSerializationKind.NumberLikeType: - return factory.createIdentifier("Number"); - case ts.TypeReferenceSerializationKind.StringLikeType: - return factory.createIdentifier("String"); - case ts.TypeReferenceSerializationKind.ArrayLikeType: - return factory.createIdentifier("Array"); - case ts.TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - return factory.createIdentifier("Function"); - case ts.TypeReferenceSerializationKind.Promise: - return factory.createIdentifier("Promise"); - case ts.TypeReferenceSerializationKind.ObjectType: - return factory.createIdentifier("Object"); - default: - return ts.Debug.assertNever(kind); - } - } - function createCheckedValue(left, right) { - return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right); - } - /** - * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 79 /* SyntaxKind.Identifier */) { - // A -> typeof A !== undefined && A - var copied = serializeEntityNameAsExpression(node); - return createCheckedValue(copied, copied); - } - if (node.left.kind === 79 /* SyntaxKind.Identifier */) { - // A.B -> typeof A !== undefined && A.B - return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); - } - // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C - var left = serializeEntityNameAsExpressionFallback(node.left); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right)); - } - /** - * Serializes an entity name as an expression for decorator type metadata. - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpression(node) { - switch (node.kind) { - case 79 /* SyntaxKind.Identifier */: - // Create a clone of the name with a new parent, and treat it as if it were - // a source tree node for the purposes of the checker. - var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); - name.original = undefined; - ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. - return name; - case 161 /* SyntaxKind.QualifiedName */: - return serializeQualifiedNameAsExpression(node); - } - } - /** - * Serializes an qualified name as an expression for decorator type metadata. - * - * @param node The qualified name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * qualified name at runtime. - */ - function serializeQualifiedNameAsExpression(node) { - return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); - } - /** - * Gets an expression that points to the global "Symbol" constructor at runtime if it is - * available. - */ - function getGlobalSymbolNameWithFallback() { - return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("Symbol"), - /*colonToken*/ undefined, factory.createIdentifier("Object")); - } - /** - * Gets an expression that points to the global "BigInt" constructor at runtime if it is - * available. - */ - function getGlobalBigIntNameWithFallback() { - return languageVersion < 99 /* ScriptTarget.ESNext */ - ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("BigInt"), - /*colonToken*/ undefined, factory.createIdentifier("Object")) - : factory.createIdentifier("BigInt"); - } /** * Gets an expression that represents a property name (for decorated properties or enums). * For a computed property, a name is generated for the node. @@ -93047,7 +93718,7 @@ var ts; // The names are used more than once when: // - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments). // - the property has a decorator. - if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) { + if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.hasDecorators(member))) { var expression = ts.visitNode(name.expression, visitor, ts.isExpression); var innerExpression = ts.skipPartiallyEmittedExpressions(expression); if (!ts.isSimpleInlineableExpression(innerExpression)) { @@ -93095,28 +93766,29 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } - function visitPropertyDeclaration(node) { - if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)) { + function visitPropertyDeclaration(node, parent) { + var isAmbient = node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */); + if (isAmbient && !ts.hasDecorators(node)) { return undefined; } - var updated = factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), + var allDecorators = ts.getAllDecoratorsOfClassElement(node, parent); + var decorators = transformAllDecoratorsOfDeclaration(node, parent, allDecorators); + // Preserve a `declare x` property with decorators to be handled by the decorators transform + if (isAmbient) { + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, factory.createModifiersFromModifierFlags(2 /* ModifierFlags.Ambient */)), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } return factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node)); } function transformConstructorBody(body, constructor) { @@ -93155,7 +93827,8 @@ var ts; statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, prologueStatementCount), true), parameterPropertyAssignments, true), statements.slice(prologueStatementCount), true); } // Add remaining statements from the body, skipping the super() call if it was found and any (already added) prologue statements - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, superStatementIndex + 1 + prologueStatementCount)); + var start = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, start)); // End the lexical environment. statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true); @@ -93181,22 +93854,19 @@ var ts; ts.setEmitFlags(localName, 1536 /* EmitFlags.NoComments */); return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(factory.createExpressionStatement(factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1)))); } - function visitMethodDeclaration(node) { + function visitMethodDeclaration(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + var allDecorators = ts.isClassLike(parent) ? ts.getAllDecoratorsOfClassElement(node, parent) : undefined; + var decorators = ts.isClassLike(parent) ? transformAllDecoratorsOfDeclaration(node, parent, allDecorators) : undefined; + return factory.updateMethodDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), node.asteriskToken, visitPropertyNameOfClassElement(node), /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } /** * Determines whether to emit an accessor declaration. We should not emit the @@ -93207,41 +93877,36 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)); } - function visitGetAccessor(node) { + function visitGetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateGetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } - function visitSetAccessor(node) { + function visitSetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateSetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return factory.createNotEmittedStatement(node); } - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + var updated = factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); if (isExportOfNamespace(node)) { @@ -93270,9 +93935,8 @@ var ts; if (ts.parameterIsThisKeyword(node)) { return undefined; } - var updated = factory.updateParameterDeclaration(node, - /*decorators*/ undefined, - /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), // preserve positions, if available + node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); if (updated !== node) { @@ -93432,7 +94096,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); @@ -93662,7 +94326,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); @@ -93775,7 +94439,6 @@ var ts; compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ ? factory.updateImportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, importClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -93850,7 +94513,6 @@ var ts; var exportClause = ts.visitNode(node.exportClause, function (bindings) { return visitNamedExportBindings(bindings, allowEmpty); }, ts.isNamedExportBindings); return exportClause ? factory.updateExportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -93908,7 +94570,6 @@ var ts; // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'. if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */) { return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, node.moduleReference.expression, /*assertClause*/ undefined), node), node); @@ -93968,12 +94629,6 @@ var ts; return isExternalModuleExport(node) && ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */); } - /** - * Creates a statement for the provided expression. This is used in calls to `map`. - */ - function expressionToStatement(expression) { - return factory.createExpressionStatement(expression); - } function addExportMemberAssignment(statements, node) { var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); @@ -94005,44 +94660,12 @@ var ts; function getNamespaceContainerName(node) { return factory.getGeneratedNameForNode(node); } - /** - * Gets a local alias for a class declaration if it is a decorated class with an internal - * reference to the static side of the class. This is necessary to avoid issues with - * double-binding semantics for the class name. - */ - function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { - enableSubstitutionForClassAliases(); - var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - hoistVariableDeclaration(classAlias); - return classAlias; - } - } - function getClassPrototype(node) { - return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); - } - function getClassMemberPrefix(node, member) { - return ts.isStatic(member) - ? factory.getDeclarationName(node) - : getClassPrototype(node); - } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */; context.enableSubstitution(79 /* SyntaxKind.Identifier */); } } - function enableSubstitutionForClassAliases() { - if ((enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) === 0) { - enabledSubstitutions |= 1 /* TypeScriptSubstitutionFlags.ClassAliases */; - // We need to enable substitutions for identifiers. This allows us to - // substitute class names inside of a class declaration. - context.enableSubstitution(79 /* SyntaxKind.Identifier */); - // Keep track of class aliases. - classAliases = []; - } - } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2 /* TypeScriptSubstitutionFlags.NamespaceExports */) === 0) { enabledSubstitutions |= 2 /* TypeScriptSubstitutionFlags.NamespaceExports */; @@ -94127,32 +94750,9 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - return trySubstituteClassAlias(node) - || trySubstituteNamespaceExportedName(node) + return trySubstituteNamespaceExportedName(node) || node; } - function trySubstituteClassAlias(node) { - if (enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - // Also, when emitting statics for class expressions, we must substitute a class alias for - // constructor references in static property initializers. - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = classAliases[declaration.id]; // TODO: GH#18217 - if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; - } - } - } - } - return undefined; - } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { @@ -94290,7 +94890,7 @@ var ts; return visited; } function visitorWorker(node, valueIsDiscarded) { - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */) { + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */) { switch (node.kind) { case 226 /* SyntaxKind.ClassExpression */: case 257 /* SyntaxKind.ClassDeclaration */: @@ -94305,8 +94905,8 @@ var ts; return visitClassStaticBlockDeclaration(node); } } - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */ || - node.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */ && + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */ || + node.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */ && shouldTransformSuperInStaticInitializers && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { @@ -94446,7 +95046,7 @@ var ts; return node; } function visitMethodOrAccessorDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.isPrivateIdentifier(node.name)) { return ts.visitEachChild(node, classElementVisitor, context); } @@ -94458,7 +95058,7 @@ var ts; } var functionName = getHoistedFunctionName(node); if (functionName) { - getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return ts.isModifier(m) && !ts.isStaticModifier(m); }), node.asteriskToken, functionName, /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); } @@ -94482,7 +95082,7 @@ var ts; } } function visitPropertyDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (ts.isPrivateIdentifier(node.name)) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { if (ts.isStatic(node)) { @@ -94490,8 +95090,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + return factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); @@ -94513,9 +95112,7 @@ var ts; if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); if (initializerStatement) { - var staticBlock = factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([initializerStatement])); + var staticBlock = factory.createClassStaticBlockDeclaration(factory.createBlock([initializerStatement])); ts.setOriginalNode(staticBlock, node); ts.setCommentRange(staticBlock, node); // Set the comment range for the statement to an empty synthetic range @@ -94591,10 +95188,11 @@ var ts; } function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) { if (node.operator === 45 /* SyntaxKind.PlusPlusToken */ || node.operator === 46 /* SyntaxKind.MinusMinusToken */) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + var operand = ts.skipParentheses(node.operand); + if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(operand)) { var info = void 0; - if (info = accessPrivateIdentifier(node.operand.name)) { - var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression); + if (info = accessPrivateIdentifier(operand.name)) { + var receiver = ts.visitNode(operand.expression, visitor, ts.isExpression); var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; var expression = createPrivateIdentifierAccess(info, readExpression); var temp = ts.isPrefixUnaryExpression(node) || valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); @@ -94610,7 +95208,7 @@ var ts; } } else if (shouldTransformSuperInStaticInitializers && - ts.isSuperProperty(node.operand) && + ts.isSuperProperty(operand) && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { // converts `++super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = ++_a), _classTemp), _b)` @@ -94623,31 +95221,31 @@ var ts; // converts `super[f()]--` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = _b--), _classTemp), _c)` var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; if (facts & 1 /* ClassFacts.ClassWasDecorated */) { - var operand = visitInvalidSuperProperty(node.operand); + var expression = visitInvalidSuperProperty(operand); return ts.isPrefixUnaryExpression(node) ? - factory.updatePrefixUnaryExpression(node, operand) : - factory.updatePostfixUnaryExpression(node, operand); + factory.updatePrefixUnaryExpression(node, expression) : + factory.updatePostfixUnaryExpression(node, expression); } if (classConstructor && superClassReference) { var setterName = void 0; var getterName = void 0; - if (ts.isPropertyAccessExpression(node.operand)) { - if (ts.isIdentifier(node.operand.name)) { - getterName = setterName = factory.createStringLiteralFromNode(node.operand.name); + if (ts.isPropertyAccessExpression(operand)) { + if (ts.isIdentifier(operand.name)) { + getterName = setterName = factory.createStringLiteralFromNode(operand.name); } } else { - if (ts.isSimpleInlineableExpression(node.operand.argumentExpression)) { - getterName = setterName = node.operand.argumentExpression; + if (ts.isSimpleInlineableExpression(operand.argumentExpression)) { + getterName = setterName = operand.argumentExpression; } else { getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, ts.visitNode(node.operand.argumentExpression, visitor, ts.isExpression)); + setterName = factory.createAssignment(getterName, ts.visitNode(operand.argumentExpression, visitor, ts.isExpression)); } } if (setterName && getterName) { var expression = factory.createReflectGetCall(superClassReference, getterName, classConstructor); - ts.setTextRange(expression, node.operand); + ts.setTextRange(expression, operand); var temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); expression = ts.expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp); expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor); @@ -94880,13 +95478,13 @@ var ts; facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } if (ts.isPropertyDeclaration(member) || ts.isClassStaticBlockDeclaration(member)) { - if (shouldTransformThisInStaticInitializers && member.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */) { + if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */) { facts |= 8 /* ClassFacts.NeedsSubstitutionForThisInClassStaticField */; if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } } - if (shouldTransformSuperInStaticInitializers && member.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */) { + if (shouldTransformSuperInStaticInitializers && member.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */) { if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */ | 4 /* ClassFacts.NeedsClassSuperReference */; } @@ -94924,8 +95522,7 @@ var ts; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* SyntaxKind.NullKeyword */); var statements = [ - factory.updateClassDeclaration(node, - /*decorators*/ undefined, node.modifiers, node.name, + factory.updateClassDeclaration(node, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; if (pendingClassReferenceAssignment) { @@ -94977,7 +95574,7 @@ var ts; temp = createClassTempVar(); getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); } - var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, + var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || ts.isPrivateIdentifier(p.name); }); if (hasTransformableStatics || ts.some(pendingExpressions)) { @@ -95045,9 +95642,7 @@ var ts; members.push(constructor); } if (!shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(pendingExpressions)) { - members.push(factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([ + members.push(factory.createClassStaticBlockDeclaration(factory.createBlock([ factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)) ]))); pendingExpressions = undefined; @@ -95084,7 +95679,6 @@ var ts; return undefined; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { @@ -95471,10 +96065,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_3 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_3, node); - ts.setCommentRange(clone_3, node); - return clone_3; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -95836,6 +96430,1001 @@ var ts; })(ts || (ts = {})); /*@internal*/ var ts; +(function (ts) { + function createRuntimeTypeSerializer(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var currentLexicalScope; + var currentNameScope; + return { + serializeTypeNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeNode, node); }, + serializeTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeOfNode, node); }, + serializeParameterTypesOfNode: function (serializerContext, node, container) { return setSerializerContextAnd(serializerContext, serializeParameterTypesOfNode, node, container); }, + serializeReturnTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeReturnTypeOfNode, node); }, + }; + function setSerializerContextAnd(serializerContext, cb, node, arg) { + var savedCurrentLexicalScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + currentLexicalScope = serializerContext.currentLexicalScope; + currentNameScope = serializerContext.currentNameScope; + var result = arg === undefined ? cb(node) : cb(node, arg); + currentLexicalScope = savedCurrentLexicalScope; + currentNameScope = savedCurrentNameScope; + return result; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 167 /* SyntaxKind.PropertyDeclaration */: + case 164 /* SyntaxKind.Parameter */: + return serializeTypeNode(node.type); + case 173 /* SyntaxKind.SetAccessor */: + case 172 /* SyntaxKind.GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 169 /* SyntaxKind.MethodDeclaration */: + return ts.factory.createIdentifier("Function"); + default: + return ts.factory.createVoidZero(); + } + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.factory.createArrayLiteralExpression(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.factory.createIdentifier("Promise"); + } + return ts.factory.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.factory.createIdentifier("Object"); + } + node = ts.skipTypeParentheses(node); + switch (node.kind) { + case 114 /* SyntaxKind.VoidKeyword */: + case 153 /* SyntaxKind.UndefinedKeyword */: + case 143 /* SyntaxKind.NeverKeyword */: + return ts.factory.createVoidZero(); + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + return ts.factory.createIdentifier("Function"); + case 183 /* SyntaxKind.ArrayType */: + case 184 /* SyntaxKind.TupleType */: + return ts.factory.createIdentifier("Array"); + case 177 /* SyntaxKind.TypePredicate */: + return node.assertsModifier ? + ts.factory.createVoidZero() : + ts.factory.createIdentifier("Boolean"); + case 133 /* SyntaxKind.BooleanKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 198 /* SyntaxKind.TemplateLiteralType */: + case 150 /* SyntaxKind.StringKeyword */: + return ts.factory.createIdentifier("String"); + case 148 /* SyntaxKind.ObjectKeyword */: + return ts.factory.createIdentifier("Object"); + case 196 /* SyntaxKind.LiteralType */: + return serializeLiteralOfLiteralTypeNode(node.literal); + case 147 /* SyntaxKind.NumberKeyword */: + return ts.factory.createIdentifier("Number"); + case 158 /* SyntaxKind.BigIntKeyword */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 151 /* SyntaxKind.SymbolKeyword */: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case 178 /* SyntaxKind.TypeReference */: + return serializeTypeReferenceNode(node); + case 188 /* SyntaxKind.IntersectionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ true); + case 187 /* SyntaxKind.UnionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ false); + case 189 /* SyntaxKind.ConditionalType */: + return serializeUnionOrIntersectionConstituents([node.trueType, node.falseType], /*isIntersection*/ false); + case 193 /* SyntaxKind.TypeOperator */: + if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { + return serializeTypeNode(node.type); + } + break; + case 181 /* SyntaxKind.TypeQuery */: + case 194 /* SyntaxKind.IndexedAccessType */: + case 195 /* SyntaxKind.MappedType */: + case 182 /* SyntaxKind.TypeLiteral */: + case 130 /* SyntaxKind.AnyKeyword */: + case 155 /* SyntaxKind.UnknownKeyword */: + case 192 /* SyntaxKind.ThisType */: + case 200 /* SyntaxKind.ImportType */: + break; + // handle JSDoc types from an invalid parse + case 312 /* SyntaxKind.JSDocAllType */: + case 313 /* SyntaxKind.JSDocUnknownType */: + case 317 /* SyntaxKind.JSDocFunctionType */: + case 318 /* SyntaxKind.JSDocVariadicType */: + case 319 /* SyntaxKind.JSDocNamepathType */: + break; + case 314 /* SyntaxKind.JSDocNullableType */: + case 315 /* SyntaxKind.JSDocNonNullableType */: + case 316 /* SyntaxKind.JSDocOptionalType */: + return serializeTypeNode(node.type); + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.factory.createIdentifier("Object"); + } + function serializeLiteralOfLiteralTypeNode(node) { + switch (node.kind) { + case 10 /* SyntaxKind.StringLiteral */: + case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: + return ts.factory.createIdentifier("String"); + case 219 /* SyntaxKind.PrefixUnaryExpression */: { + var operand = node.operand; + switch (operand.kind) { + case 8 /* SyntaxKind.NumericLiteral */: + case 9 /* SyntaxKind.BigIntLiteral */: + return serializeLiteralOfLiteralTypeNode(operand); + default: + return ts.Debug.failBadSyntaxKind(operand); + } + } + case 8 /* SyntaxKind.NumericLiteral */: + return ts.factory.createIdentifier("Number"); + case 9 /* SyntaxKind.BigIntLiteral */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 110 /* SyntaxKind.TrueKeyword */: + case 95 /* SyntaxKind.FalseKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 104 /* SyntaxKind.NullKeyword */: + return ts.factory.createVoidZero(); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function serializeUnionOrIntersectionConstituents(types, isIntersection) { + // Note when updating logic here also update `getEntityNameForDecoratorMetadata` in checker.ts so that aliases can be marked as referenced + var serializedType; + for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { + var typeNode = types_22[_i]; + typeNode = ts.skipTypeParentheses(typeNode); + if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { + if (isIntersection) + return ts.factory.createVoidZero(); // Reduce to `never` in an intersection + continue; // Elide `never` in a union + } + if (typeNode.kind === 155 /* SyntaxKind.UnknownKeyword */) { + if (!isIntersection) + return ts.factory.createIdentifier("Object"); // Reduce to `unknown` in a union + continue; // Elide `unknown` in an intersection + } + if (typeNode.kind === 130 /* SyntaxKind.AnyKeyword */) { + return ts.factory.createIdentifier("Object"); // Reduce to `any` in a union or intersection + } + if (!strictNullChecks && ((ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */) || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedConstituent = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedConstituent; + } + // If there exists union that is not `void 0` expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + if (serializedType) { + // Different types + if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) { + return ts.factory.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedType = serializedConstituent; + } + } + // If we were able to find common type, use it + return serializedType !== null && serializedType !== void 0 ? serializedType : (ts.factory.createVoidZero()); // Fallback is only hit if all union constituents are null/undefined/never + } + function equateSerializedTypeNodes(left, right) { + return ( + // temp vars used in fallback + ts.isGeneratedIdentifier(left) ? ts.isGeneratedIdentifier(right) : + // entity names + ts.isIdentifier(left) ? ts.isIdentifier(right) + && left.escapedText === right.escapedText : + ts.isPropertyAccessExpression(left) ? ts.isPropertyAccessExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) + && equateSerializedTypeNodes(left.name, right.name) : + // `void 0` + ts.isVoidExpression(left) ? ts.isVoidExpression(right) + && ts.isNumericLiteral(left.expression) && left.expression.text === "0" + && ts.isNumericLiteral(right.expression) && right.expression.text === "0" : + // `"undefined"` or `"function"` in `typeof` checks + ts.isStringLiteral(left) ? ts.isStringLiteral(right) + && left.text === right.text : + // used in `typeof` checks for fallback + ts.isTypeOfExpression(left) ? ts.isTypeOfExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // parens in `typeof` checks with temps + ts.isParenthesizedExpression(left) ? ts.isParenthesizedExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // conditionals used in fallback + ts.isConditionalExpression(left) ? ts.isConditionalExpression(right) + && equateSerializedTypeNodes(left.condition, right.condition) + && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) + && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : + // logical binary and assignments used in fallback + ts.isBinaryExpression(left) ? ts.isBinaryExpression(right) + && left.operatorToken.kind === right.operatorToken.kind + && equateSerializedTypeNodes(left.left, right.left) + && equateSerializedTypeNodes(left.right, right.right) : + false); + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with decorator type metadata. + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope !== null && currentNameScope !== void 0 ? currentNameScope : currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.factory.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createAssignment(temp, serialized), "function"), + /*questionToken*/ undefined, temp, + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.factory.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.factory.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.factory.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.factory.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.factory.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.factory.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.factory.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.factory.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + /** + * Produces an expression that results in `right` if `left` is not undefined at runtime: + * + * ``` + * typeof left !== "undefined" && right + * ``` + * + * We use `typeof L !== "undefined"` (rather than `L !== undefined`) since `L` may not be declared. + * It's acceptable for this expression to result in `false` at runtime, as the result is intended to be + * further checked by any containing expression. + */ + function createCheckedValue(left, right) { + return ts.factory.createLogicalAnd(ts.factory.createStrictInequality(ts.factory.createTypeOfExpression(left), ts.factory.createStringLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 79 /* SyntaxKind.Identifier */) { + // A -> typeof A !== "undefined" && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 79 /* SyntaxKind.Identifier */) { + // A.B -> typeof A !== "undefined" && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== "undefined" && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createLogicalAnd(ts.factory.createLogicalAnd(left.left, ts.factory.createStrictInequality(ts.factory.createAssignment(temp, left.right), ts.factory.createVoidZero())), ts.factory.createPropertyAccessExpression(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); + name.original = undefined; + ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. + return name; + case 161 /* SyntaxKind.QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * @param node The qualified name to serialize. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); + } + function getGlobalConstructorWithFallback(name) { + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createIdentifier(name), "function"), + /*questionToken*/ undefined, ts.factory.createIdentifier(name), + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + } + function getGlobalConstructor(name, minLanguageVersion) { + return languageVersion < minLanguageVersion ? + getGlobalConstructorWithFallback(name) : + ts.factory.createIdentifier(name); + } + } + ts.createRuntimeTypeSerializer = createRuntimeTypeSerializer; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformLegacyDecorators(context) { + var factory = context.factory, emitHelpers = context.getEmitHelperFactory, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + // Save the previous transformation hooks. + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onSubstituteNode = onSubstituteNode; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function modifierVisitor(node) { + return ts.isDecorator(node) ? undefined : node; + } + function visitor(node) { + if (!(node.transformFlags & 33554432 /* TransformFlags.ContainsDecorators */)) { + return node; + } + switch (node.kind) { + case 165 /* SyntaxKind.Decorator */: + // Decorators are elided. They will be emitted as part of `visitClassDeclaration`. + return undefined; + case 257 /* SyntaxKind.ClassDeclaration */: + return visitClassDeclaration(node); + case 226 /* SyntaxKind.ClassExpression */: + return visitClassExpression(node); + case 171 /* SyntaxKind.Constructor */: + return visitConstructorDeclaration(node); + case 169 /* SyntaxKind.MethodDeclaration */: + return visitMethodDeclaration(node); + case 173 /* SyntaxKind.SetAccessor */: + return visitSetAccessorDeclaration(node); + case 172 /* SyntaxKind.GetAccessor */: + return visitGetAccessorDeclaration(node); + case 167 /* SyntaxKind.PropertyDeclaration */: + return visitPropertyDeclaration(node); + case 164 /* SyntaxKind.Parameter */: + return visitParameterDeclaration(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitClassDeclaration(node) { + if (!(ts.classOrConstructorParameterIsDecorated(node) || ts.childIsDecorated(node))) + return ts.visitEachChild(node, visitor, context); + var statements = ts.hasDecorators(node) ? + transformClassDeclarationWithClassDecorators(node, node.name) : + transformClassDeclarationWithoutClassDecorators(node, node.name); + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(factory.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statements[0], ts.getEmitFlags(statements[0]) | 4194304 /* EmitFlags.HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + function decoratorContainsPrivateIdentifierInExpression(decorator) { + return !!(decorator.transformFlags & 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); + } + function parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators) { + return ts.some(parameterDecorators, decoratorContainsPrivateIdentifierInExpression); + } + function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.canHaveDecorators(member)) + continue; + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) + return true; + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) + return true; + } + return false; + } + function transformDecoratorsOfClassElements(node, members) { + var decorationStatements = []; + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ false); + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ true); + if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { + members = ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], members, true), [ + factory.createClassStaticBlockDeclaration(factory.createBlock(decorationStatements, /*multiLine*/ true)) + ], false)), members); + decorationStatements = undefined; + } + return { decorationStatements: decorationStatements, members: members }; + } + /** + * Transforms a non-decorated class declaration. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + */ + function transformClassDeclarationWithoutClassDecorators(node, name) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var _a; + var modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var updated = factory.updateClassDeclaration(node, modifiers, name, + /*typeParameters*/ undefined, heritageClauses, members); + return ts.addRange([updated], decorationStatements); + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function transformClassDeclarationWithClassDecorators(node, name) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var _a; + var location = ts.moveRangePastModifiers(node); + var classAlias = getClassAliasIfNeeded(node); + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var classExpression = factory.createClassExpression( + /*modifiers*/ undefined, name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(declName, + /*exclamationToken*/ undefined, + /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* NodeFlags.Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + var statements = [statement]; + ts.addRange(statements, decorationStatements); + addConstructorDecorationStatement(statements, node); + return statements; + } + function visitClassExpression(node) { + // Legacy decorators were not supported on class expressions + return factory.updateClassExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)); + } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)); + } + function finishClassElement(updated, original) { + if (updated !== original) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, original); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(original)); + } + return updated; + } + function visitMethodDeclaration(node) { + return finishClassElement(factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitGetAccessorDeclaration(node) { + return finishClassElement(factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitSetAccessorDeclaration(node) { + return finishClassElement(factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitPropertyDeclaration(node) { + if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */)) { + return undefined; + } + return finishClassElement(factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function visitParameterDeclaration(node) { + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* EmitFlags.NoTrailingSourceMap */); + } + return updated; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), function (expr) { return factory.createExpressionStatement(expr); })); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStaticElement, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStaticElement === ts.isStatic(member); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, function (m) { return isDecoratedClassElement(m, isStatic, node); }); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { + var member = members_8[_i]; + expressions = ts.append(expressions, generateClassElementDecorationExpression(node, member)); + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); + var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ + ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? factory.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : factory.createNull() + : undefined; + var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(helper, ts.moveRangePastModifiers(member)); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); + var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); + ts.setTextRange(helper, decorator.expression); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Gets an expression that represents a property name (for decorated properties or enums). + * For a computed property, a name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isPrivateIdentifier(name)) { + return factory.createIdentifier(""); + } + else if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression) + ? factory.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return factory.createStringLiteral(ts.idText(name)); + } + else { + return factory.cloneNode(name); + } + } + function enableSubstitutionForClassAliases() { + if (!classAliases) { + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(79 /* SyntaxKind.Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.isStatic(member) + ? factory.getDeclarationName(node) + : getClassPrototype(node); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* EmitHint.Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + var _a; + return (_a = trySubstituteClassAlias(node)) !== null && _a !== void 0 ? _a : node; + } + function trySubstituteClassAlias(node) { + if (classAliases) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; + } + } + } + } + return undefined; + } + } + ts.transformLegacyDecorators = transformLegacyDecorators; +})(ts || (ts = {})); +/*@internal*/ +var ts; (function (ts) { var ES2017SubstitutionFlags; (function (ES2017SubstitutionFlags) { @@ -96054,8 +97643,7 @@ var ts; * @param node The node to visit. */ function visitMethodDeclaration(node) { - return factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ @@ -96071,8 +97659,7 @@ var ts; * @param node The node to visit. */ function visitFunctionDeclaration(node) { - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96087,7 +97674,7 @@ var ts; * @param node The node to visit. */ function visitFunctionExpression(node) { - return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96102,7 +97689,7 @@ var ts; * @param node The node to visit. */ function visitArrowFunction(node) { - return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96404,7 +97991,6 @@ var ts; /* typeParameters */ undefined, /* parameters */ [ factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "v", /* questionToken */ undefined, @@ -96684,7 +98270,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -96757,7 +98343,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* SyntaxKind.CommaToken */) { @@ -96788,7 +98374,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* FlattenLevel.ObjectRest */); @@ -96829,7 +98415,7 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } @@ -96848,7 +98434,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* HierarchyFacts.IterationStatementExcludes */, 2 /* HierarchyFacts.IterationStatementIncludes */); - if (node.initializer.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -96955,17 +98541,15 @@ var ts; function visitParameter(node) { if (parametersWithPrecedingObjectRestOrSpread === null || parametersWithPrecedingObjectRestOrSpread === void 0 ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); } - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); @@ -96979,7 +98563,7 @@ var ts; if (parameters) { parameters.add(parameter); } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { parameters = new ts.Set(); } } @@ -96990,8 +98574,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateConstructorDeclaration(node, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -97001,8 +98584,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), + var updated = factory.updateGetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -97013,8 +98595,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateSetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -97024,9 +98605,8 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ - ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + var updated = factory.updateMethodDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifierLike) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), @@ -97043,8 +98623,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + var updated = factory.updateFunctionDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined @@ -97202,7 +98781,7 @@ var ts; statements = ts.append(statements, statement); } } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { containsPrecedingObjectRestOrSpread = true; var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* FlattenLevel.ObjectRest */, factory.getGeneratedNameForNode(parameter), /*doNotRecordTempVariablesInLine*/ false, @@ -97699,7 +99278,7 @@ var ts; var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1]; if (ts.isExternalModule(node)) { // Add `import` statement - var importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); + var importStatement = factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); ts.setParentRecursive(importStatement, /*incremental*/ false); statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement); } @@ -97930,22 +99509,29 @@ var ts; if (node === undefined) { return factory.createTrue(); } - else if (node.kind === 10 /* SyntaxKind.StringLiteral */) { + if (node.kind === 10 /* SyntaxKind.StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 288 /* SyntaxKind.JsxExpression */) { + if (node.kind === 288 /* SyntaxKind.JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } return ts.visitNode(node.expression, visitor, ts.isExpression); } - else { - return ts.Debug.failBadSyntaxKind(node); + if (ts.isJsxElement(node)) { + return visitJsxElement(node, /*isChild*/ false); + } + if (ts.isJsxSelfClosingElement(node)) { + return visitJsxSelfClosingElement(node, /*isChild*/ false); } + if (ts.isJsxFragment(node)) { + return visitJsxFragment(node, /*isChild*/ false); + } + return ts.Debug.failBadSyntaxKind(node); } function visitJsxText(node) { var fixed = fixupWhitespaceAndDecodeEntities(node.text); @@ -98567,7 +100153,7 @@ var ts; && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -98940,7 +100526,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], + /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], /*type*/ undefined, transformClassBody(node, extendsClauseElement)); // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier @@ -99018,7 +100604,6 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), @@ -99131,7 +100716,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass || superCallExpression) { - if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */)) { + if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -99283,7 +100868,6 @@ var ts; // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, @@ -99295,7 +100879,6 @@ var ts; else if (node.initializer) { // Initializers are elided return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.name, /*questionToken*/ undefined, @@ -99676,7 +101259,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { + if (node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { hierarchyFacts |= 65536 /* HierarchyFacts.CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -99735,8 +101318,7 @@ var ts; : node.name; exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -99962,7 +101544,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */) { + if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */) { if (node.flags & 3 /* NodeFlags.BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -99975,7 +101557,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */ + if (node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -100299,7 +101881,7 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 524288 /* TransformFlags.ContainsYield */ && + if ((property.transformFlags & 1048576 /* TransformFlags.ContainsYield */ && hierarchyFacts & 4 /* HierarchyFacts.AsyncFunctionBody */) || (hasComputed = ts.Debug.checkDefined(property.name).kind === 162 /* SyntaxKind.ComputedPropertyName */)) { numInitialProperties = i; @@ -100572,7 +102154,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 0 /* EmitFlags.None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -100687,7 +102269,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 524288 /* EmitFlags.ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -100830,7 +102412,7 @@ var ts; } } else { - loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + loopParameters.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); var checkFlags = resolver.getNodeCheckFlags(decl); if (checkFlags & 4194304 /* NodeCheckFlags.NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { var outParamName = factory.createUniqueName("out_" + ts.idText(name)); @@ -100987,10 +102569,10 @@ var ts; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); if (node.kind === 172 /* SyntaxKind.GetAccessor */) { - updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + updated = factory.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); } else { - updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body); + updated = factory.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; @@ -101169,7 +102751,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */ || + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */ || node.expression.kind === 106 /* SyntaxKind.SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -101177,7 +102759,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* EmitFlags.NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -102019,10 +103601,10 @@ var ts; case 247 /* SyntaxKind.ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -102086,8 +103668,7 @@ var ts; function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. if (node.asteriskToken) { - node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, node.modifiers, + node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(node.modifiers, /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body)), @@ -102227,7 +103808,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -103285,7 +104866,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + return !!node && (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -103916,7 +105497,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], /*type*/ undefined, factory.createBlock(buildResult, /*multiLine*/ buildResult.length > 0)), 524288 /* EmitFlags.ReuseTempVariableScope */)); } @@ -104334,7 +105915,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */ || + node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -104435,8 +106016,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ], false))) @@ -104457,7 +106038,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], /*type*/ undefined, ts.setTextRange(factory.createBlock([ factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([ factory.createVariableStatement( @@ -104506,8 +106087,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ])) @@ -104536,7 +106117,7 @@ var ts; var amdDependency = _a[_i]; if (amdDependency.name) { aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); } else { unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); @@ -104557,7 +106138,7 @@ var ts; // This is so that when printer will not substitute the identifier ts.setEmitFlags(importAliasName, 4 /* EmitFlags.NoSubstitution */); aliasedModuleNames.push(externalModuleName); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); } else { unaliasedModuleNames.push(externalModuleName); @@ -104671,7 +106252,7 @@ var ts; function visitorWorker(node, valueIsDiscarded) { // This visitor does not need to descend into the tree if there is no dynamic import, destructuring assignment, or update expression // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & (4194304 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (8388608 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -104822,7 +106403,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), visitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -104877,8 +106458,8 @@ var ts; var resolve = factory.createUniqueName("resolve"); var reject = factory.createUniqueName("reject"); var parameters = [ - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) ]; var body = factory.createBlock([ factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), @@ -105166,8 +106747,7 @@ var ts; function visitFunctionDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor), /*type*/ undefined, ts.visitEachChild(node.body, visitor, context)), /*location*/ node), @@ -105194,8 +106774,7 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor), ts.visitNodes(node.members, visitor)), node), node)); } else { @@ -105809,7 +107388,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -105842,8 +107421,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) ], /*type*/ undefined, moduleBodyBlock); // Write the call to `System.register` @@ -105978,7 +107557,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 1048576 /* TransformFlags.ContainsAwait */ ? + var modifiers = node.transformFlags & 2097152 /* TransformFlags.ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* ModifierFlags.Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -106065,10 +107644,9 @@ var ts; /*typeArguments*/ undefined, [n]))); } return factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, exportStarFunction, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], /*type*/ undefined, factory.createBlock([ factory.createVariableStatement( /*modifiers*/ undefined, factory.createVariableDeclarationList([ @@ -106159,7 +107737,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true))); } return factory.createArrayLiteralExpression(setters, /*multiLine*/ true); @@ -106257,7 +107835,7 @@ var ts; */ function visitFunctionDeclaration(node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock))); } @@ -106285,8 +107863,7 @@ var ts; var name = factory.getLocalName(node); hoistVariableDeclaration(name); // Rewrite the class declaration into an assignment of a class expression. - statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, visitor, ts.isDecorator), - /*modifiers*/ undefined, node.name, + statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -106887,7 +108464,7 @@ var ts; * @param node The node to visit. */ function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 4194304 /* TransformFlags.ContainsDynamicImport */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 8388608 /* TransformFlags.ContainsDynamicImport */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -107334,7 +108911,7 @@ var ts; // Though an error in es2020 modules, in node-flavor es2020 modules, we can helpfully transform this to a synthetic `require` call // To give easy access to a synchronous `require` in node-flavor esm. We do the transform even in scenarios where we error, but `import.meta.url` // is available, just because the output is reasonable for a node-like runtime. - return ts.getEmitScriptTarget(compilerOptions) >= ts.ModuleKind.ES2020 ? visitImportEqualsDeclaration(node) : undefined; + return ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.Node16 ? visitImportEqualsDeclaration(node) : undefined; case 271 /* SyntaxKind.ExportAssignment */: return visitExportAssignment(node); case 272 /* SyntaxKind.ExportDeclaration */: @@ -107357,7 +108934,6 @@ var ts; if (!importRequireStatements) { var createRequireName = factory.createUniqueName("_createRequire", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */); var importStatement = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamedImports([ @@ -107400,7 +108976,6 @@ var ts; function appendExportsOfImportEqualsDeclaration(statements, node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { statements = ts.append(statements, factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, ts.idText(node.name))]))); } return statements; @@ -107421,13 +108996,11 @@ var ts; var oldIdentifier = node.exportClause.name; var synthName = factory.getGeneratedNameForNode(oldIdentifier); var importDecl = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier, node.assertClause); ts.setOriginalNode(importDecl, node.exportClause); var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, synthName, oldIdentifier)])); ts.setOriginalNode(exportDecl, node); @@ -107679,7 +109252,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.SyntaxKind[node.kind])); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(node.kind))); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 254 /* SyntaxKind.VariableDeclaration */ || node.kind === 203 /* SyntaxKind.BindingElement */) { @@ -107890,7 +109463,7 @@ var ts; ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1; default: - return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.SyntaxKind[node.parent.kind])); + return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind))); } } function getTypeParameterConstraintVisibilityError() { @@ -108055,7 +109628,8 @@ var ts; trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, reportNonlocalAugmentation: reportNonlocalAugmentation, - reportNonSerializableProperty: reportNonSerializableProperty + reportNonSerializableProperty: reportNonSerializableProperty, + reportImportTypeNodeResolutionModeOverride: reportImportTypeNodeResolutionModeOverride, }; var errorNameNode; var errorFallbackNode; @@ -108182,6 +109756,11 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName)); } } + function reportImportTypeNodeResolutionModeOverride() { + if (!ts.isNightly() && (errorNameNode || errorFallbackNode)) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ @@ -108221,7 +109800,7 @@ var ts; resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -108364,7 +109943,7 @@ var ts; }); return ret; } - function filterBindingPatternInitializers(name) { + function filterBindingPatternInitializersAndRenamings(name) { if (name.kind === 79 /* SyntaxKind.Identifier */) { return name; } @@ -108380,7 +109959,12 @@ var ts; if (elem.kind === 227 /* SyntaxKind.OmittedExpression */) { return elem; } - return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + if (elem.propertyName && ts.isIdentifier(elem.propertyName) && ts.isIdentifier(elem.name) && !elem.symbol.isReferenced) { + // Unnecessary property renaming is forbidden in types, so remove renaming + return factory.updateBindingElement(elem, elem.dotDotDotToken, + /* propertyName */ undefined, elem.propertyName, shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializersAndRenamings(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); } } function ensureParameter(p, modifierMask, type) { @@ -108389,8 +109973,7 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } - var newParam = factory.updateParameterDeclaration(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + var newParam = factory.updateParameterDeclaration(p, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -108441,7 +110024,7 @@ var ts; if (node.kind === 164 /* SyntaxKind.Parameter */ || node.kind === 167 /* SyntaxKind.PropertyDeclaration */ || node.kind === 166 /* SyntaxKind.PropertySignature */) { - if (!node.initializer) + if (ts.isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } @@ -108527,7 +110110,6 @@ var ts; } if (!newValueParameter) { newValueParameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "value"); } @@ -108585,8 +110167,7 @@ var ts; if (decl.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); - return factory.updateImportEqualsDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + return factory.updateImportEqualsDeclaration(decl, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } else { var oldDiag = getSymbolAccessibilityDiagnostic; @@ -108599,31 +110180,28 @@ var ts; function transformImportDeclaration(decl) { if (!decl.importClause) { // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // The `importClause` visibility corresponds to the default's visibility. var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; if (!decl.importClause.namedBindings) { // No named bindings (either namespace or list), meaning the import is just default or should be elided - return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, + return visibleDefaultBinding && factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } if (decl.importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; - return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; + return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; } // Named imports (optionally with visible default) var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); if ((bindingList && bindingList.length) || visibleDefaultBinding) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Augmentation of export depends on import if (resolver.isImportRequiredByAugmentation(decl)) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, + return factory.updateImportDeclaration(decl, decl.modifiers, /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Nothing visible @@ -108632,7 +110210,7 @@ var ts; var mode = ts.getResolutionModeOverrideForClause(assertClause); if (mode !== undefined) { if (!ts.isNightly()) { - context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); } return assertClause; } @@ -108656,7 +110234,7 @@ var ts; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.Debug.formatSyntaxKind(i.kind))); } var priorNeedsDeclare = needsDeclare; needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); @@ -108720,7 +110298,7 @@ var ts; if (ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)) { if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; // Elide all but the first overload - return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + return cleanup(factory.createPropertyDeclaration(ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); } } if (canProduceDiagnostic && !suppressNewDiagnosticContexts) { @@ -108752,7 +110330,6 @@ var ts; case 171 /* SyntaxKind.Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* ModifierFlags.None */), /*body*/ undefined); return cleanup(ctor); @@ -108761,8 +110338,7 @@ var ts; if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - var sig = factory.createMethodDeclaration( - /*decorators*/ undefined, ensureModifiers(input), + var sig = factory.createMethodDeclaration(ensureModifiers(input), /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined); return cleanup(sig); @@ -108772,24 +110348,21 @@ var ts; return cleanup(/*returnValue*/ undefined); } var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); - return cleanup(factory.updateGetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), + return cleanup(factory.updateGetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), /*body*/ undefined)); } case 173 /* SyntaxKind.SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updateSetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), + return cleanup(factory.updateSetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), /*body*/ undefined)); } case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updatePropertyDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); + return cleanup(factory.updatePropertyDeclaration(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); case 166 /* SyntaxKind.PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); @@ -108805,8 +110378,7 @@ var ts; return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } case 176 /* SyntaxKind.IndexSignature */: { - return cleanup(factory.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); + return cleanup(factory.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); } case 254 /* SyntaxKind.VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { @@ -108845,7 +110417,7 @@ var ts; return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.assertions, input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); } - default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.SyntaxKind[input.kind])); + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(input.kind))); } } if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) { @@ -108889,8 +110461,7 @@ var ts; resultHasScopeMarker = true; // Always visible if the parent node isn't dropped for being not visible // Rewrite external module names if necessary - return factory.updateExportDeclaration(input, - /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); + return factory.updateExportDeclaration(input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); } case 271 /* SyntaxKind.ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible @@ -108913,7 +110484,7 @@ var ts; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* NodeFlags.Const */)); preserveJsDoc(statement, input); ts.removeAllComments(input); - return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + return [statement, factory.updateExportAssignment(input, input.modifiers, newId)]; } } } @@ -108928,7 +110499,7 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (125951 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (257023 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { @@ -108964,22 +110535,19 @@ var ts; var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 259 /* SyntaxKind.TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all - return cleanup(factory.updateTypeAliasDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + return cleanup(factory.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 258 /* SyntaxKind.InterfaceDeclaration */: { - return cleanup(factory.updateInterfaceDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + return cleanup(factory.updateInterfaceDeclaration(input, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 256 /* SyntaxKind.FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - var clean = cleanup(factory.updateFunctionDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), + var clean = cleanup(factory.updateFunctionDeclaration(input, ensureModifiers(input), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); if (clean && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { var props = resolver.getPropertiesOfContainerFunction(input); // Use parseNodeFactory so it is usable as an enclosing declaration - var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace_1, enclosingDeclaration); fakespace_1.locals = ts.createSymbolTable(props); fakespace_1.symbol = props[0].parent; @@ -109005,26 +110573,22 @@ var ts; } else { declarations.push(factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) { var gen = _a[0], exp = _a[1]; return factory.createExportSpecifier(/*isTypeOnly*/ false, gen, exp); })))); } - var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); + var namespaceDecl = factory.createModuleDeclaration(ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); if (!ts.hasEffectiveModifier(clean, 512 /* ModifierFlags.Default */)) { return [clean, namespaceDecl]; } var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ModifierFlags.ExportDefault */) | 2 /* ModifierFlags.Ambient */); - var cleanDeclaration = factory.updateFunctionDeclaration(clean, - /*decorators*/ undefined, modifiers, + var cleanDeclaration = factory.updateFunctionDeclaration(clean, modifiers, /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, /*body*/ undefined); - var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, - /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body); + var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, modifiers, namespaceDecl.name, namespaceDecl.body); var exportDefaultDeclaration = factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, namespaceDecl.name); if (ts.isSourceFile(input.parent)) { @@ -109067,8 +110631,7 @@ var ts; needsScopeFixMarker = oldNeedsScopeFix; resultHasScopeMarker = oldHasScopeFix; var mods = ensureModifiers(input); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; @@ -109079,8 +110642,7 @@ var ts; var id = ts.getOriginalNodeId(inner); // TODO: GH#18217 var body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, input.name, body)); } } case 257 /* SyntaxKind.ClassDeclaration */: { @@ -109097,8 +110659,7 @@ var ts; return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 79 /* SyntaxKind.Identifier */) { - return preserveJsDoc(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + return preserveJsDoc(factory.createPropertyDeclaration(ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } else { // Pattern - this is currently an error, but we emit declarations for it somewhat correctly @@ -109114,8 +110675,7 @@ var ts; elems = ts.concatenate(elems, walkBindingPattern(elem.name)); } elems = elems || []; - elems.push(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), elem.name, + elems.push(factory.createPropertyDeclaration(ensureModifiers(param), elem.name, /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), /*initializer*/ undefined)); } @@ -109129,7 +110689,6 @@ var ts; // Prevents other classes with the same public members from being used in place of the current class var privateIdentifier = hasPrivateIdentifier ? [ factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"), /*questionToken*/ undefined, /*type*/ undefined, @@ -109159,20 +110718,18 @@ var ts; } return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 104 /* SyntaxKind.NullKeyword */; })), visitDeclarationSubtree)); })); - return [statement, cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + return [statement, cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 } else { var heritageClauses = transformHeritageClauses(input.heritageClauses); - return cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + return cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members)); } } case 237 /* SyntaxKind.VariableStatement */: { return cleanup(transformVariableStatement(input)); } case 260 /* SyntaxKind.EnumDeclaration */: { - return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(factory.updateEnumDeclaration(input, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; // Rewrite enum values to their constants, if available @@ -109182,7 +110739,7 @@ var ts; } } // Anything left unhandled is an error, so this should be unreachable - return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.SyntaxKind[input.kind])); + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.Debug.formatSyntaxKind(input.kind))); function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; @@ -109256,12 +110813,12 @@ var ts; var currentFlags = ts.getEffectiveModifierFlags(node); var newFlags = ensureModifierFlags(node); if (currentFlags === newFlags) { - return node.modifiers; + return ts.visitArray(node.modifiers, function (n) { return ts.tryCast(n, ts.isModifier); }, ts.isModifier); } return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 125951 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files + var mask = 257023 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* ModifierFlags.Ambient */ : 0 /* ModifierFlags.None */; var parentIsFile = node.parent.kind === 305 /* SyntaxKind.SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { @@ -109302,7 +110859,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 125951 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } + if (modifierMask === void 0) { modifierMask = 257023 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* ModifierFlags.None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* ModifierFlags.Default */ && !(flags & 1 /* ModifierFlags.Export */)) { @@ -109424,6 +110981,7 @@ var ts; var transformers = []; ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory)); transformers.push(ts.transformTypeScript); + transformers.push(ts.transformLegacyDecorators); transformers.push(ts.transformClassFields); if (ts.getJSXTransformEnabled(compilerOptions)) { transformers.push(ts.transformJsx); @@ -110184,7 +111742,6 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; - var exportedModulesFromDeclarationEmit; // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); @@ -110194,7 +111751,6 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, - exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath; @@ -110248,14 +111804,16 @@ var ts; return; } var version = ts.version; // Extracted into a const so the form is stable between namespace and module - ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false); + var buildInfo = { bundle: bundle, program: program, version: version }; + // Pass buildinfo as additional data to avoid having to reparse + ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText(buildInfo), /*writeByteOrderMark*/ false, /*sourceFiles*/ undefined, { buildInfo: buildInfo }); } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) { if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) { return; } // Make sure not to write js file and source map file if any of them cannot be written - if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit) { emitSkipped = true; return; } @@ -110284,7 +111842,7 @@ var ts; substituteNode: transform.substituteNode, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); if (bundleBuildInfo) @@ -110320,7 +111878,7 @@ var ts; noEmitHelpers: true, module: compilerOptions.module, target: compilerOptions.target, - sourceMap: compilerOptions.sourceMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, inlineSourceMap: compilerOptions.inlineSourceMap, extendedDiagnostics: compilerOptions.extendedDiagnostics, onlyPrintJsDocStyle: true, @@ -110340,17 +111898,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: !forceDtsEmit && compilerOptions.declarationMap, + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform, declarationPrinter, { + sourceMap: printerOptions.sourceMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 305 /* SyntaxKind.SourceFile */) { - var sourceFile = declarationTransform.transformed[0]; - exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; - } } declarationTransform.dispose(); if (bundleBuildInfo) @@ -110369,7 +111923,8 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, mapOptions) { + var sourceFileOrBundle = transform.transformed[0]; var bundle = sourceFileOrBundle.kind === 306 /* SyntaxKind.Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 305 /* SyntaxKind.SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; @@ -110402,13 +111957,20 @@ var ts; if (sourceMapFilePath) { var sourceMap = sourceMapGenerator.toString(); ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + if (printer.bundleFileInfo) + printer.bundleFileInfo.mapHash = ts.computeSignature(sourceMap, ts.maybeBind(host, host.createHash)); } } else { writer.writeLine(); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos }); + var text = writer.getText(); + ts.writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos, diagnostics: transform.diagnostics }); + // We store the hash of the text written in the buildinfo to ensure that text of the referenced d.ts file is same as whats in the buildinfo + // This is needed because incremental can be toggled between two runs and we might use stale file text to do text manipulation in prepend mode + if (printer.bundleFileInfo) + printer.bundleFileInfo.hash = ts.computeSignature(text, ts.maybeBind(host, host.createHash)); // Reset state writer.clear(); } @@ -110551,34 +112113,56 @@ var ts; } /*@internal*/ function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) { + var createHash = ts.maybeBind(host, host.createHash); var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath)); - if (!buildInfoText) + var buildInfo; + if (host.getBuildInfo) { + // If host directly provides buildinfo we can get it directly. This allows host to cache the buildinfo + var hostBuildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); + if (!hostBuildInfo) + return buildInfoPath; + buildInfo = hostBuildInfo; + } + else { + var buildInfoText = host.readFile(buildInfoPath); + if (!buildInfoText) + return buildInfoPath; + buildInfo = getBuildInfo(buildInfoText); + } + if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationFilePath && !buildInfo.bundle.dts)) return buildInfoPath; var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath)); if (!jsFileText) return jsFilePath; + // If the jsFileText is not same has what it was created with, tsbuildinfo is stale so dont use it + if (ts.computeSignature(jsFileText, createHash) !== buildInfo.bundle.js.hash) + return jsFilePath; var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); // error if no source map or for now if inline sourcemap if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap) return sourceMapFilePath || "inline sourcemap decoding"; + if (sourceMapFilePath && ts.computeSignature(sourceMapText, createHash) !== buildInfo.bundle.js.mapHash) + return sourceMapFilePath; // read declaration text var declarationText = declarationFilePath && host.readFile(declarationFilePath); if (declarationFilePath && !declarationText) return declarationFilePath; + if (declarationFilePath && ts.computeSignature(declarationText, createHash) !== buildInfo.bundle.dts.hash) + return declarationFilePath; var declarationMapText = declarationMapPath && host.readFile(declarationMapPath); // error if no source map or for now if inline sourcemap if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding"; - var buildInfo = getBuildInfo(buildInfoText); - if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts)) - return buildInfoPath; + if (declarationMapPath && ts.computeSignature(declarationMapText, createHash) !== buildInfo.bundle.dts.mapHash) + return declarationMapPath; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, /*onlyOwnText*/ true); var outputFiles = []; var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); }); var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host); + var changedDtsText; + var changedDtsData; var emitHost = { getPrependNodes: ts.memoize(function () { return __spreadArray(__spreadArray([], prependNodes, true), [ownPrependInput], false); }), getCanonicalFileName: host.getCanonicalFileName, @@ -110594,7 +112178,7 @@ var ts; getResolvedProjectReferenceToRedirect: ts.returnUndefined, getProjectReferenceRedirect: ts.returnUndefined, isSourceOfProjectReferenceRedirect: ts.returnFalse, - writeFile: function (name, text, writeByteOrderMark) { + writeFile: function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { switch (name) { case jsFilePath: if (jsFileText === text) @@ -110605,8 +112189,12 @@ var ts; return; break; case buildInfoPath: - var newBuildInfo = getBuildInfo(text); + var newBuildInfo = data.buildInfo; newBuildInfo.program = buildInfo.program; + if (newBuildInfo.program && changedDtsText !== undefined && config.options.composite) { + // Update the output signature + newBuildInfo.program.outSignature = ts.computeSignature(changedDtsText, createHash, changedDtsData); + } // Update sourceFileInfo var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles; newBuildInfo.bundle.js.sources = js.sources; @@ -110614,11 +112202,13 @@ var ts; newBuildInfo.bundle.dts.sources = dts.sources; } newBuildInfo.bundle.sourceFiles = sourceFiles; - outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark }); + outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark, buildInfo: newBuildInfo }); return; case declarationFilePath: if (declarationText === text) return; + changedDtsText = text; + changedDtsData = data; break; case declarationMapPath: if (declarationMapText === text) @@ -110637,6 +112227,7 @@ var ts; getSourceFileFromReference: ts.returnUndefined, redirectTargetsMap: ts.createMultiMap(), getFileIncludeReasons: ts.notImplemented, + createHash: createHash, }; emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers)); @@ -111724,8 +113315,7 @@ var ts; } } function emitParameter(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); @@ -111736,7 +113326,7 @@ var ts; emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); @@ -111746,7 +113336,6 @@ var ts; // Type members // function emitPropertySignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); @@ -111754,8 +113343,7 @@ var ts; writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); emit(node.exclamationToken); @@ -111765,7 +113353,6 @@ var ts; } function emitMethodSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); @@ -111776,16 +113363,13 @@ var ts; popNameGenerationScope(node); } function emitMethodDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.asteriskToken); emit(node.name); emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitClassStaticBlockDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("static"); emitBlockFunctionBody(node.body); } @@ -111795,8 +113379,7 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword(node.kind === 172 /* SyntaxKind.GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); @@ -111804,8 +113387,6 @@ var ts; } function emitCallSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); @@ -111814,8 +113395,6 @@ var ts; } function emitConstructSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -111825,7 +113404,6 @@ var ts; popNameGenerationScope(node); } function emitIndexSignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); @@ -112218,7 +113796,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitSignatureAndBody(node, emitArrowFunctionHead); } @@ -112699,7 +114276,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitFunctionDeclarationOrExpression(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); emit(node.asteriskToken); @@ -112757,8 +114333,8 @@ var ts; if (!ts.nodeIsSynthesized(body) && currentSourceFile && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { return false; } - if (getLeadingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */) - || getClosingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */)) { + if (getLeadingLineTerminatorCount(body, ts.firstOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */) + || getClosingLineTerminatorCount(body, ts.lastOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */, body.statements)) { return false; } var previousStatement; @@ -112806,8 +114382,7 @@ var ts; } function emitClassDeclarationOrExpression(node) { ts.forEach(node.members, generateMemberNames); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword("class"); if (node.name) { writeSpace(); @@ -112828,7 +114403,6 @@ var ts; } } function emitInterfaceDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("interface"); writeSpace(); @@ -112841,7 +114415,6 @@ var ts; writePunctuation("}"); } function emitTypeAliasDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("type"); writeSpace(); @@ -113468,8 +115041,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* BundleFileSectionKind.Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_24 = types; _d < types_24.length; _d++) { - var directive = types_24[_d]; + for (var _d = 0, types_23 = types; _d < types_23.length; _d++) { + var directive = types_23[_d]; var pos = writer.getTextPos(); var resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.impliedNodeFormat) ? "resolution-mode=\"".concat(directive.resolutionMode === ts.ModuleKind.ESNext ? "import" : "require", "\"") @@ -113643,12 +115216,52 @@ var ts; emit(node); write = savedWrite; } - function emitModifiers(node, modifiers) { - if (modifiers && modifiers.length) { - emitList(node, modifiers, 262656 /* ListFormat.Modifiers */); - writeSpace(); + function emitDecoratorsAndModifiers(node, modifiers) { + if (modifiers === null || modifiers === void 0 ? void 0 : modifiers.length) { + if (ts.every(modifiers, ts.isModifier)) { + // if all modifier-likes are `Modifier`, simply emit the array as modifiers. + return emitModifiers(node, modifiers); + } + if (ts.every(modifiers, ts.isDecorator)) { + // if all modifier-likes are `Decorator`, simply emit the array as decorators. + return emitDecorators(node, modifiers); + } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(modifiers); + // partition modifiers into contiguous chunks of `Modifier` or `Decorator` + var lastMode = void 0; + var mode = void 0; + var start = 0; + var pos = 0; + while (start < modifiers.length) { + while (pos < modifiers.length) { + var modifier = modifiers[pos]; + mode = ts.isDecorator(modifier) ? "decorators" : "modifiers"; + if (lastMode === undefined) { + lastMode = mode; + } + else if (mode !== lastMode) { + break; + } + pos++; + } + var textRange = { pos: -1, end: -1 }; + if (start === 0) + textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) + textRange.end = modifiers.end; + emitNodeListItems(emit, node, modifiers, lastMode === "modifiers" ? 2359808 /* ListFormat.Modifiers */ : 2146305 /* ListFormat.Decorators */, + /*parenthesizerRule*/ undefined, start, pos - start, + /*hasTrailingComma*/ false, textRange); + start = pos; + lastMode = mode; + pos++; + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(modifiers); } } + function emitModifiers(node, modifiers) { + emitList(node, modifiers, 2359808 /* ListFormat.Modifiers */); + } function emitTypeAnnotation(node) { if (node) { writePunctuation(":"); @@ -113726,11 +115339,9 @@ var ts; && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head && !parentNode.type // arrow function may not have return type annotation - && !ts.some(parentNode.decorators) // parent may not have decorators - && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.modifiers) // parent may not have decorators or modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters - && !ts.some(parameter.decorators) // parameter may not have decorators - && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !ts.some(parameter.modifiers) // parameter may not have decorators or modifiers && !parameter.dotDotDotToken // parameter may not be rest && !parameter.questionToken // parameter may not be optional && !parameter.type // parameter may not have a type annotation @@ -113785,12 +115396,8 @@ var ts; } var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 32768 /* ListFormat.OptionalIfEmpty */) { - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); return; } if (format & 15360 /* ListFormat.BracketsMask */) { @@ -113799,9 +115406,7 @@ var ts; emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); if (isEmpty) { // Write a line terminator if the parent node was multi-line if (format & 1 /* ListFormat.MultiLine */ && !(preserveSourceNewlines && (!parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { @@ -113812,123 +115417,128 @@ var ts; } } else { - ts.Debug.type(children); - // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; - var shouldEmitInterveningComments = mayEmitInterveningComments; - var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217 - if (leadingLineTerminatorCount) { - writeLine(leadingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { - writeSpace(); - } - // Increase the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { - increaseIndent(); + emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, children.hasTrailingComma, children); + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); + if (format & 15360 /* ListFormat.BracketsMask */) { + if (isEmpty && children) { + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } - var emitListItem = getEmitListItem(emit, parenthesizerRule); - // Emit each child. - var previousSibling = void 0; - var previousSourceFileTextKind = void 0; - var shouldDecreaseIndentAfterEmit = false; - for (var i = 0; i < count; i++) { - var child = children[start + i]; - // Write the delimiter if this is not the first node. - if (format & 32 /* ListFormat.AsteriskDelimited */) { - // always write JSDoc in the format "\n *" - writeLine(); - writeDelimiter(format); - } - else if (previousSibling) { - // i.e - // function commentedParameters( - // /* Parameter a */ - // a - // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline - // , - if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { - emitLeadingCommentsOfPosition(previousSibling.end); - } - writeDelimiter(format); - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write either a line terminator or whitespace to separate the elements. - var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); - if (separatingLineTerminatorCount > 0) { - // If a synthesized node in a single-line list starts on a new - // line, we should increase the indent. - if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { - increaseIndent(); - shouldDecreaseIndentAfterEmit = true; - } - writeLine(separatingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { - writeSpace(); - } - } - // Emit this child. - previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); - if (shouldEmitInterveningComments) { - var commentRange = ts.getCommentRange(child); - emitTrailingCommentsOfPosition(commentRange.pos); - } - else { - shouldEmitInterveningComments = mayEmitInterveningComments; - } - nextListElementPos = child.pos; - emitListItem(child, emit, parenthesizerRule, i); - if (shouldDecreaseIndentAfterEmit) { - decreaseIndent(); - shouldDecreaseIndentAfterEmit = false; + writePunctuation(getClosingBracket(format)); + } + } + /** + * Emits a list without brackets or raising events. + * + * NOTE: You probably don't want to call this directly and should be using `emitList` or `emitExpressionList` instead. + */ + function emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, hasTrailingComma, childrenTextRange) { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children[start], format); + if (leadingLineTerminatorCount) { + writeLine(leadingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + increaseIndent(); + } + var emitListItem = getEmitListItem(emit, parenthesizerRule); + // Emit each child. + var previousSibling; + var previousSourceFileTextKind; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* ListFormat.AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write either a line terminator or whitespace to separate the elements. + var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); + if (separatingLineTerminatorCount > 0) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(separatingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { + writeSpace(); } - previousSibling = child; } - // Write a trailing comma, if requested. - var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; - var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); - var hasTrailingComma = (children === null || children === void 0 ? void 0 : children.hasTrailingComma) && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); - if (hasTrailingComma) { - if (previousSibling && !skipTrailingComments) { - emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); - } - else { - writePunctuation(","); - } + // Emit this child. + previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); + if (shouldEmitInterveningComments) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); } - // Emit any trailing comment of the last element in the list - // i.e - // var array = [... - // 2 - // /* end of element 2 */ - // ]; - if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { - emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); - } - // Decrease the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + nextListElementPos = child.pos; + emitListItem(child, emit, parenthesizerRule, i); + if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; } - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write the closing line terminator or closing whitespace. - var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format); - if (closingLineTerminatorCount) { - writeLine(closingLineTerminatorCount); + previousSibling = child; + } + // Write a trailing comma, if requested. + var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; + var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); + var emitTrailingComma = hasTrailingComma && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); + if (emitTrailingComma) { + if (previousSibling && !skipTrailingComments) { + emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); } - else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { - writeSpace(); + else { + writePunctuation(","); } } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { + emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange === null || childrenTextRange === void 0 ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end); } - if (format & 15360 /* ListFormat.BracketsMask */) { - if (isEmpty && children) { - emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists - } - writePunctuation(getClosingBracket(format)); + // Decrease the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + decreaseIndent(); + } + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write the closing line terminator or closing whitespace. + var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children[start + count - 1], format, childrenTextRange); + if (closingLineTerminatorCount) { + writeLine(closingLineTerminatorCount); + } + else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { + writeSpace(); } } // Writers @@ -114058,16 +115668,15 @@ var ts; decreaseIndent(); } } - function getLeadingLineTerminatorCount(parentNode, children, format) { + function getLeadingLineTerminatorCount(parentNode, firstChild, format) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var firstChild_1 = children[0]; - if (firstChild_1 === undefined) { + if (firstChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (firstChild_1.pos === nextListElementPos) { + if (firstChild.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading // line terminators have already been written as the separating line terminators of the // parent list. Example: @@ -114085,20 +115694,20 @@ var ts; // leading newline to start the modifiers. return 0; } - if (firstChild_1.kind === 11 /* SyntaxKind.JsxText */) { + if (firstChild.kind === 11 /* SyntaxKind.JsxText */) { // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && - !ts.nodeIsSynthesized(firstChild_1) && - (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { + !ts.nodeIsSynthesized(firstChild) && + (!firstChild.parent || ts.getOriginalNode(firstChild.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild.pos, parentNode.pos, currentSourceFile, includeComments); }); } - return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; + return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; } - if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) { + if (synthesizedNodeStartsOnNewLine(firstChild, format)) { return 1; } } @@ -114138,18 +115747,17 @@ var ts; } return format & 1 /* ListFormat.MultiLine */ ? 1 : 0; } - function getClosingLineTerminatorCount(parentNode, children, format) { + function getClosingLineTerminatorCount(parentNode, lastChild, format, childrenTextRange) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { - var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; + var end_1 = childrenTextRange && !ts.positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; @@ -114187,14 +115795,14 @@ var ts; return lines; } function writeLineSeparatorsAndIndentBefore(node, parent) { - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, node, 0 /* ListFormat.None */); if (leadingNewlines) { writeLinesAndIndent(leadingNewlines, /*writeSpaceIfNotIndenting*/ false); } return !!leadingNewlines; } function writeLineSeparatorsAfter(node, parent) { - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, node, 0 /* ListFormat.None */, /*childrenTextRange*/ undefined); if (trailingNewlines) { writeLine(trailingNewlines); } @@ -115721,12 +117329,10 @@ var ts; } ts.createCompilerHost = createCompilerHost; /*@internal*/ - // TODO(shkamat): update this after reworking ts build API function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = new ts.Map(); var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); - var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash; function getSourceFile(fileName, languageVersionOrOptions, onError) { var text; try { @@ -115759,7 +117365,7 @@ var ts; // NOTE: If patchWriteFileEnsuringDirectory has been called, // the system.writeFile will do its own directory creation and // the ensureDirectoriesExist call will always be redundant. - ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -115769,35 +117375,6 @@ var ts; } } } - var outputFingerprints; - function writeFileWorker(fileName, data, writeByteOrderMark) { - if (!ts.isWatchSet(options) || !system.getModifiedTime) { - system.writeFile(fileName, data, writeByteOrderMark); - return; - } - if (!outputFingerprints) { - outputFingerprints = new ts.Map(); - } - var hash = computeHash(data); - var mtimeBefore = system.getModifiedTime(fileName); - if (mtimeBefore) { - var fingerprint = outputFingerprints.get(fileName); - // If output has not been changed, and the file has no external modification - if (fingerprint && - fingerprint.byteOrderMark === writeByteOrderMark && - fingerprint.hash === hash && - fingerprint.mtime.getTime() === mtimeBefore.getTime()) { - return; - } - } - system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; - outputFingerprints.set(fileName, { - hash: hash, - byteOrderMark: writeByteOrderMark, - mtime: mtimeAfter - }); - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -115904,7 +117481,7 @@ var ts; }; } // directoryExists - if (originalDirectoryExists && originalCreateDirectory) { + if (originalDirectoryExists) { host.directoryExists = function (directory) { var key = toPath(directory); var value = directoryExistsCache.get(key); @@ -115914,11 +117491,13 @@ var ts; directoryExistsCache.set(key, !!newValue); return newValue; }; - host.createDirectory = function (directory) { - var key = toPath(directory); - directoryExistsCache.delete(key); - originalCreateDirectory.call(host, directory); - }; + if (originalCreateDirectory) { + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } } return { originalReadFile: originalReadFile, @@ -116139,12 +117718,14 @@ var ts; } ts.loadWithTypeDirectiveCache = loadWithTypeDirectiveCache; ; - /* @internal */ + /** + * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly + * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. + */ function getModeForFileReference(ref, containingFileMode) { return (ts.isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode; } ts.getModeForFileReference = getModeForFileReference; - /* @internal */ function getModeForResolutionAtIndex(file, index) { if (file.impliedNodeFormat === undefined) return undefined; @@ -116165,7 +117746,15 @@ var ts; return false; } ts.isExclusivelyTypeOnlyImportOrExport = isExclusivelyTypeOnlyImportOrExport; - /* @internal */ + /** + * Calculates the final resolution mode for a given module reference node. This is generally the explicitly provided resolution mode, if + * one exists, or the mode of the containing source file. (Excepting import=require, which is always commonjs, and dynamic import, which is always esm). + * Notably, this function always returns `undefined` if the containing file has an `undefined` `impliedNodeFormat` - this field is only set when + * `moduleResolution` is `node16`+. + * @param file The file the import or import-like reference is contained within + * @param usage The module reference string + * @returns The final resolution mode of the import + */ function getModeForUsageLocation(file, usage) { var _a, _b; if (file.impliedNodeFormat === undefined) @@ -116411,6 +118000,12 @@ var ts; * @returns `undefined` if the path has no relevant implied format, `ModuleKind.ESNext` for esm format, and `ModuleKind.CommonJS` for cjs format */ function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, options) { + var result = getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options); + return typeof result === "object" ? result.impliedNodeFormat : result; + } + ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + /*@internal*/ + function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) { switch (ts.getEmitModuleResolutionKind(options)) { case ts.ModuleResolutionKind.Node16: case ts.ModuleResolutionKind.NodeNext: @@ -116422,11 +118017,16 @@ var ts; return undefined; } function lookupFromPackageJson() { - var scope = ts.getPackageScopeForPath(fileName, packageJsonInfoCache, host, options); - return (scope === null || scope === void 0 ? void 0 : scope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + var state = ts.getTemporaryModuleResolutionState(packageJsonInfoCache, host, options); + var packageJsonLocations = []; + state.failedLookupLocations = packageJsonLocations; + state.affectingLocations = packageJsonLocations; + var packageJsonScope = ts.getPackageScopeForPath(fileName, state); + var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope }; } } - ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + ts.getImpliedNodeFormatForFileWorker = getImpliedNodeFormatForFileWorker; /** @internal */ ts.plainJSErrors = new ts.Set([ // binder errors @@ -116519,6 +118119,9 @@ var ts; ts.Diagnostics.extends_clause_already_seen.code, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + ts.Diagnostics.Class_constructor_may_not_be_a_generator.code, + ts.Diagnostics.Class_constructor_may_not_be_an_accessor.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]); /** * Determine if source file needs to be re-created even if its text hasn't changed @@ -116748,7 +118351,7 @@ var ts; for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); - if (shouldCreateNewSourceFile || !newFile || + if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // old file wasn't redirect but new file is (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); @@ -117085,7 +118688,7 @@ var ts; // `result[i]` is either a `ResolvedModuleFull` or a marker. // If it is the former, we can leave it as is. if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; // TODO: GH#18217 + result[i] = undefined; } } else { @@ -117141,7 +118744,7 @@ var ts; }); } function tryReuseStructureFromOldProgram() { - var _a; + var _a, _b; if (!oldProgram) { return 0 /* StructureIsReused.Not */; } @@ -117182,12 +118785,15 @@ var ts; var seenPackageNames = new ts.Map(); for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; + var sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options); var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat) + : host.getSourceFile(oldSourceFile.fileName, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat); // TODO: GH#18217 if (!newSourceFile) { return 0 /* StructureIsReused.Not */; } + newSourceFile.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope; ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); var fileChanged = void 0; if (oldSourceFile.redirectInfo) { @@ -117227,38 +118833,43 @@ var ts; seenPackageNames.set(packageName, newKind); } if (fileChanged) { + if (oldSourceFile.impliedNodeFormat !== newSourceFile.impliedNodeFormat) { + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } // The `newSourceFile` object was created for the new program. - if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { // 'lib' references has changed. Matches behavior in changesAffectModuleResolution structureIsReused = 1 /* StructureIsReused.SafeModules */; } - if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + else if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files structureIsReused = 1 /* StructureIsReused.SafeModules */; } // check tripleslash references - if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed structureIsReused = 1 /* StructureIsReused.SafeModules */; } - // check imports and module augmentations - collectExternalModuleReferences(newSourceFile); - if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - // imports has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - // moduleAugmentations has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { - // dynamicImport has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - // 'types' references has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; + else { + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); @@ -117276,18 +118887,18 @@ var ts; return structureIsReused; } var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); - for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) { - var oldFile = oldSourceFiles_3[_b]; + for (var _c = 0, oldSourceFiles_3 = oldSourceFiles; _c < oldSourceFiles_3.length; _c++) { + var oldFile = oldSourceFiles_3[_c]; if (!ts.contains(modifiedFiles, oldFile)) { - for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) { - var moduleName = _d[_c]; + for (var _d = 0, _e = oldFile.ambientModuleNames; _d < _e.length; _d++) { + var moduleName = _e[_d]; ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); } } } // try to verify results of module resolution - for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) { - var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile; + for (var _f = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _f < modifiedSourceFiles_1.length; _f++) { + var _g = modifiedSourceFiles_1[_f], oldSourceFile = _g.oldFile, newSourceFile = _g.newFile; var moduleNames = getModuleNames(newSourceFile); var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); // ensure that module resolution results are still correct @@ -117314,14 +118925,14 @@ var ts; if (structureIsReused !== 2 /* StructureIsReused.Completely */) { return structureIsReused; } - if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host))) { + if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_b = host.hasChangedAutomaticTypeDirectiveNames) === null || _b === void 0 ? void 0 : _b.call(host))) { return 1 /* StructureIsReused.SafeModules */; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); - for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) { - var newSourceFile = newSourceFiles_1[_g]; + for (var _h = 0, newSourceFiles_1 = newSourceFiles; _h < newSourceFiles_1.length; _h++) { + var newSourceFile = newSourceFiles_1[_h]; filesByName.set(newSourceFile.path, newSourceFile); } var oldFilesByNameMap = oldProgram.getFilesByNameMap(); @@ -117383,6 +118994,7 @@ var ts; getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); }, redirectTargetsMap: redirectTargetsMap, getFileIncludeReasons: program.getFileIncludeReasons, + createHash: ts.maybeBind(host, host.createHash), }; } function writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data) { @@ -117736,7 +119348,7 @@ var ts; } } function walkArray(nodes, parent) { - if (parent.decorators === nodes && !options.experimentalDecorators) { + if (ts.canHaveModifiers(parent) && parent.modifiers === nodes && ts.some(nodes, ts.isDecorator) && !options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { @@ -117767,7 +119379,7 @@ var ts; if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { + if (ts.isModifier(modifier) && modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); } } @@ -117776,7 +119388,7 @@ var ts; break; case 164 /* SyntaxKind.Parameter */: // Check modifiers of parameter declaration - if (nodes === parent.modifiers) { + if (nodes === parent.modifiers && ts.some(nodes, ts.isModifier)) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -117895,7 +119507,7 @@ var ts; } function createSyntheticImport(text, file) { var externalHelpersModuleReference = ts.factory.createStringLiteral(text); - var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); + var importDecl = ts.factory.createImportDeclaration(/*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); ts.addEmitFlags(importDecl, 67108864 /* EmitFlags.NeverApplyImportHelper */); ts.setParent(externalHelpersModuleReference, importDecl); ts.setParent(importDecl, file); @@ -118103,13 +119715,16 @@ var ts; addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) { + var _a; var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; redirect.resolvedPath = resolvedPath; redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + redirect.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + redirect.packageJsonScope = sourceFileOptions.packageJsonScope; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { @@ -118138,14 +119753,14 @@ var ts; // It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache // and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way // to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront. - var impliedNodeFormat = getImpliedNodeFormatForFile(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); - return { - languageVersion: ts.getEmitScriptTarget(options), - impliedNodeFormat: impliedNodeFormat, - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(options) - }; + var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); + var languageVersion = ts.getEmitScriptTarget(options); + var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options); + return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) : + { languageVersion: languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator }; } function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { + var _a, _b; var path = toPath(fileName); if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(path); @@ -118232,14 +119847,15 @@ var ts; } } // We haven't looked for this file, do so now and cache result - var file = host.getSourceFile(fileName, getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options), function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile); + var sourceFileOptions = getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options); + var file = host.getSourceFile(fileName, sourceFileOptions, function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile || (((_a = oldProgram === null || oldProgram === void 0 ? void 0 : oldProgram.getSourceFileByPath(toPath(fileName))) === null || _a === void 0 ? void 0 : _a.impliedNodeFormat) !== sourceFileOptions.impliedNodeFormat)); if (packageId) { var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName, sourceFileOptions); redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, redirectedPath); addFileIncludeReason(dupFile, reason); @@ -118260,6 +119876,8 @@ var ts; file.path = path; file.resolvedPath = toPath(fileName); file.originalFileName = originalFileName; + file.packageJsonLocations = ((_b = sourceFileOptions.packageJsonLocations) === null || _b === void 0 ? void 0 : _b.length) ? sourceFileOptions.packageJsonLocations : undefined; + file.packageJsonScope = sourceFileOptions.packageJsonScope; addFileIncludeReason(file, reason); if (host.useCaseSensitiveFileNames()) { var pathLowerCase = ts.toFileNameLowerCase(path); @@ -118399,13 +120017,13 @@ var ts; ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); var mode = ref.resolutionMode || file.impliedNodeFormat; if (mode && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { - programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); + programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); } processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, }); } } function processTypeReferenceDirective(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -118890,7 +120508,7 @@ var ts; fileIncludeReasons = undefined; var location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason); var fileIncludeReasonDetails = fileIncludeReasons && ts.chainDiagnosticMessages(fileIncludeReasons, ts.Diagnostics.The_file_is_in_the_program_because_Colon); - var redirectInfo = file && ts.explainIfFileIsRedirect(file); + var redirectInfo = file && ts.explainIfFileIsRedirectAndImpliedFormat(file); var chain = ts.chainDiagnosticMessages.apply(void 0, __spreadArray([redirectInfo ? fileIncludeReasonDetails ? __spreadArray([fileIncludeReasonDetails], redirectInfo, true) : redirectInfo : fileIncludeReasonDetails, diagnostic], args || ts.emptyArray, false)); return location && isReferenceFileLocation(location) ? ts.createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : @@ -118960,7 +120578,7 @@ var ts; } var matchedByInclude = ts.getMatchedIncludeSpec(program, fileName); // Could be additional files specified as roots - if (!matchedByInclude) + if (!matchedByInclude || !ts.isString(matchedByInclude)) return undefined; configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude); message = ts.Diagnostics.File_is_matched_by_include_pattern_specified_here; @@ -119484,8 +121102,8 @@ var ts; (function (ts) { function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) { var outputFiles = []; - var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit; - return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; + var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics; + return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -119496,13 +121114,9 @@ var ts; function createManyToManyPathMap() { function create(forward, reverse, deleted) { var map = { - clone: function () { return create(new ts.Map(forward), new ts.Map(reverse), deleted && new ts.Set(deleted)); }, - forEach: function (fn) { return forward.forEach(fn); }, getKeys: function (v) { return reverse.get(v); }, getValues: function (k) { return forward.get(k); }, - hasKey: function (k) { return forward.has(k); }, keys: function () { return forward.keys(); }, - deletedKeys: function () { return deleted; }, deleteKey: function (k) { (deleted || (deleted = new ts.Set())).add(k); var set = forward.get(k); @@ -119529,11 +121143,6 @@ var ts; }); return map; }, - clear: function () { - forward.clear(); - reverse.clear(); - deleted === null || deleted === void 0 ? void 0 : deleted.clear(); - } }; return map; } @@ -119661,18 +121270,21 @@ var ts; * Creates the state of file references and signature for the new program from oldState if it is safe */ function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b, _c; var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? createManyToManyPathMap() : undefined; var exportedModulesMap = referencedMap ? createManyToManyPathMap() : undefined; - var hasCalledUpdateShapeSignature = new ts.Set(); var useOldState = canReuseOldState(referencedMap, oldState); // Ensure source files have parent pointers set newProgram.getTypeChecker(); // Create the reference map, and set the file infos - for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + for (var _i = 0, _d = newProgram.getSourceFiles(); _i < _d.length; _i++) { + var sourceFile = _d[_i]; var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); - var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined; + var oldUncommittedSignature = useOldState ? (_a = oldState.oldSignatures) === null || _a === void 0 ? void 0 : _a.get(sourceFile.resolvedPath) : undefined; + var signature = oldUncommittedSignature === undefined ? + useOldState ? (_b = oldState.fileInfos.get(sourceFile.resolvedPath)) === null || _b === void 0 ? void 0 : _b.signature : undefined : + oldUncommittedSignature || undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -119680,19 +121292,26 @@ var ts; } // Copy old visible to outside files map if (useOldState) { - var exportedModules = oldState.exportedModulesMap.getValues(sourceFile.resolvedPath); + var oldUncommittedExportedModules = (_c = oldState.oldExportedModulesMap) === null || _c === void 0 ? void 0 : _c.get(sourceFile.resolvedPath); + var exportedModules = oldUncommittedExportedModules === undefined ? + oldState.exportedModulesMap.getValues(sourceFile.resolvedPath) : + oldUncommittedExportedModules || undefined; if (exportedModules) { exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, impliedFormat: sourceFile.impliedNodeFormat }); + fileInfos.set(sourceFile.resolvedPath, { + version: version_2, + signature: signature, + affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, + impliedFormat: sourceFile.impliedNodeFormat + }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } @@ -119706,120 +121325,95 @@ var ts; } BuilderState.releaseCache = releaseCache; /** - * Creates a clone of the state + * Gets the files affected by the path from the program */ - function clone(state) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var _a, _b; - // Dont need to backup allFiles info since its cache anyway - return { - fileInfos: new ts.Map(state.fileInfos), - referencedMap: (_a = state.referencedMap) === null || _a === void 0 ? void 0 : _a.clone(), - exportedModulesMap: (_b = state.exportedModulesMap) === null || _b === void 0 ? void 0 : _b.clone(), - hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), - useFileVersionAsSignature: state.useFileVersionAsSignature, - }; + var result = getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); + return result; } - BuilderState.clone = clone; - /** - * Gets the files affected by the path from the program - */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { - // Since the operation could be cancelled, the signatures are always stored in the cache - // They will be committed once it is safe to use them - // eg when calling this api from tsserver, if there is no cancellation of the operation - // In the other cases the affected files signatures are committed only after the iteration through the result is complete - var signatureCache = cacheToUpdateSignature || new ts.Map(); + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var sourceFile = programOfThisState.getSourceFileByPath(path); if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); - if (!cacheToUpdateSignature) { - // Commit all the signatures in the signature cache - updateSignaturesFromCache(state, signatureCache); - } - return result; - } - BuilderState.getFilesAffectedBy = getFilesAffectedBy; - /** - * Updates the signatures from the cache into state's fileinfo signatures - * This should be called whenever it is safe to commit the state of the builder - */ - function updateSignaturesFromCache(state, signatureCache) { - signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); }); + return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName); } - BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + BuilderState.getFilesAffectedByWithOldState = getFilesAffectedByWithOldState; function updateSignatureOfFile(state, signature, path) { state.fileInfos.get(path).signature = signature; - state.hasCalledUpdateShapeSignature.add(path); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(path); } BuilderState.updateSignatureOfFile = updateSignatureOfFile; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache, useFileVersionAsSignature) { + function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName, useFileVersionAsSignature) { + var _a; if (useFileVersionAsSignature === void 0) { useFileVersionAsSignature = state.useFileVersionAsSignature; } - ts.Debug.assert(!!sourceFile); - ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) { + if ((_a = state.hasCalledUpdateShapeSignature) === null || _a === void 0 ? void 0 : _a.has(sourceFile.resolvedPath)) return false; - } var info = state.fileInfos.get(sourceFile.resolvedPath); - if (!info) - return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) { - var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, - /*emitOnlyDtsFiles*/ true, cancellationToken, + programOfThisState.emit(sourceFile, function (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) { + ts.Debug.assert(ts.isDeclarationFileName(fileName), "File extension for signature expected to be dts: Got:: ".concat(fileName)); + latestSignature = ts.computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data); + if (latestSignature !== prevSignature) { + updateExportedModules(state, sourceFile, sourceFiles[0].exportedModulesFromDeclarationEmit); + } + }, cancellationToken, + /*emitOnlyDtsFiles*/ true, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); - if (firstDts_1) { - ts.Debug.assert(ts.isDeclarationFileName(firstDts_1.name), "File extension for signature expected to be dts", function () { return "Found: ".concat(ts.getAnyExtensionFromPath(firstDts_1.name), " for ").concat(firstDts_1.name, ":: All output files: ").concat(JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; }))); }); - latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); - if (exportedModulesMapCache && latestSignature !== prevSignature) { - updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); - } - } } // Default is to use file version as signature if (latestSignature === undefined) { latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { + if (state.exportedModulesMap && latestSignature !== prevSignature) { + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); // All the references in this file are exported var references = state.referencedMap ? state.referencedMap.getValues(sourceFile.resolvedPath) : undefined; if (references) { - exportedModulesMapCache.set(sourceFile.resolvedPath, references); + state.exportedModulesMap.set(sourceFile.resolvedPath, references); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } } } - cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); + (state.oldSignatures || (state.oldSignatures = new ts.Map())).set(sourceFile.resolvedPath, prevSignature || false); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(sourceFile.resolvedPath); + info.signature = latestSignature; return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** * Coverts the declaration emit result into exported modules map */ - function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + function updateExportedModules(state, sourceFile, exportedModulesFromDeclarationEmit) { + if (!state.exportedModulesMap) + return; + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); if (!exportedModulesFromDeclarationEmit) { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); return; } var exportedModules; exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFilesFromImportedModuleSymbol(symbol)); }); if (exportedModules) { - exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules); + state.exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } function addExportedModule(exportedModulePaths) { if (exportedModulePaths === null || exportedModulePaths === void 0 ? void 0 : exportedModulePaths.length) { @@ -119831,19 +121425,6 @@ var ts; } } BuilderState.updateExportedModules = updateExportedModules; - /** - * Updates the exported modules from cache into state's exported modules map - * This should be called whenever it is safe to commit the state of the builder - */ - function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { - var _a; - if (exportedModulesMapCache) { - ts.Debug.assert(!!state.exportedModulesMap); - (_a = exportedModulesMapCache.deletedKeys()) === null || _a === void 0 ? void 0 : _a.forEach(function (path) { return state.exportedModulesMap.deleteKey(path); }); - exportedModulesMapCache.forEach(function (exportedModules, path) { return state.exportedModulesMap.set(path, exportedModules); }); - } - } - BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -119964,7 +121545,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cancellationToken, computeHash, getCanonicalFileName) { if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -119984,7 +121565,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, computeHash, getCanonicalFileName)) { queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } @@ -120010,32 +121591,33 @@ var ts; * Create the state so that we can iterate on changedFiles/affected files */ function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; + var outFilePath = ts.outFile(compilerOptions); // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them - if (!ts.outFile(compilerOptions)) { + if (!outFilePath) { state.semanticDiagnosticsPerFile = new ts.Map(); } + else if (compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.outSignature) && outFilePath === ts.outFile(oldState === null || oldState === void 0 ? void 0 : oldState.compilerOptions)) { + state.outSignature = oldState === null || oldState === void 0 ? void 0 : oldState.outSignature; + } state.changedFilesSet = new ts.Set(); + state.latestChangedDtsFile = compilerOptions.composite ? oldState === null || oldState === void 0 ? void 0 : oldState.latestChangedDtsFile : undefined; var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + var canCopyEmitSignatures = compilerOptions.composite && + (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && + !outFilePath && + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); if (useOldState) { - // Verify the sanity of old state - if (!oldState.currentChangedFilePath) { - var affectedSignatures = oldState.currentAffectedFilesSignatures; - ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); - } - var changedFilesSet = oldState.changedFilesSet; - if (canCopySemanticDiagnostics) { - ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); - } // Copy old state's changed files set - changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); }); - if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) { + (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); + if (!outFilePath && oldState.affectedFilesPendingEmit) { state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice(); state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind); state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; @@ -120056,6 +121638,8 @@ var ts; !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || // versions dont match oldInfo.version !== info.version || + // Implied formats dont match + oldInfo.impliedFormat !== info.impliedFormat || // Referenced files changed !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || // Referenced file was deleted in the new program @@ -120079,27 +121663,25 @@ var ts; state.semanticDiagnosticsFromOldState.add(sourceFilePath); } } + if (canCopyEmitSignatures) { + var oldEmitSignature = oldState.emitSignatures.get(sourceFilePath); + if (oldEmitSignature) + (state.emitSignatures || (state.emitSignatures = new ts.Map())).set(sourceFilePath, oldEmitSignature); + } }); // If the global file is removed, add all files as changed if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) { ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined) .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); }); } - else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { + else if (oldCompilerOptions && !outFilePath && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { // Add all files to affectedFilesPendingEmit since emit changed newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* BuilderFileEmit.Full */); }); ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set(); } - if (useOldState) { - // Any time the interpretation of a source file changes, mark it as changed - ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { - if (state.fileInfos.has(sourceFilePath) && state.fileInfos.get(sourceFilePath).impliedFormat !== info.impliedFormat) { - state.changedFilesSet.add(sourceFilePath); - } - }); - } - state.buildInfoEmitPending = !!state.changedFilesSet.size; + // Since old states change files set is copied, any additional change means we would need to emit build info + state.buildInfoEmitPending = !useOldState || state.changedFilesSet.size !== (((_b = oldState.changedFilesSet) === null || _b === void 0 ? void 0 : _b.size) || 0); return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -120135,30 +121717,35 @@ var ts; ts.BuilderState.releaseCache(state); state.program = undefined; } - /** - * Creates a clone of the state - */ - function cloneBuilderProgramState(state) { - var _a; - var newState = ts.BuilderState.clone(state); - newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile); - newState.changedFilesSet = new ts.Set(state.changedFilesSet); - newState.affectedFiles = state.affectedFiles; - newState.affectedFilesIndex = state.affectedFilesIndex; - newState.currentChangedFilePath = state.currentChangedFilePath; - newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures); - newState.currentAffectedFilesExportedModulesMap = (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clone(); - newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles); - newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; - newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState); - newState.program = state.program; - newState.compilerOptions = state.compilerOptions; - newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(); - newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind); - newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; - newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles); - newState.programEmitComplete = state.programEmitComplete; - return newState; + function backupBuilderProgramEmitState(state) { + var outFilePath = ts.outFile(state.compilerOptions); + // Only in --out changeFileSet is kept around till emit + ts.Debug.assert(!state.changedFilesSet.size || outFilePath); + return { + affectedFilesPendingEmit: state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(), + affectedFilesPendingEmitKind: state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind), + affectedFilesPendingEmitIndex: state.affectedFilesPendingEmitIndex, + seenEmittedFiles: state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles), + programEmitComplete: state.programEmitComplete, + emitSignatures: state.emitSignatures && new ts.Map(state.emitSignatures), + outSignature: state.outSignature, + latestChangedDtsFile: state.latestChangedDtsFile, + hasChangedEmitSignature: state.hasChangedEmitSignature, + changedFilesSet: outFilePath ? new ts.Set(state.changedFilesSet) : undefined, + }; + } + function restoreBuilderProgramEmitState(state, savedEmitState) { + state.affectedFilesPendingEmit = savedEmitState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitKind = savedEmitState.affectedFilesPendingEmitKind; + state.affectedFilesPendingEmitIndex = savedEmitState.affectedFilesPendingEmitIndex; + state.seenEmittedFiles = savedEmitState.seenEmittedFiles; + state.programEmitComplete = savedEmitState.programEmitComplete; + state.emitSignatures = savedEmitState.emitSignatures; + state.outSignature = savedEmitState.outSignature; + state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile; + state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; + if (savedEmitState.changedFilesSet) + state.changedFilesSet = savedEmitState.changedFilesSet; } /** * Verifies that source file is ok to be used in calls that arent handled by next @@ -120172,8 +121759,8 @@ var ts; * This is to allow the callers to be able to actually remove affected file only when the operation is complete * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained */ - function getNextAffectedFile(state, cancellationToken, computeHash, host) { - var _a; + function getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { @@ -120184,7 +121771,7 @@ var ts; if (!seenAffectedFiles.has(affectedFile.resolvedPath)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); return affectedFile; } affectedFilesIndex++; @@ -120193,10 +121780,8 @@ var ts; state.changedFilesSet.delete(state.currentChangedFilePath); state.currentChangedFilePath = undefined; // Commit the changes in file signature - ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); - state.currentAffectedFilesSignatures.clear(); - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); - (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clear(); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); state.affectedFiles = undefined; } // Get next changed file @@ -120214,12 +121799,7 @@ var ts; return program; } // Get next batch of affected files - if (!state.currentAffectedFilesSignatures) - state.currentAffectedFilesSignatures = new ts.Map(); - if (state.exportedModulesMap) { - state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap()); - } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedByWithOldState(state, program, nextKey.value, cancellationToken, computeHash, getCanonicalFileName); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; if (!state.seenAffectedFiles) @@ -120270,8 +121850,7 @@ var ts; * Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ - function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -120279,19 +121858,18 @@ var ts; // When a change affects the global scope, all files are considered to be affected without updating their signature // That means when affected file is handled, its signature can be out of date // To avoid this, ensure that we update the signature for any affected file in this scenario. - ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, cancellationToken, computeHash, getCanonicalFileName); return; } - ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: ".concat(affectedFile.fileName)); if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; - handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); } /** * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled, * Also we need to make sure signature is updated for these files */ - function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, host) { + function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { var program = ts.Debug.checkDefined(state.program); @@ -120302,7 +121880,7 @@ var ts; // This ensures that we dont later during incremental builds considering wrong signature. // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build // But we avoid expensive full shape computation, as using file version as shape is enough for correctness. - ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap, !host.disableUseFileVersionAsSignature); + ts.BuilderState.updateShapeSignature(state, program, sourceFile, cancellationToken, computeHash, getCanonicalFileName, !host.disableUseFileVersionAsSignature); // If not dts emit, nothing more to do if (ts.getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, 0 /* BuilderFileEmit.DtsOnly */); @@ -120323,41 +121901,25 @@ var ts; return !state.semanticDiagnosticsFromOldState.size; } function isChangedSignature(state, path) { - var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path); - var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; + var oldSignature = ts.Debug.checkDefined(state.oldSignatures).get(path) || undefined; + var newSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; return newSignature !== oldSignature; } - function forEachKeyOfExportedModulesMap(state, filePath, fn) { - // Go through exported modules from cache first - var keys = state.currentAffectedFilesExportedModulesMap.getKeys(filePath); - var result = keys && ts.forEachKey(keys, fn); - if (result) - return result; - // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - keys = state.exportedModulesMap.getKeys(filePath); - return keys && ts.forEachKey(keys, function (exportedFromPath) { - var _a; - // If the cache had an updated value, skip - return !state.currentAffectedFilesExportedModulesMap.hasKey(exportedFromPath) && - !((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(exportedFromPath)) ? - fn(exportedFromPath) : - undefined; - }); - } - function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host) { var _a; if (!((_a = state.fileInfos.get(filePath)) === null || _a === void 0 ? void 0 : _a.affectsGlobalScope)) return false; // Every file needs to be handled ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, state.program, /*firstSourceFile*/ undefined) - .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, host); }); + .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, getCanonicalFileName, host); }); removeDiagnosticsOfLibraryFiles(state); return true; } /** * Iterate on referencing modules that export entities from affected file and delete diagnostics and add pending emit */ - function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a; // If there was change in signature (dts output) for the changed file, // then only we need to handle pending file emit if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) @@ -120374,9 +121936,9 @@ var ts; var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { seenFileNamesMap.set(currentPath, true); - if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host)) return; - handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, host); + handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host); if (isChangedSignature(state, currentPath)) { var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath); queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); @@ -120384,16 +121946,15 @@ var ts; } } } - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); var seenFileAndExportsOfFile = new ts.Set(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, affectedFile.resolvedPath, function (exportedFromPath) { - if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, host)) + (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; var references = state.referencedMap.getKeys(exportedFromPath); return references && ts.forEachKey(references, function (filePath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); }); } @@ -120401,23 +121962,22 @@ var ts; * handle dts and semantic diagnostics on file and iterate on anything that exports this file * return true when all work is done and we can exit handling dts emit and semantic diagnostics */ - function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) return undefined; - if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; - handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, host); - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host); // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, filePath, function (exportedFromPath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + (_a = state.exportedModulesMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); // Remove diagnostics of files that import this file (without going to exports of referencing files) - (_a = state.referencedMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (referencingFilePath) { + (_b = state.referencedMap.getKeys(filePath)) === null || _b === void 0 ? void 0 : _b.forEach(function (referencingFilePath) { return !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file handleDtsMayChangeOf(// Dont add to seen since this is not yet done with the export removal - state, referencingFilePath, cancellationToken, computeHash, host); + state, referencingFilePath, cancellationToken, computeHash, getCanonicalFileName, host); }); return undefined; } @@ -120435,12 +121995,13 @@ var ts; } else { state.seenAffectedFiles.add(affected.resolvedPath); + // Change in changeSet/affectedFilesPendingEmit, buildInfo needs to be emitted + state.buildInfoEmitPending = true; if (emitKind !== undefined) { (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind); } if (isPendingEmit) { state.affectedFilesPendingEmitIndex++; - state.buildInfoEmitPending = true; } else { state.affectedFilesIndex++; @@ -120488,25 +122049,62 @@ var ts; } return ts.filterSemanticDiagnostics(diagnostics, state.compilerOptions); } + function isProgramBundleEmitBuildInfo(info) { + return !!ts.outFile(info.options || {}); + } + ts.isProgramBundleEmitBuildInfo = isProgramBundleEmitBuildInfo; /** * Gets the program information to be emitted in buildInfo so that we can use it to create new program */ function getProgramBuildInfo(state, getCanonicalFileName) { - if (ts.outFile(state.compilerOptions)) - return undefined; + var outFilePath = ts.outFile(state.compilerOptions); + if (outFilePath && !state.compilerOptions.composite) + return; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); + // Convert the file name to Path here if we set the fileName instead to optimize multiple d.ts file emits and having to compute Canonical path + var latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : undefined; + if (outFilePath) { + var fileNames_1 = []; + var fileInfos_1 = []; + state.program.getRootFileNames().forEach(function (f) { + var sourceFile = state.program.getSourceFile(f); + if (!sourceFile) + return; + fileNames_1.push(relativeToBuildInfo(sourceFile.resolvedPath)); + fileInfos_1.push(sourceFile.version); + }); + var result_15 = { + fileNames: fileNames_1, + fileInfos: fileInfos_1, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsBundleEmitBuildInfo"), + outSignature: state.outSignature, + latestChangedDtsFile: latestChangedDtsFile, + }; + return result_15; + } var fileNames = []; var fileNameToFileId = new ts.Map(); var fileIdsList; var fileNamesToFileIdListId; + var emitSignatures; var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var _b, _c; var key = _a[0], value = _a[1]; // Ensure fileId var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); - var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + var oldSignature = (_b = state.oldSignatures) === null || _b === void 0 ? void 0 : _b.get(key); + var actualSignature = oldSignature !== undefined ? oldSignature || undefined : value.signature; + if (state.compilerOptions.composite) { + var file = state.program.getSourceFileByPath(key); + if (!ts.isJsonSourceFile(file) && ts.sourceFileMayBeEmitted(file, state.program)) { + var emitSignature = (_c = state.emitSignatures) === null || _c === void 0 ? void 0 : _c.get(key); + if (emitSignature !== actualSignature) { + (emitSignatures || (emitSignatures = [])).push(emitSignature === undefined ? fileId : [fileId, emitSignature]); + } + } + } return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? // If file version is same as signature, dont serialize signature @@ -120514,11 +122112,11 @@ var ts; // If file info only contains version and signature and both are same we can just write string value.version : actualSignature !== undefined ? // If signature is not same as version, encode signature in the fileInfo - signature === undefined ? + oldSignature === undefined ? // If we havent computed signature, use fileInfo as is value : // Serialize fileInfo with new updated signature - { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : + { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : // Signature of the FileInfo is undefined, serialize it as false { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }; }); @@ -120533,17 +122131,13 @@ var ts; if (state.exportedModulesMap) { exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var _a; - if (state.currentAffectedFilesExportedModulesMap) { - if ((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(key)) { - return undefined; - } - var newValue = state.currentAffectedFilesExportedModulesMap.getValues(key); - if (newValue) { - return [toFileId(key), toFileIdListId(newValue)]; - } - } + var oldValue = (_a = state.oldExportedModulesMap) === null || _a === void 0 ? void 0 : _a.get(key); // Not in temporary cache, use existing value - return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue === undefined) + return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue) + return [toFileId(key), toFileIdListId(oldValue)]; + return undefined; }); } var semanticDiagnosticsPerFile; @@ -120554,9 +122148,7 @@ var ts; (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ toFileId(key), - state.hasReusableDiagnostic ? - value : - convertToReusableDiagnostics(value, relativeToBuildInfo) + convertToReusableDiagnostics(value, relativeToBuildInfo) ] : toFileId(key)); } @@ -120571,16 +122163,27 @@ var ts; } } } - return { + var changeFileSet; + if (state.changedFilesSet.size) { + for (var _d = 0, _e = ts.arrayFrom(state.changedFilesSet.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { + var path = _e[_d]; + (changeFileSet || (changeFileSet = [])).push(toFileId(path)); + } + } + var result = { fileNames: fileNames, fileInfos: fileInfos, - options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsMultiFileEmitBuildInfo"), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, affectedFilesPendingEmit: affectedFilesPendingEmit, + changeFileSet: changeFileSet, + emitSignatures: emitSignatures, + latestChangedDtsFile: latestChangedDtsFile, }; + return result; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } @@ -120605,24 +122208,21 @@ var ts; } return fileIdListId; } - } - function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { - var result; - var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var name = _a[_i]; - var optionKey = name.toLowerCase(); - var optionInfo = optionsNameMap.get(optionKey); - if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || - // We need to store `strict`, even though it won't be examined directly, so that the - // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly from the buildinfo - optionKey === "strict" || - // We need to store these to determine whether `lib` files need to be rechecked. - optionKey === "skiplibcheck" || optionKey === "skipdefaultlibcheck") { - (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); + /** + * @param optionKey key of CommandLineOption to use to determine if the option should be serialized in tsbuildinfo + */ + function convertToProgramBuildInfoCompilerOptions(options, optionKey) { + var result; + var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo[optionKey]) { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfoEnsuringAbsolutePath); + } } + return result; } - return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { if (option) { @@ -120696,6 +122296,41 @@ var ts; return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; } ts.getBuilderCreationParameters = getBuilderCreationParameters; + function getTextHandlingSourceMapForSignature(text, data) { + return (data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text; + } + function computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data) { + var _a; + text = getTextHandlingSourceMapForSignature(text, data); + var sourceFileDirectory; + if ((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length) { + text += data.diagnostics.map(function (diagnostic) { + return "".concat(locationInfo(diagnostic)).concat(ts.DiagnosticCategory[diagnostic.category]).concat(diagnostic.code, ": ").concat(flattenDiagnosticMessageText(diagnostic.messageText)); + }).join("\n"); + } + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(text); + function flattenDiagnosticMessageText(diagnostic) { + return ts.isString(diagnostic) ? + diagnostic : + diagnostic === undefined ? + "" : + !diagnostic.next ? + diagnostic.messageText : + diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText).join("\n"); + } + function locationInfo(diagnostic) { + if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) + return "(".concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + if (sourceFileDirectory === undefined) + sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath); + return "".concat(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceFileDirectory, diagnostic.file.resolvedPath, getCanonicalFileName)), "(").concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + } + } + ts.computeSignatureWithDiagnostics = computeSignatureWithDiagnostics; + function computeSignature(text, computeHash, data) { + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); + } + ts.computeSignature = computeSignature; function createBuilderProgram(kind, _a) { var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; // Return same program if underlying program doesnt change @@ -120714,7 +122349,6 @@ var ts; */ var computeHash = ts.maybeBind(host, host.createHash); var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); - var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 @@ -120723,21 +122357,13 @@ var ts; var getState = function () { return state; }; var builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics); builderProgram.getState = getState; - builderProgram.backupState = function () { - ts.Debug.assert(backupState === undefined); - backupState = cloneBuilderProgramState(state); - }; - builderProgram.restoreState = function () { - state = ts.Debug.checkDefined(backupState); - backupState = undefined; - }; + builderProgram.saveEmitState = function () { return backupBuilderProgramEmitState(state); }; + builderProgram.restoreEmitState = function (saved) { return restoreBuilderProgramEmitState(state, saved); }; + builderProgram.hasChangedEmitSignature = function () { return !!state.hasChangedEmitSignature; }; builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); }; builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; builderProgram.emit = emit; - builderProgram.releaseProgram = function () { - releaseCache(state); - backupState = undefined; - }; + builderProgram.releaseProgram = function () { return releaseCache(state); }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; } @@ -120764,7 +122390,7 @@ var ts; * in that order would be used to write the files */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); var emitKind = 1 /* BuilderFileEmit.Full */; var isPendingEmitFile = false; if (!affected) { @@ -120795,34 +122421,68 @@ var ts; return toAffectedFileEmitResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, affected !== state.program && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* BuilderFileEmit.DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile); } - function getWriteFileUpdatingSignatureCallback(writeFile) { + function getWriteFileCallback(writeFile, customTransformers) { return function (fileName, text, writeByteOrderMark, onError, sourceFiles, data) { - var _a; + var _a, _b, _c, _d, _e, _f, _g; if (ts.isDeclarationFileName(fileName)) { - ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); - var file = sourceFiles[0]; - var info = state.fileInfos.get(file.resolvedPath); - var signature = ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.get(file.resolvedPath)) || info.signature; - if (signature === file.version) { - var newSignature = (computeHash || ts.generateDjb2Hash)((data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text); - if (newSignature !== file.version) { // Update it - if (host.storeFilesChangingSignatureDuringEmit) - (state.filesChangingSignature || (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); - if (state.exportedModulesMap) - ts.BuilderState.updateExportedModules(file, file.exportedModulesFromDeclarationEmit, state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap())); - if (state.affectedFiles && state.affectedFilesIndex < state.affectedFiles.length) { - state.currentAffectedFilesSignatures.set(file.resolvedPath, newSignature); - } - else { - info.signature = newSignature; - if (state.exportedModulesMap) - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + if (!ts.outFile(state.compilerOptions)) { + ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); + var emitSignature = void 0; + if (!customTransformers) { + var file = sourceFiles[0]; + var info = state.fileInfos.get(file.resolvedPath); + if (info.signature === file.version) { + var signature = computeSignatureWithDiagnostics(file, text, computeHash, getCanonicalFileName, data); + // With d.ts diagnostics they are also part of the signature so emitSignature will be different from it since its just hash of d.ts + if (!((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length)) + emitSignature = signature; + if (signature !== file.version) { // Update it + if (host.storeFilesChangingSignatureDuringEmit) + ((_b = state.filesChangingSignature) !== null && _b !== void 0 ? _b : (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); + if (state.exportedModulesMap) + ts.BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit); + if (state.affectedFiles) { + // Keep old signature so we know what to undo if cancellation happens + var existing = (_c = state.oldSignatures) === null || _c === void 0 ? void 0 : _c.get(file.resolvedPath); + if (existing === undefined) + ((_d = state.oldSignatures) !== null && _d !== void 0 ? _d : (state.oldSignatures = new ts.Map())).set(file.resolvedPath, info.signature || false); + info.signature = signature; + } + else { + // These are directly commited + info.signature = signature; + (_e = state.oldExportedModulesMap) === null || _e === void 0 ? void 0 : _e.clear(); + } + } } } + // Store d.ts emit hash so later can be compared to check if d.ts has changed. + // Currently we do this only for composite projects since these are the only projects that can be referenced by other projects + // and would need their d.ts change time in --build mode + if (state.compilerOptions.composite) { + var filePath = sourceFiles[0].resolvedPath; + var oldSignature = (_f = state.emitSignatures) === null || _f === void 0 ? void 0 : _f.get(filePath); + emitSignature !== null && emitSignature !== void 0 ? emitSignature : (emitSignature = computeSignature(text, computeHash, data)); + // Dont write dts files if they didn't change + if (emitSignature === oldSignature) + return; + ((_g = state.emitSignatures) !== null && _g !== void 0 ? _g : (state.emitSignatures = new ts.Map())).set(filePath, emitSignature); + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; + } + } + else if (state.compilerOptions.composite) { + var newSignature = computeSignature(text, computeHash, data); + // Dont write dts files if they didn't change + if (newSignature === state.outSignature) + return; + state.outSignature = newSignature; + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; } } if (writeFile) @@ -120888,8 +122548,8 @@ var ts; } } } - return ts.Debug.checkDefined(state.program).emit(targetSourceFile, !ts.outFile(state.compilerOptions) && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + return ts.Debug.checkDefined(state.program).emit(targetSourceFile, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers); } /** @@ -120898,7 +122558,7 @@ var ts; */ function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { while (true) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); if (!affected) { // Done return undefined; @@ -120978,29 +122638,59 @@ var ts; { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; } ts.toBuilderStateFileInfo = toBuilderStateFileInfo; - function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { - var _a; + function createBuilderProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a, _b, _c, _d; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var filePaths = program.fileNames.map(toPath); - var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); - var fileInfos = new ts.Map(); - program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); - var state = { - fileInfos: fileInfos, - compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, - referencedMap: toManyToManyPathMap(program.referencedMap), - exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), - hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), - affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, - }; + var state; + var filePaths; + var filePathsSetList; + var latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : undefined; + if (isProgramBundleEmitBuildInfo(program)) { + state = { + fileInfos: new ts.Map(), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + latestChangedDtsFile: latestChangedDtsFile, + outSignature: program.outSignature, + }; + } + else { + filePaths = (_a = program.fileNames) === null || _a === void 0 ? void 0 : _a.map(toPath); + filePathsSetList = (_b = program.fileIdsList) === null || _b === void 0 ? void 0 : _b.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); + var fileInfos_2 = new ts.Map(); + var emitSignatures_1 = ((_c = program.options) === null || _c === void 0 ? void 0 : _c.composite) && !ts.outFile(program.options) ? new ts.Map() : undefined; + program.fileInfos.forEach(function (fileInfo, index) { + var path = toFilePath(index + 1); + var stateFileInfo = toBuilderStateFileInfo(fileInfo); + fileInfos_2.set(path, stateFileInfo); + if (emitSignatures_1 && stateFileInfo.signature) + emitSignatures_1.set(path, stateFileInfo.signature); + }); + (_d = program.emitSignatures) === null || _d === void 0 ? void 0 : _d.forEach(function (value) { + if (ts.isNumber(value)) + emitSignatures_1.delete(toFilePath(value)); + else + emitSignatures_1.set(toFilePath(value[0]), value[1]); + }); + state = { + fileInfos: fileInfos_2, + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toManyToManyPathMap(program.referencedMap), + exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), + hasReusableDiagnostic: true, + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, + changedFilesSet: new ts.Set(ts.map(program.changeFileSet, toFilePath)), + latestChangedDtsFile: latestChangedDtsFile, + emitSignatures: (emitSignatures_1 === null || emitSignatures_1 === void 0 ? void 0 : emitSignatures_1.size) ? emitSignatures_1 : undefined, + }; + } return { getState: function () { return state; }, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: ts.notImplemented, getProgramOrUndefined: ts.returnUndefined, releaseProgram: ts.noop, @@ -121020,6 +122710,7 @@ var ts; getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented, emitBuildInfo: ts.notImplemented, close: ts.noop, + hasChangedEmitSignature: ts.returnFalse, }; function toPath(path) { return ts.toPath(path, buildInfoDirectory, getCanonicalFileName); @@ -121045,12 +122736,24 @@ var ts; return map; } } - ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; + ts.createBuilderProgramUsingProgramBuildInfo = createBuilderProgramUsingProgramBuildInfo; + function getBuildInfoFileVersionMap(program, buildInfoPath, host) { + var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var fileInfos = new ts.Map(); + program.fileInfos.forEach(function (fileInfo, index) { + var path = ts.toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName); + var version = ts.isString(fileInfo) ? fileInfo : fileInfo.version; // eslint-disable-line @typescript-eslint/no-unnecessary-type-assertion + fileInfos.set(path, version); + }); + return fileInfos; + } + ts.getBuildInfoFileVersionMap = getBuildInfoFileVersionMap; function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { return { getState: ts.notImplemented, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: getProgram, getProgramOrUndefined: function () { return getState().program; }, releaseProgram: function () { return getState().program = undefined; }, @@ -121110,7 +122813,7 @@ var ts; * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" * @param dirPath */ - function canWatchDirectory(dirPath) { + function canWatchDirectoryOrFile(dirPath) { var rootLength = ts.getRootLength(dirPath); if (dirPath.length === rootLength) { // Ignore "/", "c:/" @@ -121147,15 +122850,19 @@ var ts; } return true; } - ts.canWatchDirectory = canWatchDirectory; + ts.canWatchDirectoryOrFile = canWatchDirectoryOrFile; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var resolutionsWithFailedLookups = []; + var resolutionsWithOnlyAffectingLocations = []; var resolvedFileToResolution = ts.createMultiMap(); + var impliedFormatPackageJsons = new ts.Map(); var hasChangedAutomaticTypeDirectiveNames = false; + var affectingPathChecksForFile; + var affectingPathChecks; var failedLookupChecks; var startsWithPathChecks; var isInDirectoryChecks; @@ -121182,6 +122889,7 @@ var ts; var failedLookupDefaultExtensions = [".ts" /* Extension.Ts */, ".tsx" /* Extension.Tsx */, ".js" /* Extension.Js */, ".jsx" /* Extension.Jsx */, ".json" /* Extension.Json */]; var customFailedLookupPaths = new ts.Map(); var directoryWatchesOfFailedLookups = new ts.Map(); + var fileWatchesOfAffectingLocations = new ts.Map(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0; @@ -121193,7 +122901,7 @@ var ts; finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + startCachingPerDirectoryResolution: startCachingPerDirectoryResolution, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -121224,6 +122932,7 @@ var ts; } function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + ts.clearMap(fileWatchesOfAffectingLocations, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); @@ -121231,12 +122940,15 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; + resolutionsWithOnlyAffectingLocations.length = 0; failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; - // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update - // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - clearPerDirectoryResolutions(); + affectingPathChecks = undefined; + affectingPathChecksForFile = undefined; + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); + impliedFormatPackageJsons.clear(); hasChangedAutomaticTypeDirectiveNames = false; } function startRecordingFilesWithChangedResolutions() { @@ -121268,25 +122980,60 @@ var ts; return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } - function clearPerDirectoryResolutions() { - moduleResolutionCache.clear(); - typeReferenceDirectiveResolutionCache.clear(); + function startCachingPerDirectoryResolution() { + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } - function finishCachingPerDirectoryResolution() { + function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = undefined; - clearPerDirectoryResolutions(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + // Update file watches + if (newProgram !== oldProgram) { + newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFiles().forEach(function (newFile) { + var _a, _b, _c; + var expected = ts.isExternalOrCommonJsModule(newFile) ? (_b = (_a = newFile.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0 : 0; + var existing = (_c = impliedFormatPackageJsons.get(newFile.path)) !== null && _c !== void 0 ? _c : ts.emptyArray; + for (var i = existing.length; i < expected; i++) { + createFileWatcherOfAffectingLocation(newFile.packageJsonLocations[i], /*forResolution*/ false); + } + if (existing.length > expected) { + for (var i = expected; i < existing.length; i++) { + fileWatchesOfAffectingLocations.get(existing[i]).files--; + } + } + if (expected) + impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations); + else + impliedFormatPackageJsons.delete(newFile.path); + }); + impliedFormatPackageJsons.forEach(function (existing, path) { + if (!(newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFileByPath(path))) { + existing.forEach(function (location) { return fileWatchesOfAffectingLocations.get(location).files--; }); + impliedFormatPackageJsons.delete(path); + } + }); + } directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); + fileWatchesOfAffectingLocations.forEach(function (watcher, path) { + if (watcher.files === 0 && watcher.resolutions === 0) { + fileWatchesOfAffectingLocations.delete(path); + watcher.watcher.close(); + } + }); hasChangedAutomaticTypeDirectiveNames = false; } function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference, _containingSourceFile, mode) { - var _a; + var _a, _b; var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { @@ -121297,11 +123044,12 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _c = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _c.resolvedModule, failedLookupLocations = _c.failedLookupLocations, affectingLocations = _c.affectingLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = primaryResult.affectingLocations).push.apply(_b, affectingLocations); return primaryResult; } } @@ -121506,7 +123254,7 @@ var ts; } // If the directory is node_modules use it to watch, always watch it recursively if (ts.isNodeModulesDirectory(dirPath)) { - return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + return canWatchDirectoryOrFile(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -121524,7 +123272,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + return canWatchDirectoryOrFile(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -121552,10 +123300,11 @@ var ts; } function watchFailedLookupLocationOfResolution(resolution) { ts.Debug.assert(!!resolution.refCount); - var failedLookupLocations = resolution.failedLookupLocations; - if (!failedLookupLocations.length) + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (!failedLookupLocations.length && !affectingLocations.length) return; - resolutionsWithFailedLookups.push(resolution); + if (failedLookupLocations.length) + resolutionsWithFailedLookups.push(resolution); var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; @@ -121582,12 +123331,87 @@ var ts; // This is always non recursive setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } + watchAffectingLocationsOfResolution(resolution, !failedLookupLocations.length); + } + function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { + ts.Debug.assert(!!resolution.refCount); + var affectingLocations = resolution.affectingLocations; + if (!affectingLocations.length) + return; + if (addToResolutionsWithOnlyAffectingLocations) + resolutionsWithOnlyAffectingLocations.push(resolution); + // Watch package json + for (var _i = 0, affectingLocations_1 = affectingLocations; _i < affectingLocations_1.length; _i++) { + var affectingLocation = affectingLocations_1[_i]; + createFileWatcherOfAffectingLocation(affectingLocation, /*forResolution*/ true); + } + } + function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) { + var fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation); + if (fileWatcher) { + if (forResolution) + fileWatcher.resolutions++; + else + fileWatcher.files++; + return; + } + var locationToWatch = affectingLocation; + if (resolutionHost.realpath) { + locationToWatch = resolutionHost.realpath(affectingLocation); + if (affectingLocation !== locationToWatch) { + var fileWatcher_1 = fileWatchesOfAffectingLocations.get(locationToWatch); + if (fileWatcher_1) { + if (forResolution) + fileWatcher_1.resolutions++; + else + fileWatcher_1.files++; + fileWatcher_1.paths.add(affectingLocation); + fileWatchesOfAffectingLocations.set(affectingLocation, fileWatcher_1); + return; + } + } + } + var paths = new ts.Set(); + paths.add(locationToWatch); + var actualWatcher = canWatchDirectoryOrFile(resolutionHost.toPath(locationToWatch)) ? + resolutionHost.watchAffectingFileLocation(locationToWatch, function (fileName, eventKind) { + cachedDirectoryStructureHost === null || cachedDirectoryStructureHost === void 0 ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + paths.forEach(function (path) { + if (watcher.resolutions) + (affectingPathChecks !== null && affectingPathChecks !== void 0 ? affectingPathChecks : (affectingPathChecks = new ts.Set())).add(path); + if (watcher.files) + (affectingPathChecksForFile !== null && affectingPathChecksForFile !== void 0 ? affectingPathChecksForFile : (affectingPathChecksForFile = new ts.Set())).add(path); + packageJsonMap === null || packageJsonMap === void 0 ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); + }); + resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); + }) : ts.noopFileWatcher; + var watcher = { + watcher: actualWatcher !== ts.noopFileWatcher ? { + close: function () { + actualWatcher.close(); + // Ensure when watching symlinked package.json, we can close the actual file watcher only once + actualWatcher = ts.noopFileWatcher; + } + } : actualWatcher, + resolutions: forResolution ? 1 : 0, + files: forResolution ? 0 : 1, + paths: paths, + }; + fileWatchesOfAffectingLocations.set(locationToWatch, watcher); + if (affectingLocation !== locationToWatch) { + fileWatchesOfAffectingLocations.set(affectingLocation, watcher); + paths.add(affectingLocation); + } } function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { var program = resolutionHost.getCurrentProgram(); if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) { resolutions.forEach(watchFailedLookupLocationOfResolution); } + else { + resolutions.forEach(function (resolution) { return watchAffectingLocationsOfResolution(resolution, /*addToResolutionWithOnlyAffectingLocations*/ true); }); + } } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); @@ -121609,38 +123433,44 @@ var ts; if (resolved && resolved.resolvedFileName) { resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution); } - if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { - // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups - return; - } - var failedLookupLocations = resolution.failedLookupLocations; - var removeAtRoot = false; - for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { - var failedLookupLocation = failedLookupLocations_2[_i]; - var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (toWatch) { - var dirPath = toWatch.dirPath; - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - if (dirPath === rootPath) { - removeAtRoot = true; - } - else { - removeDirectoryWatcher(dirPath); - } + } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); } } - if (removeAtRoot) { - removeDirectoryWatcher(rootPath); + else if (affectingLocations.length) { + ts.unorderedRemoveItem(resolutionsWithOnlyAffectingLocations, resolution); + } + for (var _a = 0, affectingLocations_2 = affectingLocations; _a < affectingLocations_2.length; _a++) { + var affectingLocation = affectingLocations_2[_a]; + var watcher = fileWatchesOfAffectingLocations.get(affectingLocation); + watcher.resolutions--; } } function removeDirectoryWatcher(dirPath) { @@ -121694,7 +123524,7 @@ var ts; resolution.isInvalidated = invalidated = true; for (var _a = 0, _b = ts.Debug.checkDefined(resolution.files); _a < _b.length; _a++) { var containingFilePath = _b[_a]; - (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); // When its a file with inferred types resolution, invalidate type reference directive resolution hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile); } @@ -121719,7 +123549,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = new ts.Set())).add(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -121737,7 +123567,7 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { @@ -121749,7 +123579,7 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); // If the invalidated file is from a node_modules package, invalidate everything else // in the package since we might not get notifications for other files in the package. // This hardens our logic against unreliable file watchers. @@ -121761,22 +123591,46 @@ var ts; resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { - return false; + var _a; + var invalidated = false; + if (affectingPathChecksForFile) { + (_a = resolutionHost.getCurrentProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFiles().forEach(function (f) { + if (ts.some(f.packageJsonLocations, function (location) { return affectingPathChecksForFile.has(location); })) { + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(f.path); + invalidated = true; + } + }); + affectingPathChecksForFile = undefined; + } + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks && !affectingPathChecks) { + return invalidated; + } + invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach(function (_value, path) { return isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : undefined; }); } - var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; + invalidated = invalidateResolutions(resolutionsWithOnlyAffectingLocations, canInvalidatedFailedLookupResolutionWithAffectingLocation) || invalidated; + affectingPathChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { - return resolution.failedLookupLocations.some(function (location) { - var locationPath = resolutionHost.toPath(location); - return ts.contains(failedLookupChecks, locationPath) || - ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || - (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); - }); + if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) + return true; + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) + return false; + return resolution.failedLookupLocations.some(function (location) { return isInvalidatedFailedLookup(resolutionHost.toPath(location)); }); + } + function isInvalidatedFailedLookup(locationPath) { + return (failedLookupChecks === null || failedLookupChecks === void 0 ? void 0 : failedLookupChecks.has(locationPath)) || + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + ts.firstDefinedIterator((isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath) ? true : undefined; }); + } + function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) { + return !!affectingPathChecks && resolution.affectingLocations.some(function (location) { return affectingPathChecks.has(location); }); } function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); @@ -121842,7 +123696,7 @@ var ts; function directoryExistsForTypeRootWatch(nodeTypesDirectory) { var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); var dirPath = resolutionHost.toPath(dir); - return dirPath === rootPath || canWatchDirectory(dirPath); + return dirPath === rootPath || canWatchDirectoryOrFile(dirPath); } } ts.createResolutionCache = createResolutionCache; @@ -121953,7 +123807,7 @@ var ts; var info = getInfo(importingSourceFileName, host); var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences, options); return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode); }) || - getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences); + getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences, options) { if (options === void 0) { options = {}; } @@ -122036,7 +123890,7 @@ var ts; return nodeModulesSpecifiers; } if (!specifier && !modulePath.isRedirect) { - var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences); + var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); if (ts.pathIsBareSpecifier(local)) { pathsSpecifiers = ts.append(pathsSpecifiers, local); } @@ -122064,7 +123918,7 @@ var ts; var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); return { getCanonicalFileName: getCanonicalFileName, importingSourceFileName: importingSourceFileName, sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, _a) { + function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, _a) { var ending = _a.ending, relativePreference = _a.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var sourceDirectory = info.sourceDirectory, getCanonicalFileName = info.getCanonicalFileName; @@ -122078,9 +123932,8 @@ var ts; if (!relativeToBaseUrl) { return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); - var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths; + var fromPaths = paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, getAllowedEndings(ending, compilerOptions, importMode), host, compilerOptions); + var nonRelative = fromPaths === undefined && baseUrl !== undefined ? removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) : fromPaths; if (!nonRelative) { return relativePath; } @@ -122166,9 +124019,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -122188,10 +124041,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_17 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_17) + return result_17; } }); }); @@ -122233,7 +124086,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_32 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -122257,9 +124110,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_10 = _loop_32(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_10 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -122315,28 +124168,102 @@ var ts; return ambientModuleDeclare.name.text; } } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + function getAllowedEndings(preferredEnding, compilerOptions, importMode) { + if (ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && importMode === ts.ModuleKind.ESNext) { + return [2 /* Ending.JsExtension */]; + } + switch (preferredEnding) { + case 2 /* Ending.JsExtension */: return [2 /* Ending.JsExtension */, 0 /* Ending.Minimal */, 1 /* Ending.Index */]; + case 1 /* Ending.Index */: return [1 /* Ending.Index */, 0 /* Ending.Minimal */, 2 /* Ending.JsExtension */]; + case 0 /* Ending.Minimal */: return [0 /* Ending.Minimal */, 1 /* Ending.Index */, 2 /* Ending.JsExtension */]; + default: ts.Debug.assertNever(preferredEnding); + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(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, + // meaning a '.ts' or '.d.ts' extension is allowed to resolve. This is distinct from the case where a '*' substitution + // causes a module specifier to have an extension, i.e. the extension comes from the module specifier in a JS/TS file + // and matches the '*'. For example: + // + // Module Specifier | Path Mapping (key: [pattern]) | Interpolation | Resolution Action + // ---------------------->------------------------------->--------------------->--------------------------------------------------------------- + // import "@app/foo" -> "@app/*": ["./src/app/*.ts"] -> "./src/app/foo.ts" -> tryFile("./src/app/foo.ts") || [continue resolution algorithm] + // import "@app/foo.ts" -> "@app/*": ["./src/app/*"] -> "./src/app/foo.ts" -> [continue resolution algorithm] + // + // (https://github.com/microsoft/TypeScript/blob/ad4ded80e1d58f0bf36ac16bea71bc10d9f09895/src/compiler/moduleNameResolver.ts#L2509-L2516) + // + // The interpolation produced by both scenarios is identical, but only in the former, where the extension is encoded in + // the path mapping rather than in the module specifier, will we prioritize a file lookup on the interpolation result. + // (In fact, currently, the latter scenario will necessarily fail since no resolution mode recognizes '.ts' as a valid + // extension for a module specifier.) + // + // Here, this means we need to be careful about whether we generate a match from the target filename (typically with a + // .ts extension) or the possible relative module specifiers representing that file: + // + // Filename | Relative Module Specifier Candidates | Path Mapping | Filename Result | Module Specifier Results + // --------------------<----------------------------------------------<------------------------------<-------------------||---------------------------- + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*.d.ts"] <- @app/haha || (none) + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*"] <- (none) || @app/haha, @app/haha.js + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*.d.ts"] <- @app/foo/index || (none) + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*"] <- (none) || @app/foo, @app/foo/index, @app/foo/index.js + // dist/wow.js.js <- dist/wow.js, dist/wow.js.js <- "@app/*": ["./dist/*.js"] <- @app/wow.js || @app/wow, @app/wow.js + // + // The "Filename Result" can be generated only if `pattern` has an extension. Care must be taken that the list of + // relative module specifiers to run the interpolation (a) is actually valid for the module resolution mode, (b) takes + // into account the existence of other files (e.g. 'dist/wow.js' cannot refer to 'dist/wow.js.js' if 'dist/wow.js' + // exists) and (c) that they are ordered by preference. The last row shows that the filename result and module + // specifier results are not mutually exclusive. Note that the filename result is a higher priority in module + // resolution, but as long criteria (b) above is met, I don't think its result needs to be the highest priority result + // in module specifier generation. I have included it last, as it's difficult to tell exactly where it should be + // sorted among the others for a particular value of `importModuleSpecifierEnding`. + var candidates = allowedEndings.map(function (ending) { return ({ + ending: ending, + value: removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) + }); }); + if (ts.tryGetExtensionFromPath(pattern)) { + candidates.push({ ending: undefined, value: relativeToBaseUrl }); + } if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix) || - !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); - return key.replace("*", matchedStar); + var prefix = pattern.substring(0, indexOfStar); + var suffix = pattern.substring(indexOfStar + 1); + for (var _b = 0, candidates_3 = candidates; _b < candidates_3.length; _b++) { + var _c = candidates_3[_b], ending = _c.ending, value = _c.value; + if (value.length >= prefix.length + suffix.length && + ts.startsWith(value, prefix) && + ts.endsWith(value, suffix) && + validateEnding({ ending: ending, value: value })) { + var matchedStar = value.substring(prefix.length, value.length - suffix.length); + return { value: key.replace("*", matchedStar) }; + } } } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; + else if (ts.some(candidates, function (c) { return c.ending !== 0 /* Ending.Minimal */ && pattern === c.value; }) || + ts.some(candidates, function (c) { return c.ending === 0 /* Ending.Minimal */ && pattern === c.value && validateEnding(c); })) { + return { value: key }; } + }; + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } + function validateEnding(_a) { + var ending = _a.ending, value = _a.value; + // Optimization: `removeExtensionAndIndexPostFix` can query the file system (a good bit) if `ending` is `Minimal`, the basename + // is 'index', and a `host` is provided. To avoid that until it's unavoidable, we ran the function with no `host` above. Only + // here, after we've checked that the minimal ending is indeed a match (via the length and prefix/suffix checks / `some` calls), + // do we check that the host-validated result is consistent with the answer we got before. If it's not, it falls back to the + // `Ending.Index` result, which should already be in the list of candidates if `Minimal` was. (Note: the assumption here is + // that every module resolution mode that supports dropping extensions also supports dropping `/index`. Like literally + // everything else in this file, this logic needs to be updated if that's not true in some future module resolution mode.) + return ending !== 0 /* Ending.Minimal */ || value === removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions, host); + } } var MatchingMode; (function (MatchingMode) { @@ -122432,10 +124359,10 @@ var ts; return undefined; } // Simplify the full file path to something that can be resolved by Node. + var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var moduleSpecifier = path; var isPackageRootPath = false; if (!packageNameOnly) { - var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var packageRootIndex = parts.packageRootIndex; var moduleFileName = void 0; while (true) { @@ -122484,15 +124411,13 @@ var ts; var packageRootPath = path.substring(0, packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); var moduleFileToTry = path; + var maybeBlockedByTypesVersions = false; var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) { var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); + var importMode = overrideMode || importingSourceFile.impliedNodeFormat; if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { - // `conditions` *could* be made to go against `importingSourceFile.impliedNodeFormat` if something wanted to generate - // an ImportEqualsDeclaration in an ESM-implied file or an ImportCall in a CJS-implied file. But since this function is - // usually called to conjure an import out of thin air, we don't have an existing usage to call `getModeForUsageAtIndex` - // with, so for now we just stick with the mode of the file. - var conditions = ["node", overrideMode || importingSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext ? "import" : "require", "types"]; + var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"]; var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, ts.getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions) : undefined; @@ -122511,16 +124436,26 @@ var ts; : undefined; if (versionPaths) { var subModuleName = path.slice(packageRootPath.length + 1); - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Ending.Minimal */, options), versionPaths.paths); - if (fromPaths !== undefined) { + var fromPaths = tryGetModuleNameFromPaths(subModuleName, versionPaths.paths, getAllowedEndings(preferences.ending, options, importMode), host, options); + if (fromPaths === undefined) { + maybeBlockedByTypesVersions = true; + } + else { moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths); } } // If the file is the main module, it can be imported by the package name var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; - if (ts.isString(mainFileRelative)) { + if (ts.isString(mainFileRelative) && !(maybeBlockedByTypesVersions && ts.matchPatternOrExact(ts.tryParsePatterns(versionPaths.paths), mainFileRelative))) { + // The 'main' file is also subject to mapping through typesVersions, and we couldn't come up with a path + // explicitly through typesVersions, so if it matches a key in typesVersions now, it's not reachable. + // (The only way this can happen is if some file in a package that's not resolvable from outside the + // package got pulled into the program anyway, e.g. transitively through a file that *is* reachable. It + // happens very easily in fourslash tests though, since every test file listed gets included. See + // importNameCodeFix_typesVersions.ts for an example.) var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + // ^ An arbitrary removal of file extension for this comparison is almost certainly wrong return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry }; } } @@ -122815,23 +124750,46 @@ var ts; var file = _c[_i]; write("".concat(toFileName(file, relativeFileName))); (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write(" ".concat(fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText)); }); - (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); + (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); } } ts.explainFiles = explainFiles; - function explainIfFileIsRedirect(file, fileNameConvertor) { + function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { + var _a; var result; if (file.path !== file.resolvedPath) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); } if (file.redirectInfo) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); } + if (ts.isExternalOrCommonJsModule(file)) { + switch (file.impliedNodeFormat) { + case ts.ModuleKind.ESNext: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + break; + case ts.ModuleKind.CommonJS: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, file.packageJsonScope.packageJsonContent.type ? + ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : + ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + else if ((_a = file.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found)); + } + break; + } + } return result; } - ts.explainIfFileIsRedirect = explainIfFileIsRedirect; + ts.explainIfFileIsRedirectAndImpliedFormat = explainIfFileIsRedirectAndImpliedFormat; function getMatchedFileSpec(program, fileName) { var _a; var configFile = program.getCompilerOptions().configFile; @@ -122848,6 +124806,9 @@ var ts; var configFile = program.getCompilerOptions().configFile; if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedIncludeSpecs)) return undefined; + // Return true if its default include spec + if (configFile.configFileSpecs.isDefaultIncludeSpec) + return true; var isJsonFile = ts.fileExtensionIs(fileName, ".json" /* Extension.Json */); var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); var useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); @@ -122913,11 +124874,13 @@ var ts; if (matchedByFiles) return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Part_of_files_list_in_tsconfig_json); var matchedByInclude = getMatchedIncludeSpec(program, fileName); - return matchedByInclude ? + return ts.isString(matchedByInclude) ? ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) : - // Could be additional files specified as roots - ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation); + // Could be additional files specified as roots or matched by default include + ts.chainDiagnosticMessages(/*details*/ undefined, matchedByInclude ? + ts.Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : + ts.Diagnostics.Root_file_specified_for_compilation); case ts.FileIncludeKind.SourceFromProjectReference: case ts.FileIncludeKind.OutputFromProjectReference: var isOutput = reason.kind === ts.FileIncludeKind.OutputFromProjectReference; @@ -123036,11 +124999,19 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", + AffectingFileLocation: "File location affecting resolution", TypeRoots: "Type roots", ConfigFileOfReferencedProject: "Config file of referened project", ExtendedConfigOfReferencedProject: "Extended config file of referenced project", WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", PackageJson: "package.json file", + ClosedScriptInfo: "Closed Script info", + ConfigFileForInferredRoot: "Config file for the inferred project root", + NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache", + MissingSourceMapFile: "Missing source map file", + NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root", + MissingGeneratedFile: "Missing generated file", + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -123149,6 +125120,7 @@ var ts; createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, storeFilesChangingSignatureDuringEmit: system.storeFilesChangingSignatureDuringEmit, + now: ts.maybeBind(system, system.now), }; } ts.createProgramHost = createProgramHost; @@ -123216,20 +125188,27 @@ var ts; var ts; (function (ts) { function readBuilderProgram(compilerOptions, host) { - if (ts.outFile(compilerOptions)) - return undefined; var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions); if (!buildInfoPath) return undefined; - var content = host.readFile(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); + var buildInfo; + if (host.getBuildInfo) { + // host provides buildinfo, get it from there. This allows host to cache it + buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); + if (!buildInfo) + return undefined; + } + else { + var content = host.readFile(buildInfoPath); + if (!content) + return undefined; + buildInfo = ts.getBuildInfo(content); + } if (buildInfo.version !== ts.version) return undefined; if (!buildInfo.program) return undefined; - return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); + return ts.createBuilderProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); } ts.readBuilderProgram = readBuilderProgram; function createIncrementalCompilerHost(options, system) { @@ -123282,14 +125261,12 @@ var ts; var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc var missingFilesMap; // Map of file watchers for the missing files - var packageJsonMap; // map of watchers for package json files used in module resolution var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations var parsedConfigs; // Parsed commandline and watching cached for referenced projects var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation - var changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution var reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files @@ -123346,6 +125323,7 @@ var ts; compilerHost.getCompilationSettings = function () { return compilerOptions; }; compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect); compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); }; + compilerHost.watchAffectingFileLocation = function (file, cb) { return watchFile(file, cb, ts.PollingInterval.High, watchOptions, ts.WatchType.AffectingFileLocation); }; compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); }; compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations; @@ -123379,6 +125357,9 @@ var ts; return host.resolveTypeReferenceDirectives.apply(host, args); }) : (function (typeDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference, containingFileMode); }); + compilerHost.getModuleResolutionCache = host.resolveModuleNames ? + ts.maybeBind(host, host.getModuleResolutionCache) : + (function () { return resolutionCache.getModuleResolutionCache(); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); @@ -123428,10 +125409,6 @@ var ts; }); parsedConfigs = undefined; } - if (packageJsonMap) { - ts.clearMap(packageJsonMap, ts.closeFileWatcher); - packageJsonMap = undefined; - } } function getCurrentBuilderProgram() { return builderProgram; @@ -123445,12 +125422,12 @@ var ts; var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); - if (program && (changesAffectResolution || ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions))) { + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { resolutionCache.clear(); } } // All resolutions are invalid if user provided resolutions - var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution); + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { @@ -123466,7 +125443,6 @@ var ts; } createNewProgram(hasInvalidatedResolution); } - changesAffectResolution = false; // reset for next sync reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); @@ -123486,16 +125462,11 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + var oldProgram = getCurrentProgram(); builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); - // map package json cache entries to their realpaths so we don't try to watch across symlinks - var packageCacheEntries = ts.map(resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [compilerHost.realpath ? toPath(compilerHost.realpath(path)) : path, data]; - }); - resolutionCache.finishCachingPerDirectoryResolution(); + resolutionCache.finishCachingPerDirectoryResolution(builderProgram.getProgram(), oldProgram); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath); - ts.updatePackageJsonWatch(packageCacheEntries, packageJsonMap || (packageJsonMap = new ts.Map()), watchPackageJsonLookupPath); if (needsUpdateInTypeRootWatch) { resolutionCache.updateTypeRootsWatch(); } @@ -123575,9 +125546,6 @@ var ts; sourceFilesCache.set(path, false); } } - if (sourceFile) { - sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); - } return sourceFile; } return hostSourceFile.sourceFile; @@ -123692,6 +125660,7 @@ var ts; } function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; rootFileNames = ts.getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions); if (ts.updateErrorForNoInputFiles(rootFileNames, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; @@ -123800,21 +125769,6 @@ var ts; ts.noopFileWatcher : watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } - function watchPackageJsonLookupPath(packageJsonPath) { - // If the package.json is pulled into the compilation itself (eg, via json imports), don't add a second watcher here - return sourceFilesCache.has(packageJsonPath) ? - ts.noopFileWatcher : - watchFilePath(packageJsonPath, packageJsonPath, onPackageJsonChange, ts.PollingInterval.High, watchOptions, ts.WatchType.PackageJson); - } - function onPackageJsonChange(fileName, eventKind, path) { - updateCachedSystemWithFile(fileName, path, eventKind); - // package.json changes invalidate module resolution and can change the set of loaded files - // so if we witness a change to one, we have to do a full reload - reloadLevel = ts.ConfigFileProgramReloadLevel.Full; - changesAffectResolution = true; - // Update the program - scheduleProgramUpdate(); - } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { @@ -123972,14 +125926,17 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream"; - UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate"; - UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream"; - UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["OutOfDateBuildInfo"] = 7] = "OutOfDateBuildInfo"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 8] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 9] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 10] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 11] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["UpToDateWithInputFileText"] = 12] = "UpToDateWithInputFileText"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 13] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ForceBuild"] = 14] = "ForceBuild"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); function resolveConfigFileProjectName(project) { if (ts.fileExtensionIs(project, ".json" /* Extension.Json */)) { @@ -124024,9 +125981,12 @@ var ts; function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); }); } - function newer(date1, date2) { - return date2 > date1 ? date2 : date1; + /*@internal*/ + /** Helper to use now method instead of current date for testing purposes to get consistent baselines */ + function getCurrentTime(host) { + return host.now ? host.now() : new Date(); } + ts.getCurrentTime = getCurrentTime; /*@internal*/ function isCircularBuildOrder(buildOrder) { return !!buildOrder && !!buildOrder.buildOrder; @@ -124101,6 +126061,7 @@ var ts; compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); }; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); + compilerHost.getModuleResolutionCache = ts.maybeBind(host, host.getModuleResolutionCache); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { @@ -124116,6 +126077,7 @@ var ts; return ts.loadWithTypeDirectiveCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader_4); }; } + compilerHost.getBuildInfo = function (fileName, configFilePath) { return getBuildInfo(state, fileName, toResolvedConfigFilePath(state, configFilePath), /*modifiedTime*/ undefined); }; var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -124132,8 +126094,9 @@ var ts; resolvedConfigFilePaths: new ts.Map(), configFileCache: new ts.Map(), projectStatus: new ts.Map(), - buildInfoChecked: new ts.Map(), extendedConfigCache: new ts.Map(), + buildInfoCache: new ts.Map(), + outputTimeStamps: new ts.Map(), builderPrograms: new ts.Map(), diagnostics: new ts.Map(), projectPendingBuild: new ts.Map(), @@ -124149,7 +126112,6 @@ var ts; allProjectBuildPending: true, needsSummary: true, watchAllProjectsPending: watch, - currentInvalidatedProject: undefined, // Watch state watch: watch, allWatchedWildcardDirectories: new ts.Map(), @@ -124157,6 +126119,7 @@ var ts; allWatchedConfigFiles: new ts.Map(), allWatchedExtendedConfigFiles: new ts.Map(), allWatchedPackageJsonFiles: new ts.Map(), + filesWatched: new ts.Map(), lastCachedPackageJsonLookups: new ts.Map(), timerToBuildInvalidatedProject: undefined, reportFileChangeDetected: false, @@ -124263,11 +126226,12 @@ var ts; // Config file cache ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete); - ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.buildInfoCache, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.outputTimeStamps, currentProjects, noopOnDelete); // Remove watches for the program no longer in the solution if (state.watch) { ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher }); @@ -124382,7 +126346,6 @@ var ts; })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {})); function doneInvalidatedProject(state, projectPath) { state.projectPendingBuild.delete(projectPath); - state.currentInvalidatedProject = undefined; return state.diagnostics.has(projectPath) ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; @@ -124558,21 +126521,21 @@ var ts; } function emit(writeFileCallback, cancellationToken, customTransformers) { var _a; - var _b, _c; + var _b, _c, _d; ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.Emit); // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly - program.backupState(); + var saved = program.saveEmitState(); var declDiagnostics; var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; var outputFiles = []; var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, /*write*/ undefined, - /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, + /*reportSummary*/ undefined, function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark, buildInfo: data === null || data === void 0 ? void 0 : data.buildInfo }); }, cancellationToken, /*emitOnlyDts*/ false, customTransformers || ((_c = (_b = state.host).getCustomTransformers) === null || _c === void 0 ? void 0 : _c.call(_b, project))).emitResult; // Don't emit .d.ts if there are decl file errors if (declDiagnostics) { - program.restoreState(); + program.restoreEmitState(saved); (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step); return { emitSkipped: true, @@ -124581,38 +126544,38 @@ var ts; } // Actual Emit var host = state.host, compilerHost = state.compilerHost; - var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; - var newestDeclarationFileContentChangedTime = minimumDate; - var anyDtsChanged = false; + var resultFlags = ((_d = program.hasChangedEmitSignature) === null || _d === void 0 ? void 0 : _d.call(program)) ? BuildResultFlags.None : BuildResultFlags.DeclarationOutputUnchanged; var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var options = program.getCompilerOptions(); + var isIncremental = ts.isIncrementalCompilation(options); + var outputTimeStampMap; + var now; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; - var priorChangeTime; - if (!anyDtsChanged && ts.isDeclarationFileName(name)) { - // Check for unchanged .d.ts files - if (host.fileExists(name) && state.readFileWithCache(name) === text) { - priorChangeTime = host.getModifiedTime(name); - } - else { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - anyDtsChanged = true; - } - } + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; + var path = toPath(state, name); emittedOutputs.set(toPath(state, name), name); + if (buildInfo) + setBuildInfo(state, buildInfo, projectPath, options, resultFlags); ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); - if (priorChangeTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + if (!isIncremental && state.watch) { + (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); } }); - finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); + finishEmit(emitterDiagnostics, emittedOutputs, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); return emitResult; } function emitBuildInfo(writeFileCallback, cancellationToken) { ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.EmitBuildInfo); - var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken); + var emitResult = program.emitBuildInfo(function (name, text, writeByteOrderMark, onError, sourceFiles, data) { + if (data === null || data === void 0 ? void 0 : data.buildInfo) + setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), BuildResultFlags.DeclarationOutputUnchanged); + if (writeFileCallback) + writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); + else + state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); + }, cancellationToken); if (emitResult.diagnostics.length) { reportErrors(state, emitResult.diagnostics); state.diagnostics.set(projectPath, __spreadArray(__spreadArray([], state.diagnostics.get(projectPath), true), emitResult.diagnostics, true)); @@ -124625,7 +126588,7 @@ var ts; step = BuildStep.QueueReferencingProjects; return emitResult; } - function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) { + function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) { var _a; var emitDiagnostics = emitterDiagnostics.getDiagnostics(); if (emitDiagnostics.length) { @@ -124636,13 +126599,10 @@ var ts; emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); }); } // Update time stamps for rest of the outputs - var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); + updateOutputTimestampsWorker(state, config, projectPath, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); state.diagnostics.delete(projectPath); state.projectStatus.set(projectPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ? - maximumDate : - newestDeclarationFileContentChangedTime, oldestOutputFileName: oldestOutputFileName }); afterProgramDone(state, program, config); @@ -124677,13 +126637,21 @@ var ts; ts.Debug.assert(!!outputFiles.length); var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; + var existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var _b, _c; + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; emittedOutputs.set(toPath(state, name), name); + if (buildInfo) { + if (((_b = buildInfo.program) === null || _b === void 0 ? void 0 : _b.outSignature) !== ((_c = existingBuildInfo.program) === null || _c === void 0 ? void 0 : _c.outSignature)) { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + } + setBuildInfo(state, buildInfo, projectPath, config.options, resultFlags); + } ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); }); - var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged); + var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, outputFiles[0].name, resultFlags); return { emitSkipped: false, diagnostics: emitDiagnostics }; } function executeSteps(till, cancellationToken, writeFile, customTransformers) { @@ -124733,17 +126701,11 @@ var ts; !!ts.getConfigFileParsingDiagnostics(config).length || !ts.isIncrementalCompilation(config.options); } - function getNextInvalidatedProject(state, buildOrder, reportQueue) { + function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { if (!state.projectPendingBuild.size) return undefined; if (isCircularBuildOrder(buildOrder)) return undefined; - if (state.currentInvalidatedProject) { - // Only if same buildOrder the currentInvalidated project can be sent again - return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ? - state.currentInvalidatedProject : - undefined; - } var options = state.options, projectPendingBuild = state.projectPendingBuild; for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { var project = buildOrder[projectIndex]; @@ -124776,9 +126738,9 @@ var ts; watchPackageJsonFiles(state, project, projectPath, config); } var status = getUpToDateStatus(state, config, projectPath); - verboseReportProjectStatus(state, project, status); if (!options.force) { if (status.type === ts.UpToDateStatusType.UpToDate) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Up to date, skip @@ -124788,12 +126750,20 @@ var ts; } continue; } - if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) { + if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes || status.type === ts.UpToDateStatusType.UpToDateWithInputFileText) { reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); - return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder); + return { + kind: InvalidatedProjectKind.UpdateOutputFileStamps, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config + }; } } if (status.type === ts.UpToDateStatusType.UpstreamBlocked) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); if (options.verbose) { @@ -124804,17 +126774,37 @@ var ts; continue; } if (status.type === ts.UpToDateStatusType.ContainerOnly) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Do nothing continue; } - return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ? - InvalidatedProjectKind.Build : - InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder); + return { + kind: needsBuild(state, status, config) ? + InvalidatedProjectKind.Build : + InvalidatedProjectKind.UpdateBundle, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config, + }; } return undefined; } + function createInvalidatedProjectWithInfo(state, info, buildOrder) { + verboseReportProjectStatus(state, info.project, info.status); + return info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps ? + createBuildOrUpdateInvalidedProject(info.kind, state, info.project, info.projectPath, info.projectIndex, info.config, buildOrder) : + createUpdateOutputFileStampsProject(state, info.project, info.projectPath, info.config, buildOrder); + } + function getNextInvalidatedProject(state, buildOrder, reportQueue) { + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); + if (!info) + return info; + return createInvalidatedProjectWithInfo(state, info, buildOrder); + } function listEmittedFile(_a, proj, file) { var write = _a.write; if (write && proj.options.listEmittedFiles) { @@ -124832,7 +126822,7 @@ var ts; } function afterProgramDone(state, program, config) { if (program) { - if (program && state.write) + if (state.write) ts.listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); @@ -124845,7 +126835,8 @@ var ts; state.projectCompilerOptions = state.baseCompilerOptions; } function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) { - var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions()); + // Since buildinfo has changeset and diagnostics when doing multi file emit, only --out cannot emit buildinfo if it has errors + var canEmitBuildInfo = program && !ts.outFile(program.getCompilerOptions()); reportAndStoreErrors(state, resolvedPath, diagnostics); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: "".concat(errorType, " errors") }); if (canEmitBuildInfo) @@ -124853,9 +126844,107 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } + function isFileWatcherWithModifiedTime(value) { + return !!value.watcher; + } + function getModifiedTime(state, fileName) { + var path = toPath(state, fileName); + var existing = state.filesWatched.get(path); + if (state.watch && !!existing) { + if (!isFileWatcherWithModifiedTime(existing)) + return existing; + if (existing.modifiedTime) + return existing.modifiedTime; + } + // In watch mode we store the modified times in the cache + // This is either Date | FileWatcherWithModifiedTime because we query modified times first and + // then after complete compilation of the project, watch the files so we dont want to loose these modified times. + var result = ts.getModifiedTime(state.host, fileName); + if (state.watch) { + if (existing) + existing.modifiedTime = result; + else + state.filesWatched.set(path, result); + } + return result; + } + function watchFile(state, file, callback, pollingInterval, options, watchType, project) { + var path = toPath(state, file); + var existing = state.filesWatched.get(path); + if (existing && isFileWatcherWithModifiedTime(existing)) { + existing.callbacks.push(callback); + } + else { + var watcher = state.watchFile(file, function (fileName, eventKind, modifiedTime) { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + existing.modifiedTime = modifiedTime; + existing.callbacks.forEach(function (cb) { return cb(fileName, eventKind, modifiedTime); }); + }, pollingInterval, options, watchType, project); + state.filesWatched.set(path, { callbacks: [callback], watcher: watcher, modifiedTime: existing }); + } + return { + close: function () { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + if (existing.callbacks.length === 1) { + state.filesWatched.delete(path); + ts.closeFileWatcherOf(existing); + } + else { + ts.unorderedRemoveItem(existing.callbacks, callback); + } + } + }; + } + function getOutputTimeStampMap(state, resolvedConfigFilePath) { + // Output timestamps are stored only in watch mode + if (!state.watch) + return undefined; + var result = state.outputTimeStamps.get(resolvedConfigFilePath); + if (!result) + state.outputTimeStamps.set(resolvedConfigFilePath, result = new ts.Map()); + return result; + } + function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) { + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(options); + var existing = getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath); + var modifiedTime = getCurrentTime(state.host); + if (existing) { + existing.buildInfo = buildInfo; + existing.modifiedTime = modifiedTime; + if (!(resultFlags & BuildResultFlags.DeclarationOutputUnchanged)) + existing.latestChangedDtsTime = modifiedTime; + } + else { + state.buildInfoCache.set(resolvedConfigPath, { + path: toPath(state, buildInfoPath), + buildInfo: buildInfo, + modifiedTime: modifiedTime, + latestChangedDtsTime: resultFlags & BuildResultFlags.DeclarationOutputUnchanged ? undefined : modifiedTime, + }); + } + } + function getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + return (existing === null || existing === void 0 ? void 0 : existing.path) === path ? existing : undefined; + } + function getBuildInfo(state, buildInfoPath, resolvedConfigPath, modifiedTime) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + if (existing !== undefined && existing.path === path) { + return existing.buildInfo || undefined; + } + var value = state.readFileWithCache(buildInfoPath); + var buildInfo = value ? ts.getBuildInfo(value) : undefined; + ts.Debug.assert(modifiedTime || !buildInfo); + state.buildInfoCache.set(resolvedConfigPath, { path: path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || ts.missingFileModifiedTime }); + return buildInfo; + } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = ts.getModifiedTime(state.host, configFile); + var tsconfigTime = getModifiedTime(state, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -124865,88 +126954,24 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { - var force = !!state.options.force; - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - var host = state.host; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: ts.UpToDateStatusType.Unbuildable, - reason: "".concat(inputFile, " does not exist") - }; - } - if (!force) { - var inputTime = ts.getModifiedTime(host, inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - } + var _a, _b; // Container if no files are specified in the project if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) { return { type: ts.UpToDateStatusType.ContainerOnly }; } - // Collect the expected outputs of this project - var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - if (!force) { - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = ts.getModifiedTime(host, output); - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (ts.isDeclarationFileName(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; + // Fast check to see if reference projects are upto date and error free + var referenceStatuses; + var force = !!state.options.force; if (project.projectReferences) { state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream }); - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); + for (var _i = 0, _c = project.projectReferences; _i < _c.length; _i++) { + var ref = _c[_i]; var resolvedRef = ts.resolveProjectReferencePath(ref); var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef); - var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath); + var resolvedConfig = parseConfigFile(state, resolvedRef, resolvedRefPath); + var refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath); // Its a circular reference ignore the status of this project if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream || refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project @@ -124968,75 +126993,192 @@ var ts; upstreamProjectName: ref.path }; } - // Check oldest output file name only if there is no missing output file name - // (a check we will have skipped if this is a forced build) - if (!force && !missingOutputFileName) { - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + if (!force) + (referenceStatuses || (referenceStatuses = [])).push({ ref: ref, refStatus: refStatus, resolvedRefPath: resolvedRefPath, resolvedConfig: resolvedConfig }); + } + } + if (force) + return { type: ts.UpToDateStatusType.ForceBuild }; + // Check buildinfo first + var host = state.host; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); + var oldestOutputFileName; + var oldestOutputFileTime = maximumDate; + var buildInfoTime; + var buildInfoProgram; + var buildInfoVersionMap; + if (buildInfoPath) { + var buildInfoCacheEntry_1 = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath); + buildInfoTime = (buildInfoCacheEntry_1 === null || buildInfoCacheEntry_1 === void 0 ? void 0 : buildInfoCacheEntry_1.modifiedTime) || ts.getModifiedTime(host, buildInfoPath); + if (buildInfoTime === ts.missingFileModifiedTime) { + if (!buildInfoCacheEntry_1) { + state.buildInfoCache.set(resolvedPath, { + path: toPath(state, buildInfoPath), + buildInfo: false, + modifiedTime: buildInfoTime + }); + } + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: buildInfoPath + }; + } + var buildInfo = ts.Debug.checkDefined(getBuildInfo(state, buildInfoPath, resolvedPath, buildInfoTime)); + if ((buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + return { + type: ts.UpToDateStatusType.TsVersionOutputOfDate, + version: buildInfo.version + }; + } + if (buildInfo.program) { + // If there are pending changes that are not emitted, project is out of date + 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))) { return { - type: ts.UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path + type: ts.UpToDateStatusType.OutOfDateBuildInfo, + buildInfoFile: buildInfoPath }; } + buildInfoProgram = buildInfo.program; } + oldestOutputFileTime = buildInfoTime; + oldestOutputFileName = buildInfoPath; } - if (missingOutputFileName !== undefined) { - return { - type: ts.UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; + // Check input files + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + /** True if input file has changed timestamp but text is not changed, we can then do only timestamp updates on output to make it look up-to-date later */ + var pseudoInputUpToDate = false; + // Get timestamps of input files + for (var _d = 0, _e = project.fileNames; _d < _e.length; _d++) { + var inputFile = _e[_d]; + var inputTime = getModifiedTime(state, inputFile); + if (inputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.Unbuildable, + reason: "".concat(inputFile, " does not exist") + }; + } + // If an buildInfo is older than the newest input, we can stop checking + if (buildInfoTime && buildInfoTime < inputTime) { + var version_3 = void 0; + var currentVersion = void 0; + if (buildInfoProgram) { + // Read files and see if they are same, read is anyways cached + if (!buildInfoVersionMap) + buildInfoVersionMap = ts.getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + version_3 = buildInfoVersionMap.get(toPath(state, inputFile)); + var text = version_3 ? state.readFileWithCache(inputFile) : undefined; + currentVersion = text && (host.createHash || ts.generateDjb2Hash)(text); + if (version_3 && version_3 === currentVersion) + pseudoInputUpToDate = true; + } + if (!version_3 || version_3 !== currentVersion) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: buildInfoPath, + newerInputFileName: inputFile + }; + } + } + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - if (isOutOfDateWithInputs) { - return { - type: ts.UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; + // Now see if all outputs are newer than the newest input + // Dont check output timestamps if we have buildinfo telling us output is uptodate + if (!buildInfoPath) { + // Collect the expected outputs of this project + var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, resolvedPath); + for (var _f = 0, outputs_1 = outputs; _f < outputs_1.length; _f++) { + var output = outputs_1[_f]; + var path = toPath(state, output); + // Output is missing; can stop checking + var outputTime = outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.get(path); + if (!outputTime) { + outputTime = ts.getModifiedTime(state.host, output); + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.set(path, outputTime); + } + if (outputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: output + }; + } + // If an output is older than the newest input, we can stop checking + if (outputTime < newestInputFileTime) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: output, + newerInputFileName: newestInputFileName + }; + } + // No need to get newestDeclarationFileContentChangedTime since thats needed only for composite projects + // And composite projects are the only ones that can be referenced + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + } } - else { - // Check tsconfig time - var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); - if (configStatus) - return configStatus; - // Check extended config time - var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); - if (extendedConfigStatus) - return extendedConfigStatus; - // Check package file time - var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { - var path = _a[0]; - return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); - }); - if (dependentPackageFileStatus) - return dependentPackageFileStatus; - } - if (!force && !state.buildInfoChecked.has(resolvedPath)) { - state.buildInfoChecked.set(resolvedPath, true); - var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); - if (buildInfoPath) { - var value = state.readFileWithCache(buildInfoPath); - var buildInfo = value && ts.getBuildInfo(value); - if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + var seenRefs = buildInfoPath ? new ts.Set() : undefined; + var buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath); + seenRefs === null || seenRefs === void 0 ? void 0 : seenRefs.add(resolvedPath); + /** Inputs are up-to-date, just need either timestamp update or bundle prepend manipulation to make it look up-to-date */ + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (referenceStatuses) { + for (var _g = 0, referenceStatuses_1 = referenceStatuses; _g < referenceStatuses_1.length; _g++) { + var _h = referenceStatuses_1[_g], ref = _h.ref, refStatus = _h.refStatus, resolvedConfig = _h.resolvedConfig, resolvedRefPath = _h.resolvedRefPath; + usesPrepend = usesPrepend || !!(ref.prepend); + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // Check if tsbuildinfo path is shared, then we need to rebuild + if (buildInfoCacheEntry && hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath)) { return { - type: ts.UpToDateStatusType.TsVersionOutputOfDate, - version: buildInfo.version + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: buildInfoPath, + newerProjectName: ref.path }; } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + var newestDeclarationFileContentChangedTime = getLatestChangedDtsTime(state, resolvedConfig.options, resolvedRefPath); + if (newestDeclarationFileContentChangedTime && newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + // Check package file time + var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { + var path = _a[0]; + return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); + }); + if (dependentPackageFileStatus) + return dependentPackageFileStatus; if (usesPrepend && pseudoUpToDate) { return { type: ts.UpToDateStatusType.OutOfDateWithPrepend, @@ -125046,15 +127188,36 @@ var ts; } // Up to date return { - type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + type: pseudoUpToDate ? + ts.UpToDateStatusType.UpToDateWithUpstreamTypes : + pseudoInputUpToDate ? + ts.UpToDateStatusType.UpToDateWithInputFileText : + ts.UpToDateStatusType.UpToDate, newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, oldestOutputFileName: oldestOutputFileName }; } + function hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath) { + if (seenRefs.has(resolvedRefPath)) + return false; + seenRefs.add(resolvedRefPath); + var refBuildInfo = state.buildInfoCache.get(resolvedRefPath); + if (refBuildInfo.path === buildInfoCacheEntry.path) + return true; + if (resolvedConfig.projectReferences) { + // Check references + for (var _i = 0, _a = resolvedConfig.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRef = ts.resolveProjectReferencePath(ref); + var resolvedRefPath_1 = toResolvedConfigFilePath(state, resolvedRef); + var resolvedConfig_1 = parseConfigFile(state, resolvedRef, resolvedRefPath_1); + if (hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig_1, resolvedRefPath_1)) + return true; + } + } + return false; + } function getUpToDateStatus(state, project, resolvedPath) { if (project === undefined) { return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; @@ -125067,39 +127230,71 @@ var ts; state.projectStatus.set(resolvedPath, actual); return actual; } - function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) { if (proj.options.noEmit) - return priorNewestUpdateTime; + return; + var now; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(proj.options); + if (buildInfoPath) { + // For incremental projects, only buildinfo needs to be upto date with timestamp check + // as we dont check output files for up-to-date ness + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(toPath(state, buildInfoPath)))) { + if (!!state.options.verbose) + reportStatus(state, verboseMessage, proj.options.configFilePath); + state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); + getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; + } + state.outputTimeStamps.delete(projectPath); + return; + } var host = state.host; var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, projectPath); + var modifiedOutputs = outputTimeStampMap ? new ts.Set() : undefined; if (!skipOutputs || outputs.length !== skipOutputs.size) { var reportVerbose = !!state.options.verbose; - var now = host.now ? host.now() : new Date(); for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { var file = outputs_2[_i]; - if (skipOutputs && skipOutputs.has(toPath(state, file))) { + var path = toPath(state, file); + if (skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(path)) continue; - } if (reportVerbose) { reportVerbose = false; reportStatus(state, verboseMessage, proj.options.configFilePath); } - if (ts.isDeclarationFileName(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); + host.setModifiedTime(file, now || (now = getCurrentTime(state.host))); + // Store output timestamps in a map because non incremental build will need to check them to determine up-to-dateness + if (outputTimeStampMap) { + outputTimeStampMap.set(path, now); + modifiedOutputs.add(path); } - host.setModifiedTime(file, now); } } - return priorNewestUpdateTime; + // Clear out timestamps not in output list any more + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.forEach(function (_value, key) { + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) + outputTimeStampMap.delete(key); + }); + } + function getLatestChangedDtsTime(state, options, resolvedConfigPath) { + if (!options.composite) + return undefined; + var entry = ts.Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); + if (entry.latestChangedDtsTime !== undefined) + return entry.latestChangedDtsTime || undefined; + var latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? + state.host.getModifiedTime(ts.getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, ts.getDirectoryPath(entry.path))) : + undefined; + entry.latestChangedDtsTime = latestChangedDtsTime || false; + return latestChangedDtsTime; } function updateOutputTimestamps(state, proj, resolvedPath) { if (state.options.dry) { return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath); } - var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); + updateOutputTimestampsWorker(state, proj, resolvedPath, ts.Diagnostics.Updating_output_timestamps_of_project_0); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: priorNewestUpdateTime, oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames()) }); } @@ -125145,6 +127340,7 @@ var ts; break; } // falls through + case ts.UpToDateStatusType.UpToDateWithInputFileText: case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: case ts.UpToDateStatusType.OutOfDateWithPrepend: if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { @@ -125255,9 +127451,9 @@ var ts; function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) { state.reportFileChangeDetected = true; invalidateProject(state, resolvedPath, reloadLevel); - scheduleBuildInvalidatedProject(state); + scheduleBuildInvalidatedProject(state, 250, /*changeDetected*/ true); } - function scheduleBuildInvalidatedProject(state) { + function scheduleBuildInvalidatedProject(state, time, changeDetected) { var hostWithWatch = state.hostWithWatch; if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; @@ -125265,25 +127461,38 @@ var ts; if (state.timerToBuildInvalidatedProject) { hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject); } - state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state); + state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, state, changeDetected); } - function buildNextInvalidatedProject(state) { + function buildNextInvalidatedProject(state, changeDetected) { state.timerToBuildInvalidatedProject = undefined; if (state.reportFileChangeDetected) { state.reportFileChangeDetected = false; state.projectErrorsReported.clear(); reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation); } + var projectsBuilt = 0; var buildOrder = getBuildOrder(state); var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false); if (invalidatedProject) { invalidatedProject.done(); - if (state.projectPendingBuild.size) { - // Schedule next project for build - if (state.watch && !state.timerToBuildInvalidatedProject) { - scheduleBuildInvalidatedProject(state); + projectsBuilt++; + while (state.projectPendingBuild.size) { + // If already scheduled, skip + if (state.timerToBuildInvalidatedProject) + return; + // Before scheduling check if the next project needs build + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, /*reportQueue*/ false); + if (!info) + break; // Nothing to build any more + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps && (changeDetected || projectsBuilt === 5)) { + // Schedule next project for build + scheduleBuildInvalidatedProject(state, 100, /*changeDetected*/ false); + return; } - return; + var project = createInvalidatedProjectWithInfo(state, info, buildOrder); + project.done(); + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps) + projectsBuilt++; } } disableCache(state); @@ -125292,12 +127501,10 @@ var ts; function watchConfigFile(state, resolved, resolvedPath, parsed) { if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; - state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(resolved, function () { - invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); - }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); + state.allWatchedConfigFiles.set(resolvedPath, watchFile(state, resolved, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(state, extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -125329,7 +127536,7 @@ var ts; if (!state.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), { - createNewValue: function (_path, input) { return state.watchFile(input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, + createNewValue: function (_path, input) { return watchFile(state, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -125337,7 +127544,7 @@ var ts; if (!state.watch || !state.lastCachedPackageJsonLookups) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), new ts.Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), { - createNewValue: function (path, _input) { return state.watchFile(path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, + createNewValue: function (path, _input) { return watchFile(state, path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -125387,8 +127594,6 @@ var ts; return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath); }, invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); }, - buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); }, - getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); }, close: function () { return stopWatching(state); }, }; } @@ -125469,19 +127674,18 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { - if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { - return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); - } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); case ts.UpToDateStatusType.OutOfDateWithUpstream: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.OutputMissing: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName)); + case ts.UpToDateStatusType.OutOfDateBuildInfo: + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), relName(state, status.buildInfoFile)); case ts.UpToDateStatusType.UpToDate: if (status.newestInputFileTime !== undefined) { - return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); } // Don't report anything for "up to date because it was already built" -- too verbose break; @@ -125489,6 +127693,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName)); + case ts.UpToDateStatusType.UpToDateWithInputFileText: + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, relName(state, configFileName)); case ts.UpToDateStatusType.UpstreamOutOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName)); case ts.UpToDateStatusType.UpstreamBlocked: @@ -125499,6 +127705,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason); case ts.UpToDateStatusType.TsVersionOutputOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, ts.version); + case ts.UpToDateStatusType.ForceBuild: + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); case ts.UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects // falls through @@ -125665,7 +127873,7 @@ var ts; * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ - function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry, compilerOptions) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } @@ -125683,12 +127891,14 @@ var ts; addInferredTypings(typeAcquisition.include, "Explicitly included types"); var exclude = typeAcquisition.exclude || []; // Directories to search for package.json, bower.json and other typing information - var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); - possibleSearchDirs.add(projectRootPath); - possibleSearchDirs.forEach(function (searchDir) { - getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); - getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); - }); + if (!compilerOptions.types) { + var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); + possibleSearchDirs.add(projectRootPath); + possibleSearchDirs.forEach(function (searchDir) { + getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); + getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); + }); + } if (!typeAcquisition.disableFilenameBasedTypeAcquisition) { getTypingNamesFromSourceFileNames(fileNames); } @@ -127051,6 +129261,8 @@ var ts; case 256 /* SyntaxKind.FunctionDeclaration */: case 213 /* SyntaxKind.FunctionExpression */: return getAdjustedLocationForFunction(node); + case 171 /* SyntaxKind.Constructor */: + return node; } } if (ts.isNamedDeclaration(node)) { @@ -127139,7 +129351,7 @@ var ts; // // NOTE: If the node is a modifier, we don't adjust its location if it is the `default` modifier as that is handled // specially by `getSymbolAtLocation`. - if (ts.isModifier(node) && (forRename || node.kind !== 88 /* SyntaxKind.DefaultKeyword */) ? ts.contains(parent.modifiers, node) : + if (ts.isModifier(node) && (forRename || node.kind !== 88 /* SyntaxKind.DefaultKeyword */) ? ts.canHaveModifiers(parent) && ts.contains(parent.modifiers, node) : node.kind === 84 /* SyntaxKind.ClassKeyword */ ? ts.isClassDeclaration(parent) || ts.isClassExpression(node) : node.kind === 98 /* SyntaxKind.FunctionKeyword */ ? ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(node) : node.kind === 118 /* SyntaxKind.InterfaceKeyword */ ? ts.isInterfaceDeclaration(parent) : @@ -127378,12 +129590,18 @@ var ts; // flag causes us to return the first node whose end position matches the position and which produces and acceptable token // kind. Meanwhile, if includePrecedingTokenAtEndPosition is unset, we look for the first node whose start is <= the // position and whose end is greater than the position. + // There are more sophisticated end tests later, but this one is very fast + // and allows us to skip a bunch of work + var end = children[middle].getEnd(); + if (end < position) { + return -1 /* Comparison.LessThan */; + } var start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { return 1 /* Comparison.GreaterThan */; } // first element whose start position is before the input and whose end position is after or equal to the input - if (nodeContainsPosition(children[middle])) { + if (nodeContainsPosition(children[middle], start, end)) { if (children[middle - 1]) { // we want the _first_ element that contains the position, so left-recur if the prior node also contains the position if (nodeContainsPosition(children[middle - 1])) { @@ -127415,13 +129633,16 @@ var ts; case "continue-outer": continue outer; } } - function nodeContainsPosition(node) { - var start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true); + function nodeContainsPosition(node, start, end) { + end !== null && end !== void 0 ? end : (end = node.getEnd()); + if (end < position) { + return false; + } + start !== null && start !== void 0 ? start : (start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true)); if (start > position) { // If this child begins after position, then all subsequent children will as well. return false; } - var end = node.getEnd(); if (position < end || (position === end && (node.kind === 1 /* SyntaxKind.EndOfFileToken */ || includeEndPosition))) { return true; } @@ -128119,7 +130340,6 @@ var ts; ts.makeImportIfNecessary = makeImportIfNecessary; function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) { return ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? ts.factory.createNamedImports(namedImports) : undefined) : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier, @@ -128209,7 +130429,7 @@ var ts; node.getEnd() <= ts.textSpanEnd(span); } function findModifier(node, kind) { - return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + return ts.canHaveModifiers(node) ? ts.find(node.modifiers, function (m) { return m.kind === kind; }) : undefined; } ts.findModifier = findModifier; function insertImports(changes, sourceFile, imports, blankLineBetween) { @@ -128288,6 +130508,41 @@ var ts; return true; } ts.isTextWhiteSpaceLike = isTextWhiteSpaceLike; + function getMappedLocation(location, sourceMapper, fileExists) { + var mapsTo = sourceMapper.tryGetSourcePosition(location); + return mapsTo && (!fileExists || fileExists(ts.normalizePath(mapsTo.fileName)) ? mapsTo : undefined); + } + ts.getMappedLocation = getMappedLocation; + function getMappedDocumentSpan(documentSpan, sourceMapper, fileExists) { + var fileName = documentSpan.fileName, textSpan = documentSpan.textSpan; + var newPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start }, sourceMapper, fileExists); + if (!newPosition) + return undefined; + var newEndPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start + textSpan.length }, sourceMapper, fileExists); + var newLength = newEndPosition + ? newEndPosition.pos - newPosition.pos + : textSpan.length; // This shouldn't happen + return { + fileName: newPosition.fileName, + textSpan: { + start: newPosition.pos, + length: newLength, + }, + originalFileName: documentSpan.fileName, + originalTextSpan: documentSpan.textSpan, + contextSpan: getMappedContextSpan(documentSpan, sourceMapper, fileExists), + originalContextSpan: documentSpan.contextSpan + }; + } + ts.getMappedDocumentSpan = getMappedDocumentSpan; + function getMappedContextSpan(documentSpan, sourceMapper, fileExists) { + var contextSpanStart = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, sourceMapper, fileExists); + var contextSpanEnd = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length }, sourceMapper, fileExists); + return contextSpanStart && contextSpanEnd ? + { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : + undefined; + } + ts.getMappedContextSpan = getMappedContextSpan; // #endregion // Display-part writer helpers // #region @@ -128781,7 +131036,7 @@ var ts; for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { var change = textChanges_1[_b]; var span = change.span, newText = change.newText; - var index = indexInTextChange(newText, name); + var index = indexInTextChange(newText, ts.escapeString(name)); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. @@ -129749,32 +132004,41 @@ var ts; || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } - function forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, cb) { + function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { var _a, _b; - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var excludePatterns = preferences.autoImportFileExcludePatterns && ts.mapDefined(preferences.autoImportFileExcludePatterns, function (spec) { + // The client is expected to send rooted path specs since we don't know + // what directory a relative path is relative to. + var pattern = ts.getPatternFromSpec(spec, "", "exclude"); + return pattern ? ts.getRegexFromPattern(pattern, useCaseSensitiveFileNames) : undefined; + }); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); var autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)); if (autoImportProvider) { var start = ts.timestamp(); - forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); + forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: ".concat(ts.timestamp() - start)); } } ts.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModule(checker, allSourceFiles, cb) { - for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { - var ambient = _a[_i]; - if (!ts.stringContains(ambient.name, "*")) { + function forEachExternalModule(checker, allSourceFiles, excludePatterns, cb) { + var _a; + var isExcluded = function (fileName) { return excludePatterns === null || excludePatterns === void 0 ? void 0 : excludePatterns.some(function (p) { return p.test(fileName); }); }; + for (var _i = 0, _b = checker.getAmbientModules(); _i < _b.length; _i++) { + var ambient = _b[_i]; + if (!ts.stringContains(ambient.name, "*") && !(excludePatterns && ((_a = ambient.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return isExcluded(d.getSourceFile().fileName); })))) { cb(ambient, /*sourceFile*/ undefined); } } - for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { - var sourceFile = allSourceFiles_1[_b]; - if (ts.isExternalOrCommonJsModule(sourceFile)) { + for (var _c = 0, allSourceFiles_1 = allSourceFiles; _c < allSourceFiles_1.length; _c++) { + var sourceFile = allSourceFiles_1[_c]; + if (ts.isExternalOrCommonJsModule(sourceFile) && !isExcluded(sourceFile.fileName)) { cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } } } - function getExportInfoMap(importingFile, host, program, cancellationToken) { + function getExportInfoMap(importingFile, host, program, preferences, cancellationToken) { var _a, _b, _c, _d, _e; var start = ts.timestamp(); // Pulling the AutoImportProvider project will trigger its updateGraph if pending, @@ -129794,7 +132058,7 @@ var ts; var compilerOptions = program.getCompilerOptions(); var moduleCount = 0; try { - forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { + forEachExternalModuleToImportFrom(program, host, preferences, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { if (++moduleCount % 100 === 0) cancellationToken === null || cancellationToken === void 0 ? void 0 : cancellationToken.throwIfCancellationRequested(); var seenExports = new ts.Map(); @@ -131135,6 +133399,26 @@ var ts; (function (Completions) { var StringCompletions; (function (StringCompletions) { + var _a; + var kindPrecedence = (_a = {}, + _a["directory" /* ScriptElementKind.directory */] = 0, + _a["script" /* ScriptElementKind.scriptElement */] = 1, + _a["external module name" /* ScriptElementKind.externalModuleName */] = 2, + _a); + function createNameAndKindSet() { + var map = new ts.Map(); + function add(value) { + var existing = map.get(value.name); + if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value.kind]) { + map.set(value.name, value); + } + } + return { + add: add, + has: map.has.bind(map), + values: map.values.bind(map), + }; + } function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); @@ -131238,11 +133522,11 @@ var ts; var parent = walkUpParentheses(node.parent); switch (parent.kind) { case 196 /* SyntaxKind.LiteralType */: { - var grandParent = walkUpParentheses(parent.parent); - switch (grandParent.kind) { + var grandParent_1 = walkUpParentheses(parent.parent); + switch (grandParent_1.kind) { + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: case 178 /* SyntaxKind.TypeReference */: { - var typeReference_1 = grandParent; - var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === typeReference_1; }); + var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === grandParent_1; }); if (typeArgument) { return { kind: 2 /* StringLiteralCompletionKind.Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), isNewIdentifier: false }; } @@ -131255,7 +133539,7 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - var _a = grandParent, indexType = _a.indexType, objectType = _a.objectType; + var _a = grandParent_1, indexType = _a.indexType, objectType = _a.objectType; if (!ts.rangeContainsPosition(indexType, position)) { return undefined; } @@ -131263,11 +133547,11 @@ var ts; case 200 /* SyntaxKind.ImportType */: return { kind: 0 /* StringLiteralCompletionKind.Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; case 187 /* SyntaxKind.UnionType */: { - if (!ts.isTypeReferenceNode(grandParent.parent)) { + if (!ts.isTypeReferenceNode(grandParent_1.parent)) { return undefined; } - var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent); - var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(grandParent_1, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent_1)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); return { kind: 2 /* StringLiteralCompletionKind.Types */, types: types, isNewIdentifier: false }; } default: @@ -131416,11 +133700,12 @@ var ts; } function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { var literalValue = ts.normalizeSlashes(node.text); + var mode = ts.isStringLiteralLike(node) ? ts.getModeForUsageLocation(sourceFile, node) : undefined; var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, getIncludeExtensionOption()) - : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, compilerOptions, host, getIncludeExtensionOption(), typeChecker); function getIncludeExtensionOption() { var mode = ts.isStringLiteralLike(node) ? ts.getModeForUsageLocation(sourceFile, node) : undefined; return preferences.importModuleSpecifierEnding === "js" || mode === ts.ModuleKind.ESNext ? 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */ : 0 /* IncludeExtensionsOption.Exclude */; @@ -131436,7 +133721,7 @@ var ts; return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + return ts.arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath).values()); } } function isEmitResolutionKindUsingNodeModules(compilerOptions) { @@ -131472,7 +133757,7 @@ var ts; var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); - return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); + return ts.flatMap(baseDirectories, function (baseDirectory) { return ts.arrayFrom(getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude).values()); }); } var IncludeExtensionsOption; (function (IncludeExtensionsOption) { @@ -131483,9 +133768,9 @@ var ts; /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { - var extensions = _a.extensions, includeExtensionsOption = _a.includeExtensionsOption; - if (result === void 0) { result = []; } + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensionOptions, host, exclude, result) { + var _a; + if (result === void 0) { result = createNameAndKindSet(); } if (fragment === undefined) { fragment = ""; } @@ -131501,92 +133786,124 @@ var ts; fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths var absolutePath = ts.resolvePath(scriptPath, fragment); var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); + // check for a version redirect + var packageJsonPath = ts.findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionPaths = (_a = ts.getPackageJsonTypesVersionsPaths(typesVersions)) === null || _a === void 0 ? void 0 : _a.paths; + if (versionPaths) { + var packageDirectory = ts.getDirectoryPath(packageJsonPath); + var pathInPackage = absolutePath.slice(ts.ensureTrailingDirectorySeparator(packageDirectory).length); + if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, host, versionPaths)) { + // A true result means one of the `versionPaths` was matched, which will block relative resolution + // to files and folders from here. All reachable paths given the pattern match are already added. + return result; + } + } + } + } var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (!ts.tryDirectoryExists(host, baseDirectory)) return result; // Enumerate the available files if possible - var files = ts.tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + var files = ts.tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensionsOption === includeExtensionsOption.Exclude) so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - var foundFiles = new ts.Map(); // maps file to its extension for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { var filePath = files_1[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* Comparison.EqualTo */) { continue; } - var foundFileName = void 0; - var outputExtension = ts.moduleSpecifiers.tryGetJSExtensionForFile(filePath, host.getCompilationSettings()); - if (includeExtensionsOption === 0 /* IncludeExtensionsOption.Exclude */ && !ts.fileExtensionIsOneOf(filePath, [".json" /* Extension.Json */, ".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */])) { - foundFileName = ts.removeFileExtension(ts.getBaseFileName(filePath)); - foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); - } - else if ((ts.fileExtensionIsOneOf(filePath, [".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */]) || includeExtensionsOption === 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */) && outputExtension) { - foundFileName = ts.changeExtension(ts.getBaseFileName(filePath), outputExtension); - foundFiles.set(foundFileName, outputExtension); - } - else { - foundFileName = ts.getBaseFileName(filePath); - foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); - } + var _b = getFilenameWithExtensionOption(ts.getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions.includeExtensionsOption), name = _b.name, extension = _b.extension; + result.add(nameAndKind(name, "script" /* ScriptElementKind.scriptElement */, extension)); } - foundFiles.forEach(function (ext, foundFile) { - result.push(nameAndKind(foundFile, "script" /* ScriptElementKind.scriptElement */, ext)); - }); } // If possible, get folder completion as well var directories = ts.tryGetDirectories(host, baseDirectory); if (directories) { - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var directory = directories_1[_b]; + for (var _c = 0, directories_1 = directories; _c < directories_1.length; _c++) { + var directory = directories_1[_c]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); if (directoryName !== "@types") { - result.push(directoryResult(directoryName)); - } - } - } - // check for a version redirect - var packageJsonPath = ts.findPackageJson(baseDirectory, host); - if (packageJsonPath) { - var packageJson = ts.readJson(packageJsonPath, host); - var typesVersions = packageJson.typesVersions; - if (typeof typesVersions === "object") { - var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); - var versionPaths = versionResult && versionResult.paths; - var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); - if (versionPaths) { - addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + result.add(directoryResult(directoryName)); } } } return result; } - function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { - for (var path in paths) { - if (!ts.hasProperty(paths, path)) + function getFilenameWithExtensionOption(name, compilerOptions, includeExtensionsOption) { + var outputExtension = ts.moduleSpecifiers.tryGetJSExtensionForFile(name, compilerOptions); + if (includeExtensionsOption === 0 /* IncludeExtensionsOption.Exclude */ && !ts.fileExtensionIsOneOf(name, [".json" /* Extension.Json */, ".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */])) { + return { name: ts.removeFileExtension(name), extension: ts.tryGetExtensionFromPath(name) }; + } + else if ((ts.fileExtensionIsOneOf(name, [".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */]) || includeExtensionsOption === 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */) && outputExtension) { + return { name: ts.changeExtension(name, outputExtension), extension: outputExtension }; + } + else { + return { name: name, extension: ts.tryGetExtensionFromPath(name) }; + } + } + /** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */ + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, host, paths) { + var getPatternsForKey = function (key) { return paths[key]; }; + var comparePaths = function (a, b) { + var patternA = ts.tryParsePattern(a); + var patternB = ts.tryParsePattern(b); + var lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length; + var lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length; + return ts.compareValues(lengthB, lengthA); + }; + return addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, ts.getOwnKeys(paths), getPatternsForKey, comparePaths); + } + /** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */ + function addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, keys, getPatternsForKey, comparePaths) { + var pathResults = []; + var matchedPath; + for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { + var key = keys_1[_i]; + if (key === ".") continue; - var patterns = paths[path]; + var keyWithoutLeadingDotSlash = key.replace(/^\.\//, ""); // remove leading "./" + var patterns = getPatternsForKey(key); if (patterns) { - var _loop_3 = function (name, kind, extension) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind, extension)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_3(name, kind, extension); + var pathPattern = ts.tryParsePattern(keyWithoutLeadingDotSlash); + if (!pathPattern) + continue; + var isMatch = typeof pathPattern === "object" && ts.isPatternMatch(pathPattern, fragment); + var isLongestMatch = isMatch && (matchedPath === undefined || comparePaths(key, matchedPath) === -1 /* Comparison.LessThan */); + if (isLongestMatch) { + // If this is a higher priority match than anything we've seen so far, previous results from matches are invalid, e.g. + // for `import {} from "some-package/|"` with a typesVersions: + // { + // "bar/*": ["bar/*"], // <-- 1. We add 'bar', but 'bar/*' doesn't match yet. + // "*": ["dist/*"], // <-- 2. We match here and add files from dist. 'bar' is still ok because it didn't come from a match. + // "foo/*": ["foo/*"] // <-- 3. We matched '*' earlier and added results from dist, but if 'foo/*' also matched, + // } results in dist would not be visible. 'bar' still stands because it didn't come from a match. + // This is especially important if `dist/foo` is a folder, because if we fail to clear results + // added by the '*' match, after typing `"some-package/foo/|"` we would get file results from both + // ./dist/foo and ./foo, when only the latter will actually be resolvable. + // See pathCompletionsTypesVersionsWildcard6.ts. + matchedPath = key; + pathResults = pathResults.filter(function (r) { return !r.matchedPattern; }); + } + if (typeof pathPattern === "string" || matchedPath === undefined || comparePaths(key, matchedPath) !== 1 /* Comparison.GreaterThan */) { + pathResults.push({ + matchedPattern: isMatch, + results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host) + .map(function (_a) { + var name = _a.name, kind = _a.kind, extension = _a.extension; + return nameAndKind(name, kind, extension); + }), + }); } } } + pathResults.forEach(function (pathResult) { return pathResult.results.forEach(function (r) { return result.add(r); }); }); + return matchedPath !== undefined; } /** * Check all of the declared modules and those in node modules. Possible sources of modules: @@ -131595,22 +133912,22 @@ var ts; * Modules from node_modules (i.e. those listed in package.json) * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions */ - function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, compilerOptions, host, includeExtensionsOption, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; - var result = []; - var extensionOptions = getExtensionOptions(compilerOptions); + var result = createNameAndKindSet(); + var extensionOptions = getExtensionOptions(compilerOptions, includeExtensionsOption); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); if (paths) { - addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, host, paths); } } var fragmentDirectory = getFragmentDirectory(fragment); for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { var ambientName = _a[_i]; - result.push(nameAndKind(ambientName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); + result.add(nameAndKind(ambientName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (isEmitResolutionKindUsingNodeModules(compilerOptions)) { @@ -131618,15 +133935,13 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_4 = function (moduleName) { - if (!result.some(function (entry) { return entry.name === moduleName; })) { - foundGlobal = true; - result.push(nameAndKind(moduleName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); - } - }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_4(moduleName); + var moduleResult = nameAndKind(moduleName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined); + if (!result.has(moduleResult.name)) { + foundGlobal = true; + result.add(moduleResult); + } } } if (!foundGlobal) { @@ -131652,39 +133967,19 @@ var ts; } packagePath = ts.combinePaths(packagePath, subName); } - var packageFile = ts.combinePaths(ancestor, "node_modules", packagePath, "package.json"); + var packageDirectory = ts.combinePaths(ancestor, "node_modules", packagePath); + var packageFile = ts.combinePaths(packageDirectory, "package.json"); if (ts.tryFileExists(host, packageFile)) { var packageJson = ts.readJson(packageFile, host); - var exports = packageJson.exports; - if (exports) { - if (typeof exports !== "object" || exports === null) { // eslint-disable-line no-null/no-null + var exports_1 = packageJson.exports; + if (exports_1) { + if (typeof exports_1 !== "object" || exports_1 === null) { // eslint-disable-line no-null/no-null return; // null exports or entrypoint only, no sub-modules available } - var keys = ts.getOwnKeys(exports); - var fragmentSubpath_1 = components.join("/"); - var processedKeys = ts.mapDefined(keys, function (k) { - if (k === ".") - return undefined; - if (!ts.startsWith(k, "./")) - return undefined; - var subpath = k.substring(2); - if (!ts.startsWith(subpath, fragmentSubpath_1)) - return undefined; - // subpath is a valid export (barring conditions, which we don't currently check here) - if (!ts.stringContains(subpath, "*")) { - return subpath; - } - // pattern export - only return everything up to the `*`, so the user can autocomplete, then - // keep filling in the pattern (we could speculatively return a list of options by hitting disk, - // but conditions will make that somewhat awkward, as each condition may have a different set of possible - // options for the `*`. - return subpath.slice(0, subpath.indexOf("*")); - }); - ts.forEach(processedKeys, function (k) { - if (k) { - result.push(nameAndKind(k, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); - } - }); + var keys = ts.getOwnKeys(exports_1); + var fragmentSubpath = components.join("/") + (components.length && ts.hasTrailingDirectorySeparator(fragment) ? "/" : ""); + var conditions_1 = mode === ts.ModuleKind.ESNext ? ["node", "import", "types"] : ["node", "require", "types"]; + addCompletionEntriesFromPathsOrExports(result, fragmentSubpath, packageDirectory, extensionOptions, host, keys, function (key) { return ts.singleElementArray(getPatternFromFirstMatchingCondition(exports_1[key], conditions_1)); }, ts.comparePatternKeys); return; } } @@ -131694,26 +133989,44 @@ var ts; ts.forEachAncestorDirectory(scriptPath, ancestorLookup); } } - return result; + return ts.arrayFrom(result.values()); + } + function getPatternFromFirstMatchingCondition(target, conditions) { + if (typeof target === "string") { + return target; + } + if (target && typeof target === "object" && !ts.isArray(target)) { + for (var condition in target) { + if (condition === "default" || conditions.indexOf(condition) > -1 || ts.isApplicableVersionedTypesKey(conditions, condition)) { + var pattern = target[condition]; + return getPatternFromFirstMatchingCondition(pattern, conditions); + } + } + } } function getFragmentDirectory(fragment) { return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; } - function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; + return !ts.stringContains(path, "*") ? justPathMappingName(path, "script" /* ScriptElementKind.scriptElement */) : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); - return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { - return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); - }); - function justPathMappingName(name) { - return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; + if (remainingFragment === undefined) { + var starIsFullPathComponent = path[path.length - 2] === "/"; + return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* ScriptElementKind.directory */) : ts.flatMap(patterns, function (pattern) { var _a; return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)) === null || _a === void 0 ? void 0 : _a.map(function (_a) { + var name = _a.name, rest = __rest(_a, ["name"]); + return (__assign({ name: pathPrefix + name }, rest)); + }); }); + } + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host); }); + function justPathMappingName(name, kind) { + return ts.startsWith(name, fragment) ? [{ name: ts.removeTrailingDirectorySeparator(name), kind: kind, extension: undefined }] : ts.emptyArray; } } - function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, host) { if (!host.readDirectory) { return undefined; } @@ -131732,21 +134045,33 @@ var ts; var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". - var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var baseDirectory = ts.normalizePath(ts.combinePaths(packageDirectory, expandedPrefixDirectory)); var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { - var extension = ts.tryGetExtensionFromPath(match); - var name = trimPrefixAndSuffix(match); - return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* ScriptElementKind.scriptElement */, extension); - }); - var directories = ts.mapDefined(ts.tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { - var name = trimPrefixAndSuffix(dir); - return name === undefined ? undefined : directoryResult(name); + // If we have a suffix, then we read the directory all the way down to avoid returning completions for + // directories that don't contain files that would match the suffix. A previous comment here was concerned + // about the case where `normalizedSuffix` includes a `?` character, which should be interpreted literally, + // but will match any single character as part of the `include` pattern in `tryReadDirectory`. This is not + // a problem, because (in the extremely unusual circumstance where the suffix has a `?` in it) a `?` + // interpreted as "any character" can only return *too many* results as compared to the literal + // interpretation, so we can filter those superfluous results out via `trimPrefixAndSuffix` as we've always + // done. + var includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*"; + var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var trimmedWithPattern = trimPrefixAndSuffix(match); + if (trimmedWithPattern) { + if (containsSlash(trimmedWithPattern)) { + return directoryResult(ts.getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); + } + var _a = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions.includeExtensionsOption), name = _a.name, extension = _a.extension; + return nameAndKind(name, "script" /* ScriptElementKind.scriptElement */, extension); + } }); + // If we had a suffix, we already recursively searched for all possible files that could match + // it and returned the directories leading to those files. Otherwise, assume any directory could + // have something valid to import. + var directories = normalizedSuffix + ? ts.emptyArray + : ts.mapDefined(ts.tryGetDirectories(host, baseDirectory), function (dir) { return dir === "node_modules" ? undefined : directoryResult(dir); }); return __spreadArray(__spreadArray([], matches, true), directories, true); function trimPrefixAndSuffix(path) { var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); @@ -131789,10 +134114,10 @@ var ts; var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, 1 /* IncludeExtensionsOption.Include */), host, sourceFile.path) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) : ts.Debug.fail(); - return addReplacementSpans(toComplete, range.pos + prefix.length, names); + return addReplacementSpans(toComplete, range.pos + prefix.length, ts.arrayFrom(names.values())); } function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { - if (result === void 0) { result = []; } + if (result === void 0) { result = createNameAndKindSet(); } // Check for typings specified in compiler options var seen = new ts.Map(); var typeRoots = ts.tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; @@ -131817,7 +134142,7 @@ var ts; continue; if (fragmentDirectory === undefined) { if (!seen.has(packageName)) { - result.push(nameAndKind(packageName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); + result.add(nameAndKind(packageName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); seen.set(packageName, true); } } @@ -132013,10 +134338,9 @@ var ts; GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; })(GlobalsSearch || (GlobalsSearch = {})); - function resolvingModuleSpecifiers(logPrefix, host, program, sourceFile, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { + function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { var _a, _b, _c; var start = ts.timestamp(); - var packageJsonImportFilter = ts.createPackageJsonImportFilter(sourceFile, preferences, host); // Under `--moduleResolution nodenext`, we have to resolve module specifiers up front, because // package.json exports can mean we *can't* resolve a module specifier (that doesn't include a // relative path into node_modules), and we want to filter those completions out entirely. @@ -132041,7 +134365,7 @@ var ts; return result; function tryResolve(exportInfo, symbolName, isFromAmbientModule) { if (isFromAmbientModule) { - var result_1 = ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, sourceFile, program, host, preferences); + var result_1 = resolver.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite); if (result_1) { ambientCount++; } @@ -132050,7 +134374,7 @@ var ts; var shouldResolveModuleSpecifier = needsFullResolution || preferences.allowIncompleteCompletions && resolvedCount < Completions.moduleSpecifierResolutionLimit; var shouldGetModuleSpecifierFromCache = !shouldResolveModuleSpecifier && preferences.allowIncompleteCompletions && cacheAttemptCount < Completions.moduleSpecifierResolutionCacheAttemptLimit; var result = (shouldResolveModuleSpecifier || shouldGetModuleSpecifierFromCache) - ? ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, sourceFile, program, host, preferences, packageJsonImportFilter, shouldGetModuleSpecifierFromCache) + ? resolver.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, shouldGetModuleSpecifierFromCache) : undefined; if (!shouldResolveModuleSpecifier && !shouldGetModuleSpecifierFromCache || shouldGetModuleSpecifierFromCache && !result) { skippedAny = true; @@ -132154,8 +134478,8 @@ var ts; if (!previousResponse) return undefined; var lowerCaseTokenText = location.text.toLowerCase(); - var exportMap = ts.getExportInfoMap(file, host, program, cancellationToken); - var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, program, file, location.getStart(), preferences, + var exportMap = ts.getExportInfoMap(file, host, program, preferences, cancellationToken); + var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, ts.codefix.createImportSpecifierResolver(file, program, host, preferences), program, location.getStart(), preferences, /*isForImportStatementCompletion*/ false, ts.isValidTypeOnlyAliasUseSite(location), function (context) { var entries = ts.mapDefined(previousResponse.entries, function (entry) { var _a; @@ -132239,37 +134563,36 @@ var ts; } } var entries = ts.createSortedArray(); - if (isUncheckedFile(sourceFile, compilerOptions)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); - getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); - } - else { - if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* KeywordCompletionFilters.None */) { - return undefined; - } - getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); + var isChecked = isCheckedFile(sourceFile, compilerOptions); + if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* KeywordCompletionFilters.None */) { + return undefined; } + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); if (keywordFilters !== 0 /* KeywordCompletionFilters.None */) { - var entryNames_1 = new ts.Set(entries.map(function (e) { return e.name; })); for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; - if (isTypeOnlyLocation && ts.isTypeKeyword(ts.stringToToken(keywordEntry.name)) || !entryNames_1.has(keywordEntry.name)) { + if (isTypeOnlyLocation && ts.isTypeKeyword(ts.stringToToken(keywordEntry.name)) || !uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } } - var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); for (var _b = 0, _c = getContextualKeywords(contextToken, position); _b < _c.length; _b++) { var keywordEntry = _c[_b]; - if (!entryNames.has(keywordEntry.name)) { + if (!uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } for (var _d = 0, literals_1 = literals; _d < literals_1.length; _d++) { var literal = literals_1[_d]; - ts.insertSorted(entries, createCompletionEntryForLiteral(sourceFile, preferences, literal), compareCompletionEntries, /*allowDuplicates*/ true); + var literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal); + uniqueNames.add(literalEntry.name); + ts.insertSorted(entries, literalEntry, compareCompletionEntries, /*allowDuplicates*/ true); + } + if (!isChecked) { + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); } return { flags: completionData.flags, @@ -132281,8 +134604,8 @@ var ts; entries: entries, }; } - function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + function isCheckedFile(sourceFile, compilerOptions) { + return !ts.isSourceFileJS(sourceFile) || !!ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -132651,7 +134974,7 @@ var ts; span = ts.createTextSpanFromNode(contextToken); } if (ts.isPropertyDeclaration(contextToken.parent)) { - modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers); + modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers) & 125951 /* ModifierFlags.Modifier */; span = ts.createTextSpanFromNode(contextToken.parent); } return { modifiers: modifiers, span: span }; @@ -132711,7 +135034,7 @@ var ts; var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var quotePreference = ts.getQuotePreference(sourceFile, preferences); - var builderFlags = quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : undefined; + var builderFlags = 33554432 /* NodeBuilderFlags.OmitThisParameter */ | (quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : 0 /* NodeBuilderFlags.None */); switch (declaration.kind) { case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: @@ -132750,12 +135073,10 @@ var ts; } var parameters = typeNode.parameters.map(function (typedParam) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typedParam.dotDotDotToken, typedParam.name, typedParam.questionToken, /*type*/ undefined, typedParam.initializer); }); return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, @@ -133242,7 +135563,7 @@ var ts; } function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) { var typeChecker = program.getTypeChecker(); - var inUncheckedFile = isUncheckedFile(sourceFile, compilerOptions); + var inCheckedFile = isCheckedFile(sourceFile, compilerOptions); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -133486,6 +135807,7 @@ var ts; var hasUnresolvedAutoImports = false; // This also gets mutated in nested-functions after the return var symbols = []; + var importSpecifierResolver; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; var seenPropertySymbols = new ts.Map(); @@ -133657,15 +135979,7 @@ var ts; isNewIdentifierLocation = true; } var propertyAccess = node.kind === 200 /* SyntaxKind.ImportType */ ? node : node.parent; - if (inUncheckedFile) { - // In javascript files, for union types, we don't just get the members that - // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part - // of the individual types to a higher status since we know what they are. - symbols.push.apply(symbols, ts.filter(getPropertiesForCompletion(type, typeChecker), function (s) { return typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s); })); - } - else { + if (inCheckedFile) { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) { @@ -133673,6 +135987,14 @@ var ts; } } } + else { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + symbols.push.apply(symbols, ts.filter(getPropertiesForCompletion(type, typeChecker), function (s) { return typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s); })); + } if (insertAwait && preferences.includeCompletionsWithInsertText) { var promiseType = typeChecker.getPromisedTypeOfPromise(type); if (promiseType) { @@ -133707,14 +136029,14 @@ var ts; } else { var fileName = ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? (_a = ts.getSourceFileOfModule(moduleSymbol)) === null || _a === void 0 ? void 0 : _a.fileName : undefined; - var moduleSpecifier = (ts.codefix.getModuleSpecifierForBestExportInfo([{ + var moduleSpecifier = ((importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo([{ exportKind: 0 /* ExportKind.Named */, moduleFileName: fileName, isFromPackageJson: false, moduleSymbol: moduleSymbol, symbol: firstAccessibleSymbol, targetFlags: ts.skipAlias(firstAccessibleSymbol, typeChecker).flags, - }], firstAccessibleSymbol.name, position, ts.isValidTypeOnlyAliasUseSite(location), sourceFile, program, host, preferences) || {}).moduleSpecifier; + }], firstAccessibleSymbol.name, position, ts.isValidTypeOnlyAliasUseSite(location)) || {}).moduleSpecifier; if (moduleSpecifier) { var origin = { kind: getNullableSymbolOriginInfoKind(6 /* SymbolOriginInfoKind.SymbolMemberExport */), @@ -133864,7 +136186,7 @@ var ts; } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 305 /* SyntaxKind.SourceFile */) { - var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); + var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false, ts.isClassLike(scopeNode.parent) ? scopeNode : undefined); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { var symbol = _a[_i]; @@ -133967,10 +136289,10 @@ var ts; previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); - var exportInfo = ts.getExportInfoMap(sourceFile, host, program, cancellationToken); + var exportInfo = ts.getExportInfoMap(sourceFile, host, program, preferences, cancellationToken); var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); - resolvingModuleSpecifiers("collectAutoImports", host, program, sourceFile, position, preferences, !!importCompletionNode, ts.isValidTypeOnlyAliasUseSite(location), function (context) { + resolvingModuleSpecifiers("collectAutoImports", host, importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences)), program, position, preferences, !!importCompletionNode, ts.isValidTypeOnlyAliasUseSite(location), function (context) { exportInfo.search(sourceFile.path, /*preferCapitalized*/ isRightOfOpenTag, function (symbolName, targetFlags) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) @@ -135067,6 +137389,7 @@ var ts; return kind === 131 /* SyntaxKind.AsyncKeyword */ || kind === 132 /* SyntaxKind.AwaitKeyword */ || kind === 127 /* SyntaxKind.AsKeyword */ + || kind === 152 /* SyntaxKind.TypeKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { @@ -135166,6 +137489,10 @@ var ts; } break; case 79 /* SyntaxKind.Identifier */: { + var originalKeywordKind = location.originalKeywordKind; + if (originalKeywordKind && ts.isKeyword(originalKeywordKind)) { + return undefined; + } // class c { public prop = c| } if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) { return undefined; @@ -135953,60 +138280,64 @@ var ts; } return settingsOrHost; } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings)); - return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions); } - function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind, languageVersionOrOptions); } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings)); - return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions); } - function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { + return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind, languageVersionOrOptions); } function getDocumentRegistryEntry(bucketEntry, scriptKind) { var entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(ts.Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:".concat(scriptKind, " and sourceFile.scriptKind: ").concat(entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind, ", !entry: ").concat(!entry)); return entry; } - function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version, acquiring, scriptKind) { + function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version, acquiring, scriptKind, languageVersionOrOptions) { var _a, _b, _c, _d; scriptKind = ts.ensureScriptKind(fileName, scriptKind); var compilationSettings = getCompilationSettings(compilationSettingsOrHost); var host = compilationSettingsOrHost === compilationSettings ? undefined : compilationSettingsOrHost; var scriptTarget = scriptKind === 6 /* ScriptKind.JSON */ ? 100 /* ScriptTarget.JSON */ : ts.getEmitScriptTarget(compilationSettings); - var sourceFileOptions = { - languageVersion: scriptTarget, - impliedNodeFormat: host && ts.getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getModuleResolutionCache) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(compilationSettings) - }; + var sourceFileOptions = typeof languageVersionOrOptions === "object" ? + languageVersionOrOptions : + { + languageVersion: scriptTarget, + impliedNodeFormat: host && ts.getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getModuleResolutionCache) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), + setExternalModuleIndicator: ts.getSetExternalModuleIndicator(compilationSettings) + }; + sourceFileOptions.languageVersion = scriptTarget; var oldBucketCount = buckets.size; - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var keyWithMode = getDocumentRegistryBucketKeyWithMode(key, sourceFileOptions.impliedNodeFormat); + var bucket = ts.getOrUpdate(buckets, keyWithMode, function () { return new ts.Map(); }); if (ts.tracing) { if (buckets.size > oldBucketCount) { // It is interesting, but not definitively problematic if a build requires multiple document registry buckets - // perhaps they are for two projects that don't have any overlap. // Bonus: these events can help us interpret the more interesting event below. - ts.tracing.instant("session" /* tracing.Phase.Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: key }); + ts.tracing.instant("session" /* tracing.Phase.Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: keyWithMode }); } // It is fairly suspicious to have one path in two buckets - you'd expect dependencies to have similar configurations. // If this occurs unexpectedly, the fix is likely to synchronize the project settings. // Skip .d.ts files to reduce noise (should also cover most of node_modules). var otherBucketKey = !ts.isDeclarationFileName(path) && - ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== key && bucket.has(path) && bucketKey; }); + ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== keyWithMode && bucket.has(path) && bucketKey; }); if (otherBucketKey) { - ts.tracing.instant("session" /* tracing.Phase.Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: key }); + ts.tracing.instant("session" /* tracing.Phase.Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: keyWithMode }); } } var bucketEntry = bucket.get(path); var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { - var sourceFile = externalCache.getDocument(key, path); + var sourceFile = externalCache.getDocument(keyWithMode, path); if (sourceFile) { ts.Debug.assert(acquiring); entry = { @@ -136020,7 +138351,7 @@ var ts; // Have never seen this file with these settings. Create a new source file for it. var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, sourceFileOptions, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { - externalCache.setDocument(key, path, sourceFile); + externalCache.setDocument(keyWithMode, path, sourceFile); } entry = { sourceFile: sourceFile, @@ -136035,7 +138366,7 @@ var ts; if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 if (externalCache) { - externalCache.setDocument(key, path, entry.sourceFile); + externalCache.setDocument(keyWithMode, path, entry.sourceFile); } } // If we're acquiring, then this is the first time this LS is asking for this document. @@ -136064,13 +138395,13 @@ var ts; } } } - function releaseDocument(fileName, compilationSettings, scriptKind) { + function releaseDocument(fileName, compilationSettings, scriptKind, impliedNodeFormat) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key, scriptKind); + return releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat); } - function releaseDocumentWithKey(path, key, scriptKind) { - var bucket = ts.Debug.checkDefined(buckets.get(key)); + function releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat) { + var bucket = ts.Debug.checkDefined(buckets.get(getDocumentRegistryBucketKeyWithMode(key, impliedNodeFormat))); var bucketEntry = bucket.get(path); var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; @@ -136118,7 +138449,7 @@ var ts; } var str = "{"; for (var key in value) { - if (ts.hasOwnProperty.call(value, key)) { // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier + if (ts.hasProperty(value, key)) { str += "".concat(key, ": ").concat(compilerOptionValueToString(value[key])); } } @@ -136127,6 +138458,9 @@ var ts; function getKeyForCompilationSettings(settings) { return ts.sourceFileAffectingCompilerOptions.map(function (option) { return compilerOptionValueToString(ts.getCompilerOptionValue(settings, option)); }).join("|") + (settings.pathsBasePath ? "|".concat(settings.pathsBasePath) : undefined); } + function getDocumentRegistryBucketKeyWithMode(key, mode) { + return (mode ? "".concat(key, "|").concat(mode) : key); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -136259,7 +138593,7 @@ var ts; return ts.findAncestor(node, function (node) { if (stopAtAmbientModule && isAmbientModuleDeclaration(node)) return "quit"; - return ts.some(node.modifiers, function (mod) { return mod.kind === 93 /* SyntaxKind.ExportKeyword */; }); + return ts.canHaveModifiers(node) && ts.some(node.modifiers, ts.isExportModifier); }); } function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { @@ -136683,7 +139017,7 @@ var ts; ts.Debug.assert(parent.name === node); return true; case 203 /* SyntaxKind.BindingElement */: - return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent); + return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent.parent.parent); default: return false; } @@ -136942,18 +139276,18 @@ var ts; || node.kind === 106 /* SyntaxKind.SuperKeyword */) { referenceEntries = entries && __spreadArray([], entries, true); } - else { - var queue = entries && __spreadArray([], entries, true); + else if (entries) { + var queue = ts.createQueue(entries); var seenNodes = new ts.Map(); - while (queue && queue.length) { - var entry = queue.shift(); + while (!queue.isEmpty()) { + var entry = queue.dequeue(); if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) { continue; } referenceEntries = ts.append(referenceEntries, entry); var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); if (entries_1) { - queue.push.apply(queue, entries_1); + queue.enqueue.apply(queue, entries_1); } } } @@ -137209,6 +139543,7 @@ var ts; var commonjsSource = source && ts.isBinaryExpression(source) ? source.left : undefined; return !!(source && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === source || d === commonjsSource; }))); } + FindAllReferences.isDeclarationOfSymbol = isDeclarationOfSymbol; /** * True if 'decl' provides a value, as in `function f() {}`; * false if 'decl' is just a location for a future write, as in 'let x;' @@ -137415,7 +139750,7 @@ var ts; result = references; continue; } - var _loop_5 = function (entry) { + var _loop_3 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* DefinitionKind.Symbol */) { result.push(entry); return "continue"; @@ -137447,7 +139782,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_5(entry); + _loop_3(entry); } } return result; @@ -138148,7 +140483,7 @@ var ts; // Use the parent symbol if the location is commonjs require syntax on javascript files only. if (ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 203 /* SyntaxKind.BindingElement */ - && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent)) { + && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) { referenceSymbol = referenceLocation.parent.symbol; // The parent will not have a symbol if it's an ObjectBindingPattern (when destructuring is used). In // this case, just skip it, since the bound identifiers are not an alias of the import. @@ -139028,8 +141363,8 @@ var ts; var declarations; if (symbol && symbol.declarations) { var indices = ts.indicesOf(symbol.declarations); - var keys_1 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); }); - indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_1[a].file, keys_1[b].file) || keys_1[a].pos - keys_1[b].pos; }); + var keys_2 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); }); + indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_2[a].file, keys_2[b].file) || keys_2[a].pos - keys_2[b].pos; }); var sortedDeclarations = ts.map(indices, function (i) { return symbol.declarations[i]; }); var lastDecl = void 0; for (var _i = 0, sortedDeclarations_1 = sortedDeclarations; _i < sortedDeclarations_1.length; _i++) { @@ -139299,14 +141634,16 @@ var ts; collect(node.body); } function collectCallSitesOfClassLikeDeclaration(node, collect) { - ts.forEach(node.decorators, collect); + ts.forEach(node.modifiers, collect); var heritage = ts.getClassExtendsHeritageElement(node); if (heritage) { collect(heritage.expression); } for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - ts.forEach(member.decorators, collect); + if (ts.canHaveModifiers(member)) { + ts.forEach(member.modifiers, collect); + } if (ts.isPropertyDeclaration(member)) { collect(member.initializer); } @@ -139475,7 +141812,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_6 = function (sourceFile) { + var _loop_4 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -139507,7 +141844,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_6(sourceFile); + _loop_4(sourceFile); } } function combineNormal(pathA, pathB) { @@ -140149,11 +142486,12 @@ var ts; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var jsdoc = _a[_i]; + var inheritDoc = ts.isJSDoc(jsdoc) && jsdoc.tags && ts.find(jsdoc.tags, function (t) { return t.kind === 327 /* SyntaxKind.JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc"); }); // skip comments containing @typedefs since they're not associated with particular declarations // Exceptions: // - @typedefs are themselves declarations with associated comments // - @param or @return indicate that the author thinks of it as a 'local' @typedef that's part of the function documentation - if (jsdoc.comment === undefined + if (jsdoc.comment === undefined && !inheritDoc || ts.isJSDoc(jsdoc) && declaration.kind !== 345 /* SyntaxKind.JSDocTypedefTag */ && declaration.kind !== 338 /* SyntaxKind.JSDocCallbackTag */ && jsdoc.tags @@ -140161,7 +142499,10 @@ var ts; && !jsdoc.tags.some(function (t) { return t.kind === 340 /* SyntaxKind.JSDocParameterTag */ || t.kind === 341 /* SyntaxKind.JSDocReturnTag */; })) { continue; } - var newparts = getDisplayPartsFromComment(jsdoc.comment, checker); + var newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : []; + if (inheritDoc && inheritDoc.comment) { + newparts = newparts.concat(getDisplayPartsFromComment(inheritDoc.comment, checker)); + } if (!ts.contains(parts, newparts, isIdenticalListOfDisplayParts)) { parts.push(newparts); } @@ -140395,8 +142736,12 @@ var ts; return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters, hasReturn = commentOwnerInfo.hasReturn; - var commentOwnerJSDoc = ts.hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? ts.lastOrUndefined(commentOwner.jsDoc) : undefined; - if (commentOwner.getStart(sourceFile) < position || commentOwnerJSDoc && commentOwnerJSDoc !== existingDocComment) { + var commentOwnerJsDoc = ts.hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : undefined; + var lastJsDoc = ts.lastOrUndefined(commentOwnerJsDoc); + if (commentOwner.getStart(sourceFile) < position + || lastJsDoc + && existingDocComment + && lastJsDoc !== existingDocComment) { return undefined; } var indentationStr = getIndentationStringAtPosition(sourceFile, position); @@ -140413,7 +142758,9 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var openComment = "/**"; var closeComment = " */"; - if (tags) { + // If any of the existing jsDoc has tags, ignore adding new ones. + var hasTag = (commentOwnerJsDoc || []).some(function (jsDoc) { return !!jsDoc.tags; }); + if (tags && !hasTag) { var preamble = openComment + newLine + indentationStr + " * "; var endLine = tokenStart === position ? newLine + indentationStr : ""; var result = preamble + newLine + tags + indentationStr + closeComment + endLine; @@ -140527,7 +142874,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_7 = function (sourceFile) { + var _loop_5 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -140539,7 +142886,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_7(sourceFile); + _loop_5(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -141135,7 +143482,7 @@ var ts; isPossibleConstructor(b.node) ? b.node : undefined; if (ctorFunction !== undefined) { - var ctorNode = ts.setTextRange(ts.factory.createConstructorDeclaration(/* decorators */ undefined, /* modifiers */ undefined, [], /* body */ undefined), ctorFunction); + var ctorNode = ts.setTextRange(ts.factory.createConstructorDeclaration(/* modifiers */ undefined, [], /* body */ undefined), ctorFunction); var ctor = emptyNavigationBarNode(ctorNode); ctor.indent = a.indent + 1; ctor.children = a.node === ctorFunction ? a.children : b.children; @@ -141151,7 +143498,6 @@ var ts; } } lastANode = a.node = ts.setTextRange(ts.factory.createClassDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, a.name || ts.factory.createIdentifier("__class__"), /* typeParameters */ undefined, /* heritageClauses */ undefined, []), a.node); @@ -141176,7 +143522,6 @@ var ts; if (!a.additionalNodes) a.additionalNodes = []; a.additionalNodes.push(ts.setTextRange(ts.factory.createClassDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, a.name || ts.factory.createIdentifier("__class__"), /* typeParameters */ undefined, /* heritageClauses */ undefined, []), b.node)); @@ -141685,7 +144030,7 @@ var ts; else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) { // If we’re in a declaration file, it’s safe to remove the import clause from it if (sourceFile.isDeclarationFile) { - usedImports.push(ts.factory.createImportDeclaration(importDecl.decorators, importDecl.modifiers, + usedImports.push(ts.factory.createImportDeclaration(importDecl.modifiers, /*importClause*/ undefined, moduleSpecifier, /*assertClause*/ undefined)); } @@ -141851,7 +144196,7 @@ var ts; newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(exportGroup_1, function (i) { return i.exportClause && ts.isNamedExports(i.exportClause) ? i.exportClause.elements : ts.emptyArray; })); var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); var exportDecl = exportGroup_1[0]; - coalescedExports.push(ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ? + coalescedExports.push(ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ? ts.factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : ts.factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.assertClause)); } @@ -141888,7 +144233,7 @@ var ts; } OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 + return ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, ts.factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 importDeclaration.moduleSpecifier, importDeclaration.assertClause); } function sortSpecifiers(specifiers) { @@ -142604,13 +144949,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_8 = function (start) { + var _loop_6 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_8(start); + var state_3 = _loop_6(start); if (typeof state_3 === "object") return state_3.value; } @@ -143196,10 +145541,10 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(program, sourceFile, position, options) { + function getRenameInfo(program, sourceFile, position, preferences) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, preferences); if (renameInfo) { return renameInfo; } @@ -143207,7 +145552,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, preferences) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -143235,7 +145580,12 @@ var ts; return undefined; } if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { - return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + return preferences.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + } + // Disallow rename for elements that would rename across `*/node_modules/*` packages. + var wouldRenameNodeModules = wouldRenameInOtherNodeModules(sourceFile, symbol, typeChecker, preferences); + if (wouldRenameNodeModules) { + return getRenameInfoError(wouldRenameNodeModules); } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) @@ -143249,6 +145599,49 @@ var ts; var sourceFile = declaration.getSourceFile(); return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Extension.Dts */); } + function wouldRenameInOtherNodeModules(originalFile, symbol, checker, preferences) { + if (!preferences.providePrefixAndSuffixTextForRename && symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var importSpecifier = symbol.declarations && ts.find(symbol.declarations, function (decl) { return ts.isImportSpecifier(decl); }); + if (importSpecifier && !importSpecifier.propertyName) { + symbol = checker.getAliasedSymbol(symbol); + } + } + var declarations = symbol.declarations; + if (!declarations) { + return undefined; + } + var originalPackage = getPackagePathComponents(originalFile.path); + if (originalPackage === undefined) { // original source file is not in node_modules + if (ts.some(declarations, function (declaration) { return ts.isInsideNodeModules(declaration.getSourceFile().path); })) { + return ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder; + } + else { + return undefined; + } + } + // original source file is in node_modules + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + var declPackage = getPackagePathComponents(declaration.getSourceFile().path); + if (declPackage) { + var length_2 = Math.min(originalPackage.length, declPackage.length); + for (var i = 0; i <= length_2; i++) { + if (ts.compareStringsCaseSensitive(originalPackage[i], declPackage[i]) !== 0 /* Comparison.EqualTo */) { + return ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder; + } + } + } + } + return undefined; + } + function getPackagePathComponents(filePath) { + var components = ts.getPathComponents(filePath); + var nodeModulesIdx = components.lastIndexOf("node_modules"); + if (nodeModulesIdx === -1) { + return undefined; + } + return components.slice(0, nodeModulesIdx + 2); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); @@ -143319,7 +145712,7 @@ var ts; var SmartSelectionRange; (function (SmartSelectionRange) { function getSmartSelectionRange(pos, sourceFile) { - var _a; + var _a, _b; var selectionRange = { textSpan: ts.createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd()) }; @@ -143371,6 +145764,17 @@ var ts; if (ts.hasJSDocNodes(node) && ((_a = node.jsDoc) === null || _a === void 0 ? void 0 : _a.length)) { pushSelectionRange(ts.first(node.jsDoc).getStart(), end); } + // (#39618 & #49807) + // When the node is a SyntaxList and its first child has a JSDoc comment, then the node's + // `start` (which usually is the result of calling `node.getStart()`) points to the first + // token after the JSDoc comment. So, we have to make sure we'd pushed the selection + // covering the JSDoc comment before diving further. + if (ts.isSyntaxList(node)) { + var firstChild = node.getChildren()[0]; + if (firstChild && ts.hasJSDocNodes(firstChild) && ((_b = firstChild.jsDoc) === null || _b === void 0 ? void 0 : _b.length) && firstChild.getStart() !== node.pos) { + start = Math.min(start, ts.first(firstChild.jsDoc).getStart()); + } + } pushSelectionRange(start, end); // String literals should have a stop both inside and outside their quotes. if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) { @@ -143444,6 +145848,7 @@ var ts; * other as well as of other top-level statements and declarations. */ function getSelectionChildren(node) { + var _a; // Group top-level imports if (ts.isSourceFile(node)) { return groupChildren(node.getChildAt(0).getChildren(), isImport); @@ -143459,7 +145864,7 @@ var ts; // because it allows the mapped type to become an object type with a // few keystrokes. if (ts.isMappedTypeNode(node)) { - var _a = node.getChildren(), openBraceToken = _a[0], children = _a.slice(1); + var _b = node.getChildren(), openBraceToken = _b[0], children = _b.slice(1); var closeBraceToken = ts.Debug.checkDefined(children.pop()); ts.Debug.assertEqual(openBraceToken.kind, 18 /* SyntaxKind.OpenBraceToken */); ts.Debug.assertEqual(closeBraceToken.kind, 19 /* SyntaxKind.CloseBraceToken */); @@ -143490,10 +145895,13 @@ var ts; var children = groupChildren(node.getChildren(), function (child) { return child === node.name || ts.contains(node.modifiers, child); }); - return splitChildren(children, function (_a) { + var firstJSDocChild = ((_a = children[0]) === null || _a === void 0 ? void 0 : _a.kind) === 320 /* SyntaxKind.JSDoc */ ? children[0] : undefined; + var withJSDocSeparated = firstJSDocChild ? children.slice(1) : children; + var splittedChildren = splitChildren(withJSDocSeparated, function (_a) { var kind = _a.kind; return kind === 58 /* SyntaxKind.ColonToken */; }); + return firstJSDocChild ? [firstJSDocChild, createSyntaxList(splittedChildren)] : splittedChildren; } // Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`. if (ts.isParameter(node)) { @@ -144029,7 +146437,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_9 = function (n) { + var _loop_7 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: ".concat(ts.Debug.formatSyntaxKind(n.kind), ", parent: ").concat(ts.Debug.formatSyntaxKind(n.parent.kind)); }); @@ -144039,7 +146447,7 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_4 = _loop_9(n); + var state_4 = _loop_7(n); if (typeof state_4 === "object") return state_4.value; } @@ -144238,7 +146646,7 @@ var ts; if (!ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { return; } - if (ts.isTypeNode(node)) { + if (ts.isTypeNode(node) && !ts.isExpressionWithTypeArguments(node)) { return; } if (preferences.includeInlayVariableTypeHints && ts.isVariableDeclaration(node)) { @@ -144303,7 +146711,7 @@ var ts; return type.symbol && (type.symbol.flags & 1536 /* SymbolFlags.Module */); } function visitVariableLikeDeclaration(decl) { - if (!decl.initializer || ts.isBindingPattern(decl.name)) { + if (!decl.initializer || ts.isBindingPattern(decl.name) || ts.isVariableDeclaration(decl) && !isHintableDeclaration(decl)) { return; } var effectiveTypeAnnotation = ts.getEffectiveTypeAnnotationNode(decl); @@ -144316,6 +146724,10 @@ var ts; } var typeDisplayString = printTypeInSingleLine(declarationType); if (typeDisplayString) { + var isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && ts.equateStringsCaseInsensitive(decl.name.getText(), typeDisplayString); + if (isVariableNameMatchesType) { + return; + } addTypeHints(typeDisplayString, decl.name.end); } } @@ -144427,6 +146839,9 @@ var ts; } for (var i = 0; i < node.parameters.length && i < signature.parameters.length; ++i) { var param = node.parameters[i]; + if (!isHintableDeclaration(param)) { + continue; + } var effectiveTypeAnnotation = ts.getEffectiveTypeAnnotationNode(param); if (effectiveTypeAnnotation) { continue; @@ -144468,6 +146883,13 @@ var ts; function isUndefined(name) { return name === "undefined"; } + function isHintableDeclaration(node) { + if ((ts.isParameterDeclaration(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) && node.initializer) { + var initializer = ts.skipParentheses(node.initializer); + return !(isHintableLiteral(initializer) || ts.isNewExpression(initializer) || ts.isObjectLiteralExpression(initializer) || ts.isAssertionExpression(initializer)); + } + return true; + } } InlayHints.provideInlayHints = provideInlayHints; })(InlayHints = ts.InlayHints || (ts.InlayHints = {})); @@ -145638,7 +148060,7 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_10 = function (opt) { + var _loop_8 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -145657,7 +148079,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_10(opt); + _loop_8(opt); } return options; } @@ -146607,7 +149029,7 @@ var ts; } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - !!context.contextNode.decorators && + ts.hasDecorators(context.contextNode) && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -147172,6 +149594,7 @@ var ts; var options = _a.options, getRules = _a.getRules, host = _a.host; // formatting context is used by rules provider var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); + var previousRangeTriviaEnd; var previousRange; var previousParent; var previousRangeStartLine; @@ -147182,7 +149605,7 @@ var ts; if (formattingScanner.isOnToken()) { var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; var undecoratedStartLine = startLine; - if (enclosingNode.decorators) { + if (ts.hasDecorators(enclosingNode)) { undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; } processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); @@ -147200,10 +149623,30 @@ var ts; } } if (previousRange && formattingScanner.getStartPos() >= originalRange.end) { + // Formatting edits happen by looking at pairs of contiguous tokens (see `processPair`), + // typically inserting or deleting whitespace between them. The recursive `processNode` + // logic above bails out as soon as it encounters a token that is beyond the end of the + // range we're supposed to format (or if we reach the end of the file). But this potentially + // leaves out an edit that would occur *inside* the requested range but cannot be discovered + // without looking at one token *beyond* the end of the range: consider the line `x = { }` + // with a selection from the beginning of the line to the space inside the curly braces, + // inclusive. We would expect a format-selection would delete the space (if rules apply), + // but in order to do that, we need to process the pair ["{", "}"], but we stopped processing + // just before getting there. This block handles this trailing edit. var tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : undefined; - if (tokenInfo) { + if (tokenInfo && tokenInfo.pos === previousRangeTriviaEnd) { + // We need to check that tokenInfo and previousRange are contiguous: the `originalRange` + // may have ended in the middle of a token, which means we will have stopped formatting + // on that token, leaving `previousRange` pointing to the token before it, but already + // having moved the formatting scanner (where we just got `tokenInfo`) to the next token. + // If this happens, our supposed pair [previousRange, tokenInfo] actually straddles the + // token that intersects the end of the range we're supposed to format, so the pair will + // produce bogus edits if we try to `processPair`. Recall that the point of this logic is + // to perform a trailing edit at the end of the selection range: but there can be no valid + // edit in the middle of a token where the range ended, so if we have a non-contiguous + // pair here, we're already done and we can ignore it. var parent = ((_b = ts.findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)) === null || _b === void 0 ? void 0 : _b.parent) || previousParent; processPair(tokenInfo, sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line, parent, previousRange, previousRangeStartLine, previousParent, parent, /*dynamicIndentation*/ undefined); @@ -147269,8 +149712,10 @@ var ts; } } function getFirstNonDecoratorTokenOfNode(node) { - if (node.modifiers && node.modifiers.length) { - return node.modifiers[0].kind; + if (ts.canHaveModifiers(node)) { + var modifier = ts.find(node.modifiers, ts.isModifier, ts.findIndex(node.modifiers, ts.isDecorator)); + if (modifier) + return modifier.kind; } switch (node.kind) { case 257 /* SyntaxKind.ClassDeclaration */: return 84 /* SyntaxKind.ClassKeyword */; @@ -147345,7 +149790,6 @@ var ts; case 280 /* SyntaxKind.JsxOpeningElement */: case 281 /* SyntaxKind.JsxClosingElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: return false; } break; @@ -147359,7 +149803,7 @@ var ts; // if token line equals to the line of containing node (this is a first token in the node) - use node indentation return nodeStartLine !== line // if this token is the first token following the list of decorators, we do not need to indent - && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + && !(ts.hasDecorators(node) && kind === getFirstNonDecoratorTokenOfNode(node)); } function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node @@ -147399,13 +149843,14 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { + ts.Debug.assert(!ts.nodeIsSynthesized(child)); if (ts.nodeIsMissing(child)) { return inheritedIndentation; } var childStartPos = child.getStart(sourceFile); var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; var undecoratedChildStartLine = childStartLine; - if (child.decorators) { + if (ts.hasDecorators(child)) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } // if child is a list item - try to get its indentation, only if parent is within the original range. @@ -147465,6 +149910,7 @@ var ts; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); + ts.Debug.assert(!ts.nodeIsSynthesized(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; @@ -147515,12 +149961,10 @@ var ts; var listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== 0 /* SyntaxKind.Unknown */ && formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(parent); - if (tokenInfo.token.kind === 27 /* SyntaxKind.CommaToken */ && ts.isCallLikeExpression(parent)) { - var commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - if (startLine !== commaTokenLine) { - formattingScanner.advance(); - tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; - } + if (tokenInfo.token.kind === 27 /* SyntaxKind.CommaToken */) { + // consume the comma + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one @@ -147560,6 +150004,7 @@ var ts; } } if (currentTokenInfo.trailingTrivia) { + previousRangeTriviaEnd = ts.last(currentTokenInfo.trailingTrivia).end; processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); } if (indentToken) { @@ -147630,6 +150075,7 @@ var ts; } } previousRange = range; + previousRangeTriviaEnd = range.end; previousParent = parent; previousRangeStartLine = rangeStart.line; return lineAction; @@ -147921,6 +150367,12 @@ var ts; case 169 /* SyntaxKind.MethodDeclaration */: case 168 /* SyntaxKind.MethodSignature */: case 214 /* SyntaxKind.ArrowFunction */: + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: if (node.typeParameters === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -147937,7 +150389,19 @@ var ts; return 20 /* SyntaxKind.OpenParenToken */; } break; + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 258 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.TypeAliasDeclaration */: + if (node.typeParameters === list) { + return 29 /* SyntaxKind.LessThanToken */; + } + break; case 178 /* SyntaxKind.TypeReference */: + case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 181 /* SyntaxKind.TypeQuery */: + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 200 /* SyntaxKind.ImportType */: if (node.typeArguments === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -149201,7 +151665,7 @@ var ts; return { indentation: indentation, prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter, - suffix: insertTrailingComma ? "," : "" + suffix: insertTrailingComma ? "," : ts.isInterfaceDeclaration(node) && isEmpty ? ";" : "" }; }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -149405,7 +151869,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_11 = function (sourceFile, node) { + var _loop_9 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -149418,7 +151882,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_11(sourceFile, node); + _loop_9(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -149506,14 +151970,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_12 = function (i) { + var _loop_10 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return "".concat(JSON.stringify(normalized[i].range), " and ").concat(JSON.stringify(normalized[i + 1].range)); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_12(i); + _loop_10(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -150224,7 +152688,6 @@ var ts; var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { var exportDeclaration = ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([]), /*moduleSpecifier*/ undefined); @@ -150422,7 +152885,7 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_13 = function (identifier) { + var _loop_11 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; @@ -150455,7 +152918,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_13(identifier); + _loop_11(identifier); } return initializers && { initializers: initializers, @@ -150754,8 +153217,7 @@ var ts; ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); var typeNode = ts.factory.createTypeReferenceNode(param.name, /*typeArguments*/ undefined); - var replacement = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); + var replacement = ts.factory.createParameterDeclaration(param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); changeTracker.replaceNode(sourceFile, param, replacement); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -150980,7 +153442,7 @@ var ts; var isRest = node.type.kind === 318 /* SyntaxKind.JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : node.dotDotDotToken; - return ts.factory.createParameterDeclaration(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + return ts.factory.createParameterDeclaration(node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); } function transformJSDocTypeReference(node) { var name = node.typeName; @@ -151015,12 +153477,11 @@ var ts; } function transformJSDocIndexSignature(node) { var index = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "n" : "s", /*questionToken*/ undefined, ts.factory.createTypeReferenceNode(node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "number" : "string", []), /*initializer*/ undefined); - var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*modifiers*/ undefined, [index], node.typeArguments[1])]); ts.setEmitFlags(indexSignature, 1 /* EmitFlags.SingleLine */); return indexSignature; } @@ -151162,7 +153623,7 @@ var ts; ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { - members.push(ts.factory.createPropertyDeclaration([], modifiers, symbol.name, /*questionToken*/ undefined, + members.push(ts.factory.createPropertyDeclaration(modifiers, symbol.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); return; } @@ -151198,7 +153659,7 @@ var ts; return; if (!ts.isPropertyAccessExpression(memberDeclaration)) return; - var prop = ts.factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); + var prop = ts.factory.createPropertyDeclaration(modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); members.push(prop); return; @@ -151211,7 +153672,7 @@ var ts; } function createFunctionExpressionMember(members, functionExpression, name) { var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 131 /* SyntaxKind.AsyncKeyword */)); - var method = ts.factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); @@ -151229,7 +153690,7 @@ var ts; bodyBlock = ts.factory.createBlock([ts.factory.createReturnStatement(arrowFunctionBody)]); } var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 131 /* SyntaxKind.AsyncKeyword */)); - var method = ts.factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); @@ -151243,10 +153704,10 @@ var ts; } var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { - memberElements.unshift(ts.factory.createConstructorDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, initializer.parameters, initializer.body)); } var modifiers = getModifierKindFromSource(node.parent.parent, 93 /* SyntaxKind.ExportKeyword */); - var cls = ts.factory.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + var cls = ts.factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; @@ -151254,17 +153715,17 @@ var ts; function createClassFromFunctionDeclaration(node) { var memberElements = createClassElementsFromSymbol(ctorSymbol); if (node.body) { - memberElements.unshift(ts.factory.createConstructorDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, node.parameters, node.body)); } var modifiers = getModifierKindFromSource(node, 93 /* SyntaxKind.ExportKeyword */); - var cls = ts.factory.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + var cls = ts.factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } } function getModifierKindFromSource(source, kind) { - return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + return ts.canHaveModifiers(source) ? ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }) : undefined; } function isConstructorAssignment(x) { if (!x.name) @@ -151340,12 +153801,9 @@ var ts; if (!returnStatements.length) { return; } - var pos = functionToConvert.modifiers ? functionToConvert.modifiers.end : - functionToConvert.decorators ? ts.skipTrivia(sourceFile.text, functionToConvert.decorators.end) : - functionToConvert.getStart(sourceFile); - var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; - changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, options); - var _loop_14 = function (returnStatement) { + var pos = ts.skipTrivia(sourceFile.text, ts.moveRangePastModifiers(functionToConvert).pos); + changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, { suffix: " " }); + var _loop_12 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); @@ -151367,7 +153825,7 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - var state_5 = _loop_14(returnStatement); + var state_5 = _loop_12(returnStatement); if (typeof state_5 === "object") return state_5.value; } @@ -152470,12 +154928,10 @@ var ts; } // Node helpers function functionExpressionToDeclaration(name, additionalModifiers, fn, useSitesToUnqualify) { - return ts.factory.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); + return ts.factory.createFunctionDeclaration(ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); } function classExpressionToDeclaration(name, additionalModifiers, cls, useSitesToUnqualify) { - return ts.factory.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); + return ts.factory.createClassDeclaration(ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); } function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" @@ -152490,7 +154946,6 @@ var ts; } function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { return ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, exportSpecifiers && ts.factory.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.factory.createStringLiteral(moduleSpecifier)); } @@ -152579,11 +155034,10 @@ var ts; changes.insertModifierBefore(context.sourceFile, 152 /* SyntaxKind.TypeKeyword */, exportClause); } else { - var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.decorators, exportDeclaration.modifiers, + var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, /*isTypeOnly*/ false, ts.factory.updateNamedExports(exportClause, ts.filter(exportClause.elements, function (e) { return !ts.contains(typeExportSpecifiers, e); })), exportDeclaration.moduleSpecifier, /*assertClause*/ undefined); var typeExportDeclaration = ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ true, ts.factory.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, /*assertClause*/ undefined); @@ -152647,7 +155101,6 @@ var ts; if (importClause.name && importClause.namedBindings) { changes.deleteNodeRangeExcludingEnd(context.sourceFile, importClause.name, importDeclaration.importClause.namedBindings); changes.insertNodeBefore(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ true, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, @@ -153001,6 +155454,18 @@ var ts; return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0; } } + function createImportSpecifierResolver(importingFile, program, host, preferences) { + var packageJsonImportFilter = ts.createPackageJsonImportFilter(importingFile, preferences, host); + var importMap = createExistingImportMap(program.getTypeChecker(), importingFile, program.getCompilerOptions()); + return { getModuleSpecifierForBestExportInfo: getModuleSpecifierForBestExportInfo }; + function getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, fromCacheOnly) { + var _a = getImportFixes(exportInfo, { symbolName: symbolName, position: position }, isValidTypeOnlyUseSite, + /*useRequire*/ false, program, importingFile, host, preferences, importMap, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount; + var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host); + return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount }); + } + } + codefix.createImportSpecifierResolver = createImportSpecifierResolver; // Sorted with the preferred fix coming first. var ImportFixKind; (function (ImportFixKind) { @@ -153078,7 +155543,7 @@ var ts; var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); }); - ts.forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { + ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(importingFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { @@ -153101,18 +155566,12 @@ var ts; return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, preferences, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); } } - function getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, importingFile, program, host, preferences, packageJsonImportFilter, fromCacheOnly) { - var _a = getImportFixes(exportInfo, { symbolName: symbolName, position: position }, isValidTypeOnlyUseSite, - /*useRequire*/ false, program, importingFile, host, preferences, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount; - var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter || ts.createPackageJsonImportFilter(importingFile, preferences, host), host); - return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount }); - } - codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo; function getImportFixes(exportInfos, useNamespaceInfo, /** undefined only for missing JSX namespace */ - isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, fromCacheOnly) { + isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap, fromCacheOnly) { + if (importMap === void 0) { importMap = createExistingImportMap(program.getTypeChecker(), sourceFile, program.getCompilerOptions()); } var checker = program.getTypeChecker(); - var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile, program.getCompilerOptions()); }); + var existingImports = ts.flatMap(exportInfos, importMap.getImportsForExportInfo); var useNamespace = useNamespaceInfo && tryUseExistingNamespaceImport(existingImports, useNamespaceInfo.symbolName, useNamespaceInfo.position, checker); var addToExisting = tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, program.getCompilerOptions()); if (addToExisting) { @@ -153240,21 +155699,37 @@ var ts; }; }); } - function getExistingImportDeclarations(_a, checker, importingFile, compilerOptions) { - var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, targetFlags = _a.targetFlags, symbol = _a.symbol; - // Can't use an es6 import for a type in JS. - if (!(targetFlags & 111551 /* SymbolFlags.Value */) && ts.isSourceFileJS(importingFile)) - return ts.emptyArray; - var importKind = getImportKind(importingFile, exportKind, compilerOptions); - return ts.mapDefined(importingFile.imports, function (moduleSpecifier) { + function createExistingImportMap(checker, importingFile, compilerOptions) { + var importMap; + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; var i = ts.importFromModuleSpecifier(moduleSpecifier); if (ts.isVariableDeclarationInitializedToRequire(i.parent)) { - return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind, symbol: symbol, targetFlags: targetFlags } : undefined; + var moduleSymbol = checker.resolveExternalModuleName(moduleSpecifier); + if (moduleSymbol) { + (importMap || (importMap = ts.createMultiMap())).add(ts.getSymbolId(moduleSymbol), i.parent); + } } - if (i.kind === 266 /* SyntaxKind.ImportDeclaration */ || i.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { - return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind, symbol: symbol, targetFlags: targetFlags } : undefined; + else if (i.kind === 266 /* SyntaxKind.ImportDeclaration */ || i.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol) { + (importMap || (importMap = ts.createMultiMap())).add(ts.getSymbolId(moduleSymbol), i); + } } - }); + } + return { + getImportsForExportInfo: function (_a) { + var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, targetFlags = _a.targetFlags, symbol = _a.symbol; + // Can't use an es6 import for a type in JS. + if (!(targetFlags & 111551 /* SymbolFlags.Value */) && ts.isSourceFileJS(importingFile)) + return ts.emptyArray; + var matchingDeclarations = importMap === null || importMap === void 0 ? void 0 : importMap.get(ts.getSymbolId(moduleSymbol)); + if (!matchingDeclarations) + return ts.emptyArray; + var importKind = getImportKind(importingFile, exportKind, compilerOptions); + return matchingDeclarations.map(function (declaration) { return ({ declaration: declaration, importKind: importKind, symbol: symbol, targetFlags: targetFlags }); }); + } + }; } function shouldUseRequire(sourceFile, program) { // 1. TypeScript files don't use require variable declarations @@ -153537,7 +156012,7 @@ var ts; originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol: moduleSymbol, moduleFileName: toFile === null || toFile === void 0 ? void 0 : toFile.fileName, exportKind: exportKind, targetFlags: ts.skipAlias(exportedSymbol, checker).flags, isFromPackageJson: isFromPackageJson }); } } - ts.forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { + ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); @@ -153797,10 +156272,8 @@ var ts; if (namespaceLikeImport) { var declaration = namespaceLikeImport.importKind === 3 /* ImportKind.CommonJS */ ? ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, needsTypeOnly(namespaceLikeImport), ts.factory.createIdentifier(namespaceLikeImport.name), ts.factory.createExternalModuleReference(quotedModuleSpecifier)) : ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(needsTypeOnly(namespaceLikeImport), /*name*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier, /*assertClause*/ undefined); @@ -153880,6 +156353,113 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingConstraint"; + var errorCodes = [ + // We want errors this could be attached to: + // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint + ts.Diagnostics.Type_0_is_not_comparable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + ts.Diagnostics.Property_0_is_incompatible_with_index_signature.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program, preferences = context.preferences, host = context.host; + var info = getInfo(program, sourceFile, span); + if (info === undefined) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingConstraint(t, program, preferences, host, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_extends_constraint, fixId, ts.Diagnostics.Add_extends_constraint_to_all_type_parameters)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var program = context.program, preferences = context.preferences, host = context.host; + var seen = new ts.Map(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(program, diag.file, ts.createTextSpan(diag.start, diag.length)); + if (info) { + if (ts.addToSeen(seen, ts.getNodeId(info.declaration))) { + return addMissingConstraint(changes, program, preferences, host, diag.file, info); + } + } + return undefined; + }); + })); + } + }); + function getInfo(program, sourceFile, span) { + var diag = ts.find(program.getSemanticDiagnostics(sourceFile), function (diag) { return diag.start === span.start && diag.length === span.length; }); + if (diag === undefined || diag.relatedInformation === undefined) + return; + var related = ts.find(diag.relatedInformation, function (related) { return related.code === ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code; }); + if (related === undefined || related.file === undefined || related.start === undefined || related.length === undefined) + return; + var declaration = findAncestorMatchingSpan(related.file, ts.createTextSpan(related.start, related.length)); + if (declaration === undefined) + return; + if (ts.isIdentifier(declaration) && ts.isTypeParameterDeclaration(declaration.parent)) { + declaration = declaration.parent; + } + if (ts.isTypeParameterDeclaration(declaration)) { + // should only issue fix on type parameters written using `extends` + if (ts.isMappedTypeNode(declaration.parent)) + return; + var token = ts.getTokenAtPosition(sourceFile, span.start); + var checker = program.getTypeChecker(); + var constraint = tryGetConstraintType(checker, token) || tryGetConstraintFromDiagnosticMessage(related.messageText); + return { constraint: constraint, declaration: declaration, token: token }; + } + return undefined; + } + function addMissingConstraint(changes, program, preferences, host, sourceFile, info) { + var declaration = info.declaration, constraint = info.constraint; + var checker = program.getTypeChecker(); + if (ts.isString(constraint)) { + changes.insertText(sourceFile, declaration.name.end, " extends ".concat(constraint)); + } + else { + var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions()); + var tracker = codefix.getNoopSymbolTrackerWithResolver({ program: program, host: host }); + var importAdder = codefix.createImportAdder(sourceFile, program, preferences, host); + var typeNode = codefix.typeToAutoImportableTypeNode(checker, importAdder, constraint, /*contextNode*/ undefined, scriptTarget, /*flags*/ undefined, tracker); + if (typeNode) { + changes.replaceNode(sourceFile, declaration, ts.factory.updateTypeParameterDeclaration(declaration, /*modifiers*/ undefined, declaration.name, typeNode, declaration.default)); + importAdder.writeFixes(changes); + } + } + } + function findAncestorMatchingSpan(sourceFile, span) { + var end = ts.textSpanEnd(span); + var token = ts.getTokenAtPosition(sourceFile, span.start); + while (token.end < end) { + token = token.parent; + } + return token; + } + function tryGetConstraintFromDiagnosticMessage(messageText) { + var _a = ts.flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || [], _ = _a[0], constraint = _a[1]; + return constraint; + } + function tryGetConstraintType(checker, node) { + if (ts.isTypeNode(node.parent)) { + return checker.getTypeArgumentConstraint(node.parent); + } + var contextualType = ts.isExpression(node) ? checker.getContextualType(node) : undefined; + return contextualType || checker.getTypeAtLocation(node); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -154002,10 +156582,11 @@ var ts; var staticModifier = ts.find(modifiers, ts.isStaticModifier); var abstractModifier = ts.find(modifiers, ts.isAbstractModifier); var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var lastDecorator = ts.findLast(modifiers, ts.isDecorator); var modifierPos = abstractModifier ? abstractModifier.end : staticModifier ? staticModifier.end : accessibilityModifier ? accessibilityModifier.end : - classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + lastDecorator ? ts.skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile); var options = accessibilityModifier || staticModifier || abstractModifier ? { prefix: " " } : { suffix: " " }; changeTracker.insertModifierAt(sourceFile, modifierPos, 159 /* SyntaxKind.OverrideKeyword */, options); } @@ -154015,7 +156596,7 @@ var ts; changeTracker.filterJSDocTags(sourceFile, classElement, ts.not(ts.isJSDocOverrideTag)); return; } - var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 159 /* SyntaxKind.OverrideKeyword */; }); + var overrideModifier = ts.find(classElement.modifiers, ts.isOverrideModifier); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); } @@ -154615,7 +157196,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, declaration) { var supers = ts.isTypeLiteralNode(declaration) ? undefined : codefix.getAllSupers(declaration, checker); - var _loop_15 = function (info) { + var _loop_13 = function (info) { // If some superclass added this property, don't add it again. if (supers === null || supers === void 0 ? void 0 : supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -154642,7 +157223,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_15(info); + _loop_13(info); } }); })); @@ -154694,7 +157275,7 @@ var ts; return undefined; return { kind: 4 /* InfoKind.JsxAttributes */, token: token, attributes: attributes, parentDeclaration: token.parent }; } - if (ts.isIdentifier(token) && ts.isCallExpression(parent)) { + if (ts.isIdentifier(token) && ts.isCallExpression(parent) && parent.expression === token) { return { kind: 2 /* InfoKind.Function */, token: token, call: parent, sourceFile: sourceFile, modifierFlags: 0 /* ModifierFlags.None */, parentDeclaration: sourceFile }; } if (!ts.isPropertyAccessExpression(parent)) @@ -154771,7 +157352,6 @@ var ts; } else if (ts.isPrivateIdentifier(token)) { var property = ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, tokenName, /*questionToken*/ undefined, /*type*/ undefined, @@ -154829,7 +157409,7 @@ var ts; function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) { var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var property = ts.isClassLike(node) - ? ts.factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined) + ? ts.factory.createPropertyDeclaration(modifiers, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined) : ts.factory.createPropertySignature(/*modifiers*/ undefined, tokenName, /*questionToken*/ undefined, typeNode); var lastProp = getNodeToInsertPropertyAfter(node); if (lastProp) { @@ -154854,13 +157434,11 @@ var ts; // Index signatures cannot have the static modifier. var stringTypeNode = ts.factory.createKeywordTypeNode(150 /* SyntaxKind.StringKeyword */); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); var indexSignature = ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertMemberAtStart(sourceFile, node, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. @@ -154908,7 +157486,7 @@ var ts; return !!(type && type.flags & 402653316 /* TypeFlags.StringLike */); }); var enumMember = ts.factory.createEnumMember(token, hasStringInitializer ? ts.factory.createStringLiteral(token.text) : undefined); - changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.decorators, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), { + changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude }); @@ -154917,6 +157495,7 @@ var ts; var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(256 /* SyntaxKind.FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration); changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); + importAdder.writeFixes(changes); } function addJsxAttributes(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); @@ -154925,7 +157504,7 @@ var ts; var jsxAttributesNode = info.parentDeclaration.attributes; var hasSpreadAttribute = ts.some(jsxAttributesNode.properties, ts.isJsxSpreadAttribute); var attrs = ts.map(info.attributes, function (attr) { - var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr)); + var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr), info.parentDeclaration); var name = ts.factory.createIdentifier(attr.name); var jsxAttribute = ts.factory.createJsxAttribute(name, ts.factory.createJsxExpression(/*dotDotDotToken*/ undefined, value)); // formattingScanner requires the Identifier to have a context for scanning attributes with "-" (data-foo). @@ -154935,6 +157514,7 @@ var ts; var jsxAttributes = ts.factory.createJsxAttributes(hasSpreadAttribute ? __spreadArray(__spreadArray([], attrs, true), jsxAttributesNode.properties, true) : __spreadArray(__spreadArray([], jsxAttributesNode.properties, true), attrs, true)); var options = { prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : undefined }; changes.replaceNode(context.sourceFile, jsxAttributesNode, jsxAttributes, options); + importAdder.writeFixes(changes); } function addObjectLiteralProperties(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); @@ -154942,8 +157522,8 @@ var ts; var target = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var props = ts.map(info.properties, function (prop) { - var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop)); - return ts.factory.createPropertyAssignment(ts.createPropertyNameNodeForIdentifierOrLiteral(prop.name, target, quotePreference === 0 /* QuotePreference.Single */), initializer); + var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), info.parentDeclaration); + return ts.factory.createPropertyAssignment(createPropertyNameFromSymbol(prop, target, quotePreference, checker), initializer); }); var options = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, @@ -154951,8 +157531,9 @@ var ts; indentation: info.indentation }; changes.replaceNode(context.sourceFile, info.parentDeclaration, ts.factory.createObjectLiteralExpression(__spreadArray(__spreadArray([], info.parentDeclaration.properties, true), props, true), /*multiLine*/ true), options); + importAdder.writeFixes(changes); } - function tryGetValueFromType(context, checker, importAdder, quotePreference, type) { + function tryGetValueFromType(context, checker, importAdder, quotePreference, type, enclosingDeclaration) { if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { return createUndefined(); } @@ -154989,7 +157570,7 @@ var ts; return ts.factory.createNull(); } if (type.flags & 1048576 /* TypeFlags.Union */) { - var expression = ts.firstDefined(type.types, function (t) { return tryGetValueFromType(context, checker, importAdder, quotePreference, t); }); + var expression = ts.firstDefined(type.types, function (t) { return tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration); }); return expression !== null && expression !== void 0 ? expression : createUndefined(); } if (checker.isArrayLikeType(type)) { @@ -154997,7 +157578,7 @@ var ts; } if (isObjectLiteralType(type)) { var props = ts.map(checker.getPropertiesOfType(type), function (prop) { - var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration)) : createUndefined(); + var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration), enclosingDeclaration) : createUndefined(); return ts.factory.createPropertyAssignment(prop.name, initializer); }); return ts.factory.createObjectLiteralExpression(props, /*multiLine*/ true); @@ -155009,7 +157590,7 @@ var ts; var signature = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (signature === undefined) return createUndefined(); - var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ undefined, importAdder); + var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ enclosingDeclaration, importAdder); return func !== null && func !== void 0 ? func : createUndefined(); } if (ts.getObjectFlags(type) & 1 /* ObjectFlags.Class */) { @@ -155062,6 +157643,15 @@ var ts; var declaration = ts.findAncestor(callExpression, function (n) { return ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n); }); return declaration && declaration.parent === node ? declaration : undefined; } + function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) { + if (ts.isTransientSymbol(symbol) && symbol.nameType && symbol.nameType.flags & 8192 /* TypeFlags.UniqueESSymbol */) { + var expression = checker.symbolToExpression(symbol.nameType.symbol, 111551 /* SymbolFlags.Value */, symbol.valueDeclaration, 1048576 /* NodeBuilderFlags.AllowUniqueESSymbolType */); + if (expression) { + return ts.factory.createComputedPropertyName(expression); + } + } + return ts.createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* QuotePreference.Single */); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -155987,7 +158577,12 @@ var ts; if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) { if (parameter.modifiers && parameter.modifiers.length > 0 && (!ts.isIdentifier(parameter.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) { - parameter.modifiers.forEach(function (modifier) { return changes.deleteModifier(sourceFile, modifier); }); + for (var _i = 0, _a = parameter.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isModifier(modifier)) { + changes.deleteModifier(sourceFile, modifier); + } + } } else if (!parameter.initializer && isNotProvidedArguments(parameter, checker, sourceFiles)) { changes.delete(sourceFile, parameter); @@ -157402,7 +159997,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_16 = function (i) { + var _loop_14 = function (i) { var symbol = checker.createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg".concat(i))); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -157411,7 +160006,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_16(i); + _loop_14(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* SignatureFlags.None */); @@ -157601,8 +160196,7 @@ var ts; importSymbols(importAdder, importableReference.symbols); } } - addClassElement(ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, + addClassElement(ts.factory.createPropertyDeclaration(modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; case 172 /* SyntaxKind.GetAccessor */: @@ -157622,15 +160216,13 @@ var ts; for (var _i = 0, orderedAccessors_1 = orderedAccessors; _i < orderedAccessors_1.length; _i++) { var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { - addClassElement(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createGetAccessorDeclaration(modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; - addClassElement(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createSetAccessorDeclaration(modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } } break; @@ -157644,7 +160236,7 @@ var ts; // If there is more than one overload but no implementation signature // (eg: an abstract method or interface declaration), there is a 1-1 // correspondence of declarations and signatures. - var signatures = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); + var signatures = type.isUnion() ? ts.flatMap(type.types, function (t) { return t.getCallSignatures(); }) : type.getCallSignatures(); if (!ts.some(signatures)) { break; } @@ -157725,7 +160317,7 @@ var ts; type = importableReference.typeNode; importSymbols(importAdder, importableReference.symbols); } - return ts.factory.updateParameterDeclaration(parameterDecl, parameterDecl.decorators, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, parameterDecl.questionToken, type, parameterDecl.initializer); + return ts.factory.updateParameterDeclaration(parameterDecl, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, parameterDecl.questionToken, type, parameterDecl.initializer); }); if (parameters !== newParameters) { parameters = ts.setTextRange(ts.factory.createNodeArray(newParameters, parameters.hasTrailingComma), parameters); @@ -157747,7 +160339,7 @@ var ts; return ts.factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body !== null && body !== void 0 ? body : signatureDeclaration.body); } if (ts.isMethodDeclaration(signatureDeclaration)) { - return ts.factory.updateMethodDeclaration(signatureDeclaration, /* decorators */ undefined, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); + return ts.factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); } return undefined; } @@ -157763,40 +160355,50 @@ var ts; var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined; }); - var types = isJs ? [] : ts.map(args, function (arg) { - return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker); - }); + var instanceTypes = isJs ? [] : ts.map(args, function (arg) { return checker.getTypeAtLocation(arg); }); + var _a = getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, /*flags*/ undefined, tracker), argumentTypeNodes = _a.argumentTypeNodes, argumentTypeParameters = _a.argumentTypeParameters; var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var asteriskToken = ts.isYieldExpression(parent) ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined; - var typeParameters = isJs || typeArguments === undefined - ? undefined - : ts.map(typeArguments, function (_, i) { - return ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, 84 /* CharacterCodes.T */ + typeArguments.length - 1 <= 90 /* CharacterCodes.Z */ ? String.fromCharCode(84 /* CharacterCodes.T */ + i) : "T".concat(i)); - }); - var parameters = createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, isJs); + var typeParameters = isJs ? undefined : createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments); + var parameters = createDummyParameters(args.length, names, argumentTypeNodes, /*minArgumentCount*/ undefined, isJs); var type = isJs || contextualType === undefined ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); switch (kind) { case 169 /* SyntaxKind.MethodDeclaration */: - return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers, asteriskToken, name, + return ts.factory.createMethodDeclaration(modifiers, asteriskToken, name, /*questionToken*/ undefined, typeParameters, parameters, type, createStubbedMethodBody(quotePreference)); case 168 /* SyntaxKind.MethodSignature */: return ts.factory.createMethodSignature(modifiers, name, - /*questionToken*/ undefined, typeParameters, parameters, type); + /*questionToken*/ undefined, typeParameters, parameters, type === undefined ? ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */) : type); case 256 /* SyntaxKind.FunctionDeclaration */: - return ts.factory.createFunctionDeclaration( - /*decorators*/ undefined, modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); + return ts.factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); default: ts.Debug.fail("Unexpected kind"); } } codefix.createSignatureDeclarationFromCallExpression = createSignatureDeclarationFromCallExpression; + function createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments) { + var usedNames = new ts.Set(argumentTypeParameters.map(function (pair) { return pair[0]; })); + var constraintsByName = new ts.Map(argumentTypeParameters); + if (typeArguments) { + var typeArgumentsWithNewTypes = typeArguments.filter(function (typeArgument) { return !argumentTypeParameters.some(function (pair) { var _a; return checker.getTypeAtLocation(typeArgument) === ((_a = pair[1]) === null || _a === void 0 ? void 0 : _a.argumentType); }); }); + var targetSize = usedNames.size + typeArgumentsWithNewTypes.length; + for (var i = 0; usedNames.size < targetSize; i += 1) { + usedNames.add(createTypeParameterName(i)); + } + } + return ts.map(ts.arrayFrom(usedNames.values()), function (usedName) { var _a; return ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, usedName, (_a = constraintsByName.get(usedName)) === null || _a === void 0 ? void 0 : _a.constraint); }); + } + function createTypeParameterName(index) { + return 84 /* CharacterCodes.T */ + index <= 90 /* CharacterCodes.Z */ + ? String.fromCharCode(84 /* CharacterCodes.T */ + index) + : "T".concat(index); + } function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); if (typeNode && ts.isImportTypeNode(typeNode)) { @@ -157810,16 +160412,107 @@ var ts; return ts.getSynthesizedDeepClone(typeNode); } codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode; + function typeContainsTypeParameter(type) { + if (type.isUnionOrIntersection()) { + return type.types.some(typeContainsTypeParameter); + } + return type.flags & 262144 /* TypeFlags.TypeParameter */; + } + function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, tracker) { + // Types to be used as the types of the parameters in the new function + // E.g. from this source: + // added("", 0) + // The value will look like: + // [{ typeName: { text: "string" } }, { typeName: { text: "number" }] + // And in the output function will generate: + // function added(a: string, b: number) { ... } + var argumentTypeNodes = []; + // Names of type parameters provided as arguments to the call + // E.g. from this source: + // added(value); + // The value will look like: + // [ + // ["T", { argumentType: { typeName: { text: "T" } } } ], + // ["U", { argumentType: { typeName: { text: "U" } } } ], + // ] + // And in the output function will generate: + // function added() { ... } + var argumentTypeParameters = new ts.Map(); + for (var i = 0; i < instanceTypes.length; i += 1) { + var instanceType = instanceTypes[i]; + // If the instance type contains a deep reference to an existing type parameter, + // instead of copying the full union or intersection, create a new type parameter + // E.g. from this source: + // function existing(value: T | U & string) { + // added/*1*/(value); + // We don't want to output this: + // function added(value: T | U & string) { ... } + // We instead want to output: + // function added(value: T) { ... } + if (instanceType.isUnionOrIntersection() && instanceType.types.some(typeContainsTypeParameter)) { + var synthesizedTypeParameterName = createTypeParameterName(i); + argumentTypeNodes.push(ts.factory.createTypeReferenceNode(synthesizedTypeParameterName)); + argumentTypeParameters.set(synthesizedTypeParameterName, undefined); + continue; + } + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + var widenedInstanceType = checker.getBaseTypeOfLiteralType(instanceType); + var argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, tracker); + if (!argumentTypeNode) { + continue; + } + argumentTypeNodes.push(argumentTypeNode); + var argumentTypeParameter = getFirstTypeParameterName(instanceType); + // If the instance type is a type parameter with a constraint (other than an anonymous object), + // remember that constraint for when we create the new type parameter + // E.g. from this source: + // function existing(value: T) { + // added/*1*/(value); + // We don't want to output this: + // function added(value: T) { ... } + // We instead want to output: + // function added(value: T) { ... } + var instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) + ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, tracker) + : undefined; + if (argumentTypeParameter) { + argumentTypeParameters.set(argumentTypeParameter, { argumentType: instanceType, constraint: instanceTypeConstraint }); + } + } + return { argumentTypeNodes: argumentTypeNodes, argumentTypeParameters: ts.arrayFrom(argumentTypeParameters.entries()) }; + } + codefix.getArgumentTypesAndTypeParameters = getArgumentTypesAndTypeParameters; + function isAnonymousObjectConstraintType(type) { + return (type.flags & 524288 /* TypeFlags.Object */) && type.objectFlags === 16 /* ObjectFlags.Anonymous */; + } + function getFirstTypeParameterName(type) { + var _a; + if (type.flags & (1048576 /* TypeFlags.Union */ | 2097152 /* TypeFlags.Intersection */)) { + for (var _i = 0, _b = type.types; _i < _b.length; _i++) { + var subType = _b[_i]; + var subTypeName = getFirstTypeParameterName(subType); + if (subTypeName) { + return subTypeName; + } + } + } + return type.flags & 262144 /* TypeFlags.TypeParameter */ + ? (_a = type.getSymbol()) === null || _a === void 0 ? void 0 : _a.getName() + : undefined; + } function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; + var parameterNameCounts = new ts.Map(); for (var i = 0; i < argCount; i++) { + var parameterName = (names === null || names === void 0 ? void 0 : names[i]) || "arg".concat(i); + var parameterNameCount = parameterNameCounts.get(parameterName); + parameterNameCounts.set(parameterName, (parameterNameCount || 0) + 1); var newParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - /*name*/ names && names[i] || "arg".concat(i), + /*name*/ parameterName + (parameterNameCount || ""), /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, - /*type*/ inJs ? undefined : types && types[i] || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), + /*type*/ inJs ? undefined : (types === null || types === void 0 ? void 0 : types[i]) || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -157848,7 +160541,6 @@ var ts; var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var restParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, ts.factory.createArrayTypeNode(ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */)), /*initializer*/ undefined); @@ -157864,8 +160556,7 @@ var ts; } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { - return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers, + return ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } function createStubbedMethodBody(quotePreference) { @@ -157996,6 +160687,9 @@ var ts; accessorModifiers = ts.createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); fieldModifiers = ts.createModifiers(prepareModifierFlagsForField(modifierFlags)); } + if (ts.canHaveDecorators(declaration)) { + fieldModifiers = ts.concatenate(ts.getDecorators(declaration), fieldModifiers); + } } updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); @@ -158060,7 +160754,7 @@ var ts; error: ts.getLocaleSpecificMessage(ts.Diagnostics.Name_is_not_valid) }; } - if ((ts.getEffectiveModifierFlags(declaration) | meaning) !== meaning) { + if (((ts.getEffectiveModifierFlags(declaration) & 125951 /* ModifierFlags.Modifier */) | meaning) !== meaning) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_property_with_modifier) }; @@ -158083,17 +160777,14 @@ var ts; } codefix.getAccessorConvertiblePropertyAtPosition = getAccessorConvertiblePropertyAtPosition; function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { - return ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, accessorName, + return ts.factory.createGetAccessorDeclaration(modifiers, accessorName, /*parameters*/ undefined, // TODO: GH#18217 type, ts.factory.createBlock([ ts.factory.createReturnStatement(createAccessorAccessExpression(fieldName, isStatic, container)) ], /*multiLine*/ true)); } function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { - return ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, accessorName, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createSetAccessorDeclaration(modifiers, accessorName, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.factory.createIdentifier("value"), /*questionToken*/ undefined, type)], ts.factory.createBlock([ @@ -158101,7 +160792,7 @@ var ts; ], /*multiLine*/ true)); } function updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) { - var property = ts.factory.updatePropertyDeclaration(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); + var property = ts.factory.updatePropertyDeclaration(declaration, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); changeTracker.replaceNode(file, declaration, property); } function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { @@ -158116,7 +160807,7 @@ var ts; updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - changeTracker.replaceNode(file, declaration, ts.factory.updateParameterDeclaration(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + changeTracker.replaceNode(file, declaration, ts.factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } function insertAccessor(changeTracker, file, accessor, declaration, container) { @@ -158190,7 +160881,6 @@ var ts; if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, namespace.name, ts.factory.createExternalModuleReference(node.moduleSpecifier)))); } @@ -158327,7 +161017,7 @@ var ts; } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { ts.suppressLeadingAndTrailingTrivia(propertyDeclaration); - var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* SyntaxKind.ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* SyntaxKind.ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, info) { @@ -158357,7 +161047,7 @@ var ts; } function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { ts.suppressLeadingAndTrailingTrivia(propertyDeclaration); - var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { @@ -158423,8 +161113,8 @@ var ts; function doChange(changes, sourceFile, info) { var allowSyntheticDefaults = info.allowSyntheticDefaults, defaultImportName = info.defaultImportName, namedImports = info.namedImports, statement = info.statement, required = info.required; changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults - ? ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required)) - : ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); + ? ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required)) + : ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); } function getInfo(sourceFile, program, pos) { var parent = ts.getTokenAtPosition(sourceFile, pos).parent; @@ -158562,7 +161252,7 @@ var ts; return token.parent; } function doChange(changes, sourceFile, importType) { - var newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + var newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.assertions, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); changes.replaceNode(sourceFile, importType, newTypeNode); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -158679,7 +161369,7 @@ var ts; return { indexSignature: indexSignature, container: container }; } function createTypeAliasFromInterface(declaration, type) { - return ts.factory.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + return ts.factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); } function doChange(changes, sourceFile, _a) { var indexSignature = _a.indexSignature, container = _a.container; @@ -158795,9 +161485,8 @@ var ts; return; } var importClause = ts.Debug.checkDefined(importDeclaration.importClause); - changes.replaceNode(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); + changes.replaceNode(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); changes.insertNodeAfter(context.sourceFile, importDeclaration, ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ undefined, importClause.namedBindings), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -159019,14 +161708,14 @@ var ts; if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_export_statement) }; } - var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var checker = program.getTypeChecker(); + var exportingModuleSymbol = getExportingModuleSymbol(exportNode, checker); var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ModifierFlags.ExportDefault */ : 0 /* ModifierFlags.None */); var wasDefault = !!(flags & 512 /* ModifierFlags.Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* ModifierFlags.Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* InternalSymbolName.Default */)) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.This_file_already_has_a_default_export) }; } - var checker = program.getTypeChecker(); var noSymbolError = function (id) { return (ts.isIdentifier(id) && checker.getSymbolAtLocation(id)) ? undefined : { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_named_export) }; @@ -159078,7 +161767,7 @@ var ts; if (ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) { var exp = exportNode.expression; var spec = makeExportSpecifier(exp.text, exp.text); - changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); + changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); } else { changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 88 /* SyntaxKind.DefaultKeyword */), "Should find a default keyword in modifier list")); @@ -159118,6 +161807,8 @@ var ts; var checker = program.getTypeChecker(); var exportSymbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + if (exportName === ref) + return; var importingSourceFile = ref.getSourceFile(); if (wasDefault) { changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); @@ -159166,7 +161857,7 @@ var ts; } case 200 /* SyntaxKind.ImportType */: var importTypeNode = parent; - changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); + changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); break; default: ts.Debug.failBadSyntaxKind(parent); @@ -159210,6 +161901,17 @@ var ts; function makeExportSpecifier(propertyName, name) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, propertyName === name ? undefined : ts.factory.createIdentifier(propertyName), ts.factory.createIdentifier(name)); } + function getExportingModuleSymbol(node, checker) { + var parent = node.parent; + if (ts.isSourceFile(parent)) { + return parent.symbol; + } + var symbol = parent.parent.symbol; + if (symbol.valueDeclaration && ts.isExternalModuleAugmentation(symbol.valueDeclaration)) { + return checker.getMergedSymbol(symbol); + } + return symbol; + } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ @@ -159384,7 +162086,7 @@ var ts; // Imports that need to be kept as named imports in the refactored code, to avoid changing the semantics. // More specifically, those are named imports that appear in named exports in the original code, e.g. `a` in `import { a } from "m"; export { a }`. var neededNamedImports = new ts.Set(); - var _loop_17 = function (element) { + var _loop_15 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -159401,7 +162103,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_17(element); + _loop_15(element); } changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? ts.factory.createIdentifier(namespaceImportName) @@ -159422,7 +162124,7 @@ var ts; return externalModule !== exportEquals; } function updateImport(old, defaultImportName, elements) { - return ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); + return ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); @@ -159736,7 +162438,7 @@ var ts; break; } case 169 /* SyntaxKind.MethodDeclaration */: { - updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } case 174 /* SyntaxKind.CallSignature */: { @@ -159744,7 +162446,7 @@ var ts; break; } case 171 /* SyntaxKind.Constructor */: { - updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); + updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); break; } case 175 /* SyntaxKind.ConstructSignature */: { @@ -159752,7 +162454,7 @@ var ts; break; } case 256 /* SyntaxKind.FunctionDeclaration */: { - updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } default: return ts.Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); @@ -159772,7 +162474,6 @@ var ts; } return ts.factory.createNodeArray([ ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), "args", /*questionToken*/ undefined, ts.factory.createUnionTypeNode(ts.map(signatureDeclarations, convertSignatureParametersToTuple))) ]); @@ -159819,6 +162520,9 @@ var ts; if (!containingDecl) { return; } + if (ts.isFunctionLikeDeclaration(containingDecl) && containingDecl.body && ts.rangeContainsPosition(containingDecl.body, startPosition)) { + return; + } var checker = program.getTypeChecker(); var signatureSymbol = containingDecl.symbol; if (!signatureSymbol) { @@ -159839,7 +162543,7 @@ var ts; return; } var signatureDecls = decls; - if (ts.some(signatureDecls, function (d) { return !!d.typeParameters || ts.some(d.parameters, function (p) { return !!p.decorators || !!p.modifiers || !ts.isIdentifier(p.name); }); })) { + if (ts.some(signatureDecls, function (d) { return !!d.typeParameters || ts.some(d.parameters, function (p) { return !!p.modifiers || !ts.isIdentifier(p.name); }); })) { return; } var signatures = ts.mapDefined(signatureDecls, function (d) { return checker.getSignatureFromDeclaration(d); }); @@ -160169,11 +162873,11 @@ var ts; } } else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { - var declarations_5 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; + var declarations_6 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, declarations_4 = declarations_5; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + for (var _i = 0, declarations_5 = declarations_6; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; if (declaration.initializer) { numInitializers++; lastInitializer = declaration.initializer; @@ -160332,7 +163036,7 @@ var ts; var savedPermittedJumps = permittedJumps; switch (node.kind) { case 239 /* SyntaxKind.IfStatement */: - permittedJumps = 0 /* PermittedJumps.None */; + permittedJumps &= ~4 /* PermittedJumps.Return */; break; case 252 /* SyntaxKind.TryStatement */: // forbid all jumps inside try blocks @@ -160624,7 +163328,6 @@ var ts; typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NodeBuilderFlags.NoTruncation */); } var paramDecl = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ name, @@ -160664,22 +163367,19 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { modifiers.push(ts.factory.createModifier(131 /* SyntaxKind.AsyncKeyword */)); } - newFunction = ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, + newFunction = ts.factory.createMethodDeclaration(modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { if (callThis) { parameters.unshift(ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ "this", /*questionToken*/ undefined, checker.typeToTypeNode(checker.getTypeAtLocation(range.thisNode), scope, 1 /* NodeBuilderFlags.NoTruncation */), /*initializer*/ undefined)); } - newFunction = ts.factory.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + newFunction = ts.factory.createFunctionDeclaration(range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; @@ -160861,8 +163561,7 @@ var ts; modifiers.push(ts.factory.createModifier(124 /* SyntaxKind.StaticKeyword */)); } modifiers.push(ts.factory.createModifier(145 /* SyntaxKind.ReadonlyKeyword */)); - var newVariable = ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, localNameText, + var newVariable = ts.factory.createPropertyDeclaration(modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.factory.createPropertyAccessExpression(rangeFacts & RangeFacts.InStaticRegion ? ts.factory.createIdentifier(scope.name.getText()) // TODO: GH#18217 @@ -160957,7 +163656,7 @@ var ts; var paramType = checker.getTypeAtLocation(p); if (paramType === checker.getAnyType()) hasAny = true; - parameters.push(ts.factory.updateParameterDeclaration(p, p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NodeBuilderFlags.NoTruncation */), p.initializer)); + parameters.push(ts.factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NodeBuilderFlags.NoTruncation */), p.initializer)); } } // If a parameter was inferred as any we skip adding function parameters at all. @@ -160967,7 +163666,7 @@ var ts; return { variableType: variableType, initializer: initializer }; variableType = undefined; if (ts.isArrowFunction(initializer)) { - initializer = ts.factory.updateArrowFunction(initializer, node.modifiers, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.equalsGreaterThanToken, initializer.body); + initializer = ts.factory.updateArrowFunction(initializer, ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.equalsGreaterThanToken, initializer.body); } else { if (functionSignature && !!functionSignature.thisParameter) { @@ -160977,13 +163676,12 @@ var ts; if ((!firstParameter || (ts.isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this"))) { var thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); parameters.splice(0, 0, ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, checker.typeToTypeNode(thisType, scope, 1 /* NodeBuilderFlags.NoTruncation */))); } } - initializer = ts.factory.updateFunctionExpression(initializer, node.modifiers, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.body); + initializer = ts.factory.updateFunctionExpression(initializer, ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.body); } return { variableType: variableType, initializer: initializer }; } @@ -161299,7 +163997,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_18 = function (i) { + var _loop_16 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -161342,7 +164040,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_18(i); + _loop_16(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -161778,7 +164476,6 @@ var ts; function doTypeAliasChange(changes, file, name, info) { var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters; var newTypeNode = ts.factory.createTypeAliasDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters.map(function (id) { return ts.factory.updateTypeParameterDeclaration(id, id.modifiers, id.name, id.constraint, /* defaultType */ undefined); }), selection); changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true); changes.replaceNode(file, selection, ts.factory.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.factory.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.ExcludeWhitespace }); @@ -161787,7 +164484,6 @@ var ts; var _a; var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters, typeElements = info.typeElements; var newTypeNode = ts.factory.createInterfaceDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters, /* heritageClauses */ undefined, typeElements); ts.setTextRange(newTypeNode, (_a = typeElements[0]) === null || _a === void 0 ? void 0 : _a.parent); @@ -161951,7 +164647,7 @@ var ts; var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); var extension = ts.extensionFromPath(oldFile.fileName); - var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.oldFileImportsFromNewFile, usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); @@ -162045,10 +164741,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_19 = function (sourceFile) { + var _loop_17 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_20 = function (statement) { + var _loop_18 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -162070,12 +164766,12 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_20(statement); + _loop_18(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_19(sourceFile); + _loop_17(sourceFile); } } function getNamespaceLikeImport(node) { @@ -162118,10 +164814,10 @@ var ts; switch (node.kind) { case 266 /* SyntaxKind.ImportDeclaration */: return ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, + /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, /*assertClause*/ undefined); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); + return ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); case 254 /* SyntaxKind.VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: @@ -162315,8 +165011,8 @@ var ts; newModuleName = "".concat(moduleName, ".").concat(i); } } - function getNewModuleName(movedSymbols) { - return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + function getNewModuleName(importsFromNewFile, movedSymbols) { + return importsFromNewFile.forEachEntry(ts.symbolNameNoDefault) || movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; } function getUsageInfo(oldFile, toMove, checker) { var movedSymbols = new SymbolSet(); @@ -162409,7 +165105,7 @@ var ts; var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); return defaultImport || namedBindings - ? ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) + ? ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) : undefined; } case 265 /* SyntaxKind.ImportEqualsDeclaration */: @@ -162574,24 +165270,25 @@ var ts; return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); } function addEs6Export(d) { - var modifiers = ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], d.modifiers); + var modifiers = ts.canHaveModifiers(d) ? ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], ts.getModifiers(d)) : undefined; switch (d.kind) { case 256 /* SyntaxKind.FunctionDeclaration */: - return ts.factory.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + return ts.factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); case 257 /* SyntaxKind.ClassDeclaration */: - return ts.factory.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + var decorators = ts.canHaveDecorators(d) ? ts.getDecorators(d) : undefined; + return ts.factory.updateClassDeclaration(d, ts.concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); case 237 /* SyntaxKind.VariableStatement */: return ts.factory.updateVariableStatement(d, modifiers, d.declarationList); case 261 /* SyntaxKind.ModuleDeclaration */: - return ts.factory.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + return ts.factory.updateModuleDeclaration(d, modifiers, d.name, d.body); case 260 /* SyntaxKind.EnumDeclaration */: - return ts.factory.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + return ts.factory.updateEnumDeclaration(d, modifiers, d.name, d.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return ts.factory.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + return ts.factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); case 258 /* SyntaxKind.InterfaceDeclaration */: - return ts.factory.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + return ts.factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.isTypeOnly, d.name, d.moduleReference); + return ts.factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); case 238 /* SyntaxKind.ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: @@ -163088,7 +165785,7 @@ var ts; if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false; } - return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name); + return !parameterDeclaration.modifiers && ts.isIdentifier(parameterDeclaration.name); } function isValidVariableDeclaration(node) { return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113 @@ -163147,14 +165844,12 @@ var ts; objectInitializer = ts.factory.createObjectLiteralExpression(); } var objectParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, objectParameterName, /*questionToken*/ undefined, objectParameterType, objectInitializer); if (hasThisParameter(functionDeclaration.parameters)) { var thisParameter = functionDeclaration.parameters[0]; var newThisParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, thisParameter.type); @@ -163439,7 +166134,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText, rawHeadText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_21 = function (i) { + var _loop_19 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], rawSubsequentText = _c[2], stringIndexes = _c[3]; @@ -163468,7 +166163,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_21(i); + _loop_19(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -163675,7 +166370,7 @@ var ts; ts.suppressLeadingTrivia(statement); var modifiersFlags = (ts.getCombinedModifierFlags(variableDeclaration) & 1 /* ModifierFlags.Export */) | ts.getEffectiveModifierFlags(func); var modifiers = ts.factory.createModifiersFromModifierFlags(modifiersFlags); - var newNode = ts.factory.createFunctionDeclaration(func.decorators, ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + var newNode = ts.factory.createFunctionDeclaration(ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, statement, newNode); }); } @@ -164080,20 +166775,25 @@ var ts; return this.documentationComment; }; SymbolObject.prototype.getContextualDocumentationComment = function (context, checker) { - switch (context === null || context === void 0 ? void 0 : context.kind) { - case 172 /* SyntaxKind.GetAccessor */: + if (context) { + if (ts.isGetAccessor(context)) { if (!this.contextualGetAccessorDocumentationComment) { this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } - return this.contextualGetAccessorDocumentationComment; - case 173 /* SyntaxKind.SetAccessor */: + if (ts.length(this.contextualGetAccessorDocumentationComment)) { + return this.contextualGetAccessorDocumentationComment; + } + } + if (ts.isSetAccessor(context)) { if (!this.contextualSetAccessorDocumentationComment) { this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); } - return this.contextualSetAccessorDocumentationComment; - default: - return this.getDocumentationComment(checker); + if (ts.length(this.contextualSetAccessorDocumentationComment)) { + return this.contextualSetAccessorDocumentationComment; + } + } } + return this.getDocumentationComment(checker); }; SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { @@ -164102,20 +166802,25 @@ var ts; return this.tags; }; SymbolObject.prototype.getContextualJsDocTags = function (context, checker) { - switch (context === null || context === void 0 ? void 0 : context.kind) { - case 172 /* SyntaxKind.GetAccessor */: + if (context) { + if (ts.isGetAccessor(context)) { if (!this.contextualGetAccessorTags) { this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isGetAccessor), checker); } - return this.contextualGetAccessorTags; - case 173 /* SyntaxKind.SetAccessor */: + if (ts.length(this.contextualGetAccessorTags)) { + return this.contextualGetAccessorTags; + } + } + if (ts.isSetAccessor(context)) { if (!this.contextualSetAccessorTags) { this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isSetAccessor), checker); } - return this.contextualSetAccessorTags; - default: - return this.getJsDocTags(checker); + if (ts.length(this.contextualSetAccessorTags)) { + return this.contextualSetAccessorTags; + } + } } + return this.getJsDocTags(checker); }; return SymbolObject; }()); @@ -164296,7 +167001,7 @@ var ts; * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. */ function hasJSDocInheritDocTag(node) { - return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc"; }); } function getJsDocTagsOfDeclarations(declarations, checker) { if (!declarations) @@ -164304,7 +167009,7 @@ var ts; var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations, checker); if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) { var seenSymbols_1 = new ts.Set(); - var _loop_22 = function (declaration) { + var _loop_20 = function (declaration) { var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; if (!seenSymbols_1.has(symbol)) { @@ -164319,9 +167024,9 @@ var ts; tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); } }; - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - _loop_22(declaration); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + _loop_20(declaration); } } return tags; @@ -164332,7 +167037,7 @@ var ts; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { var seenSymbols_2 = new ts.Set(); - var _loop_23 = function (declaration) { + var _loop_21 = function (declaration) { var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { if (!seenSymbols_2.has(symbol)) { seenSymbols_2.add(symbol); @@ -164346,22 +167051,23 @@ var ts; if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); }; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - _loop_23(declaration); + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + _loop_21(declaration); } } return doc; } function findBaseOfDeclaration(checker, declaration, cb) { var _a; - if (ts.hasStaticModifier(declaration)) - return; var classOrInterfaceDeclaration = ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.kind) === 171 /* SyntaxKind.Constructor */ ? declaration.parent.parent : declaration.parent; if (!classOrInterfaceDeclaration) return; + var isStaticMember = ts.hasStaticModifier(declaration); return ts.firstDefined(ts.getAllSuperTypeNodes(classOrInterfaceDeclaration), function (superTypeNode) { - var symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name); + var baseType = checker.getTypeAtLocation(superTypeNode); + var type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType; + var symbol = checker.getPropertyOfType(type, declaration.symbol.name); return symbol ? cb(symbol) : undefined; }); } @@ -164604,70 +167310,6 @@ var ts; return ts.codefix.getSupportedErrorCodes(); } ts.getSupportedCodeFixes = getSupportedCodeFixes; - // Cache host information about script Should be refreshed - // at each language service public entry point, since we don't know when - // the set of scripts handled by the host changes. - var HostCache = /** @class */ (function () { - function HostCache(host, getCanonicalFileName) { - this.host = host; - // script id => script index - this.currentDirectory = host.getCurrentDirectory(); - this.fileNameToEntry = new ts.Map(); - // Initialize the list with the root file names - var rootFileNames = host.getScriptFileNames(); - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* tracing.Phase.Session */, "initializeHostCache", { count: rootFileNames.length }); - for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { - var fileName = rootFileNames_1[_i]; - this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); - } - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); - } - HostCache.prototype.createEntry = function (fileName, path) { - var entry; - var scriptSnapshot = this.host.getScriptSnapshot(fileName); - if (scriptSnapshot) { - entry = { - hostFileName: fileName, - version: this.host.getScriptVersion(fileName), - scriptSnapshot: scriptSnapshot, - scriptKind: ts.getScriptKind(fileName, this.host) - }; - } - else { - entry = fileName; - } - this.fileNameToEntry.set(path, entry); - return entry; - }; - HostCache.prototype.getEntryByPath = function (path) { - return this.fileNameToEntry.get(path); - }; - HostCache.prototype.getHostFileInformation = function (path) { - var entry = this.fileNameToEntry.get(path); - return !ts.isString(entry) ? entry : undefined; - }; - HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - var info = this.getEntryByPath(path) || this.createEntry(fileName, path); - return ts.isString(info) ? undefined : info; // TODO: GH#18217 - }; - HostCache.prototype.getRootFileNames = function () { - var names = []; - this.fileNameToEntry.forEach(function (entry) { - if (ts.isString(entry)) { - names.push(entry); - } - else { - names.push(entry.hostFileName); - } - }); - return names; - }; - HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getHostFileInformation(path); - return (file && file.scriptSnapshot); // TODO: GH#18217 - }; - return HostCache; - }()); var SyntaxTreeCache = /** @class */ (function () { function SyntaxTreeCache(host) { this.host = host; @@ -164929,32 +167571,16 @@ var ts; program = undefined; // TODO: GH#18217 lastTypesRootVersion = typeRootsVersion; } + // This array is retained by the program and will be used to determine if the program is up to date, + // so we need to make a copy in case the host mutates the underlying array - otherwise it would look + // like every program always has the host's current list of root files. + var rootFileNames = host.getScriptFileNames().slice(); // Get a fresh cache of the host information - var hostCache = new HostCache(host, getCanonicalFileName); - var rootFileNames = hostCache.getRootFileNames(); var newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; var hasChangedAutomaticTypeDirectiveNames = ts.maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); var projectReferences = (_b = host.getProjectReferences) === null || _b === void 0 ? void 0 : _b.call(host); var parsedCommandLines; - var parseConfigHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - fileExists: fileExists, - readFile: readFile, - readDirectory: readDirectory, - trace: ts.maybeBind(host, host.trace), - getCurrentDirectory: function () { return currentDirectory; }, - onUnRecoverableConfigFileDiagnostic: ts.noop, - }; - // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { - return; - } - // IMPORTANT - It is critical from this moment onward that we do not check - // cancellation tokens. We are about to mutate source files from a previous program - // instance. If we cancel midway through, we may end up in an inconsistent state where - // the program points to old source files that have been invalidated because of - // incremental parsing. // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -164966,8 +167592,8 @@ var ts; getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, - fileExists: fileExists, - readFile: readFile, + fileExists: function (fileName) { return host.fileExists(fileName); }, + readFile: function (fileName) { return host.readFile && host.readFile(fileName); }, getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache), realpath: ts.maybeBind(host, host.realpath), directoryExists: function (directoryName) { @@ -164976,19 +167602,56 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, - readDirectory: readDirectory, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, onReleaseParsedCommandLine: onReleaseParsedCommandLine, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, - trace: parseConfigHost.trace, + trace: ts.maybeBind(host, host.trace), resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), getModuleResolutionCache: ts.maybeBind(host, host.getModuleResolutionCache), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine: getParsedCommandLine, }; + var originalGetSourceFile = compilerHost.getSourceFile; + var getSourceFileWithCache = ts.changeCompilerHostLikeToUseCache(compilerHost, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args, false)); + }).getSourceFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; (_c = host.setCompilerHost) === null || _c === void 0 ? void 0 : _c.call(host, compilerHost); + var parseConfigHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, + readFile: function (fileName) { return compilerHost.readFile(fileName); }, + readDirectory: function () { + var _a; + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return (_a = compilerHost).readDirectory.apply(_a, args); + }, + trace: compilerHost.trace, + getCurrentDirectory: compilerHost.getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: ts.noop, + }; + // If the program is already up-to-date, we can reuse it + if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, function (fileName) { return compilerHost.fileExists(fileName); }, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + return; + } + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, @@ -164998,9 +167661,9 @@ var ts; projectReferences: projectReferences }; program = ts.createProgram(options); - // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. - // It needs to be cleared to allow all collected snapshots to be released - hostCache = undefined; + // 'getOrCreateSourceFile' depends on caching but should be used past this point. + // After this point, the cache needs to be cleared to allow all collected snapshots to be released + compilerHost = undefined; parsedCommandLines = undefined; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during @@ -165040,44 +167703,26 @@ var ts; onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); } } - function fileExists(fileName) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - return entry ? - !ts.isString(entry) : - (!!host.fileExists && host.fileExists(fileName)); - } - function readFile(fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - if (entry) { - return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); - } - return host.readFile && host.readFile(fileName); - } - function readDirectory(path, extensions, exclude, include, depth) { - ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(path, extensions, exclude, include, depth); - } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } - function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { - return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); + function getOrCreateSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersionOrOptions, onError, shouldCreateNewSourceFile); } - function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { - ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); + function getOrCreateSourceFileByPath(fileName, path, languageVersionOrOptions, _onError, shouldCreateNewSourceFile) { + ts.Debug.assert(compilerHost, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. - var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); - if (!hostFileInformation) { + var scriptSnapshot = host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { return undefined; } + var scriptKind = ts.getScriptKind(fileName, host); + var scriptVersion = host.getScriptVersion(fileName); // Check if the language version has changed since we last created a program; if they are the same, // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. @@ -165109,18 +167754,18 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { - return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } else { // Release old source file and fall through to aquire new file with new script kind - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } } // We didn't already have the file. Fall through and acquire it from the registry. } // Could not find this file in the old program, create a new SourceFile for it. - return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } } // TODO: GH#18217 frequently asserted as defined @@ -165136,6 +167781,61 @@ var ts; var _a; return (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); } + function updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans) { + var checker = program.getTypeChecker(); + var symbol = getSymbolForProgram(); + if (!symbol) + return false; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + var refNode = getNodeForSpan(ref); + ts.Debug.assertIsDefined(refNode); + if (knownSymbolSpans.has(ref) || ts.FindAllReferences.isDeclarationOfSymbol(refNode, symbol)) { + knownSymbolSpans.add(ref); + ref.isDefinition = true; + var mappedSpan = ts.getMappedDocumentSpan(ref, sourceMapper, ts.maybeBind(host, host.fileExists)); + if (mappedSpan) { + knownSymbolSpans.add(mappedSpan); + } + } + else { + ref.isDefinition = false; + } + } + } + return true; + function getSymbolForProgram() { + for (var _i = 0, referencedSymbols_2 = referencedSymbols; _i < referencedSymbols_2.length; _i++) { + var referencedSymbol = referencedSymbols_2[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + if (knownSymbolSpans.has(ref)) { + var refNode = getNodeForSpan(ref); + ts.Debug.assertIsDefined(refNode); + return checker.getSymbolAtLocation(refNode); + } + var mappedSpan = ts.getMappedDocumentSpan(ref, sourceMapper, ts.maybeBind(host, host.fileExists)); + if (mappedSpan && knownSymbolSpans.has(mappedSpan)) { + var refNode = getNodeForSpan(mappedSpan); + if (refNode) { + return checker.getSymbolAtLocation(refNode); + } + } + } + } + return undefined; + } + function getNodeForSpan(docSpan) { + var sourceFile = program.getSourceFile(docSpan.fileName); + if (!sourceFile) + return undefined; + var rawNode = ts.getTouchingPropertyName(sourceFile, docSpan.textSpan.start); + var adjustedNode = ts.FindAllReferences.Core.getAdjustedNode(rawNode, { use: 1 /* FindAllReferences.FindReferencesUse.References */ }); + return adjustedNode; + } + } function cleanupSemanticCache() { program = undefined; // TODO: GH#18217 } @@ -165144,7 +167844,7 @@ var ts; // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); ts.forEach(program.getSourceFiles(), function (f) { - return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind, f.impliedNodeFormat); }); program = undefined; // TODO: GH#18217 } @@ -165932,9 +168632,9 @@ var ts; return ts.stringContains(path, "/node_modules/"); } } - function getRenameInfo(fileName, position, options) { + function getRenameInfo(fileName, position, preferences) { synchronizeHostData(); - return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, preferences || {}); } function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason, kind) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; @@ -166061,7 +168761,9 @@ var ts; getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getProgram: getProgram, + getCurrentProgram: function () { return program; }, getAutoImportProvider: getAutoImportProvider, + updateIsDefinitionOfReferencedSymbols: updateIsDefinitionOfReferencedSymbols, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, toLineColumnOffset: toLineColumnOffset, @@ -166213,7 +168915,7 @@ var ts; function getDefaultLibFilePath(options) { // Check __dirname is defined and that we are on a node.js system. if (typeof __dirname !== "undefined") { - return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); + return ts.combinePaths(__dirname, ts.getDefaultLibFileName(options)); } throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); } @@ -166255,8 +168957,9 @@ var ts; // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - var start = startNode.decorators ? - ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + var lastDecorator = ts.canHaveDecorators(startNode) ? ts.findLast(startNode.modifiers, ts.isDecorator) : undefined; + var start = lastDecorator ? + ts.skipTrivia(sourceFile.text, lastDecorator.end) : startNode.getStart(sourceFile); return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } @@ -166269,8 +168972,20 @@ var ts; } return spanInNode(otherwiseOnNode); } - function spanInNodeArray(nodeArray) { - return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + function spanInNodeArray(nodeArray, node, match) { + if (nodeArray) { + var index = nodeArray.indexOf(node); + if (index >= 0) { + var start = index; + var end = index + 1; + while (start > 0 && match(nodeArray[start - 1])) + start--; + while (end < nodeArray.length && match(nodeArray[end])) + end++; + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray[start].pos), nodeArray[end - 1].end); + } + } + return textSpan(node); } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); @@ -166383,7 +169098,7 @@ var ts; // span in statement return spanInNode(node.statement); case 165 /* SyntaxKind.Decorator */: - return spanInNodeArray(parent.decorators); + return spanInNodeArray(parent.modifiers, node, ts.isDecorator); case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: return spanInBindingPattern(node); @@ -166546,7 +169261,7 @@ var ts; } // Breakpoint is possible in variableDeclaration only if there is initialization // or its declaration from 'for of' - if (variableDeclaration.initializer || + if ((ts.hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer) || ts.hasSyntacticModifier(variableDeclaration, 1 /* ModifierFlags.Export */) || parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); @@ -167286,9 +170001,9 @@ var ts; var _this = this; return this.forwardJSONCall("getImplementationAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, options); }); + return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, preferences); }); }; LanguageServiceShimObject.prototype.getSmartSelectionRange = function (fileName, position) { var _this = this; @@ -167513,7 +170228,8 @@ var ts; } return { resolvedFileName: resolvedFileName, - failedLookupLocations: result.failedLookupLocations + failedLookupLocations: result.failedLookupLocations, + affectingLocations: result.affectingLocations, }; }); }; @@ -167592,7 +170308,7 @@ var ts; if (_this.safeList === undefined) { _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); } - return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry); + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry, ts.emptyOptions); }); }; return CoreServicesShimObject; @@ -167925,16 +170641,6 @@ var ts; server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - ts.WatchType.ClosedScriptInfo = "Closed Script info"; - ts.WatchType.ConfigFileForInferredRoot = "Config file for the inferred project root"; - ts.WatchType.NodeModules = "node_modules for closed script infos and package.jsons affecting module specifier cache"; - ts.WatchType.MissingSourceMapFile = "Missing source map file"; - ts.WatchType.NoopConfigFileForInferredRoot = "Noop Config file for the inferred project root"; - ts.WatchType.MissingGeneratedFile = "Missing generated file"; -})(ts || (ts = {})); /* eslint-disable @typescript-eslint/no-unnecessary-qualifier */ /** * Declaration module describing the TypeScript Server protocol @@ -169095,6 +171801,38 @@ var ts; } return result.module; }; + /*@internal*/ + Project.importServicePluginAsync = function (moduleName, initialDir, host, log, logErrors) { + return __awaiter(this, void 0, void 0, function () { + var resolvedPath, result, e_1, err; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + ts.Debug.assertIsDefined(host.importServicePlugin); + resolvedPath = ts.combinePaths(initialDir, "node_modules"); + log("Dynamically importing ".concat(moduleName, " from ").concat(initialDir, " (resolved to ").concat(resolvedPath, ")")); + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, host.importServicePlugin(resolvedPath, moduleName)]; + case 2: + result = _a.sent(); + return [3 /*break*/, 4]; + case 3: + e_1 = _a.sent(); + result = { module: undefined, error: e_1 }; + return [3 /*break*/, 4]; + case 4: + if (result.error) { + err = result.error.stack || result.error.message || JSON.stringify(result.error); + (logErrors || log)("Failed to dynamically import module '".concat(moduleName, "' from ").concat(resolvedPath, ": ").concat(err)); + return [2 /*return*/, undefined]; + } + return [2 /*return*/, result.module]; + } + }); + }); + }; Project.prototype.isKnownTypesPackageName = function (name) { return this.typingsCache.isKnownTypesPackageName(name); }; @@ -169240,6 +171978,10 @@ var ts; return this.projectService.watchFactory.watchDirectory(directory, cb, flags, this.projectService.getWatchOptions(this), ts.WatchType.FailedLookupLocations, this); }; /*@internal*/ + Project.prototype.watchAffectingFileLocation = function (file, cb) { + return this.projectService.watchFactory.watchFile(file, cb, ts.PollingInterval.High, this.projectService.getWatchOptions(this), ts.WatchType.AffectingFileLocation, this); + }; + /*@internal*/ Project.prototype.clearInvalidateResolutionOfFailedLookupTimer = function () { return this.projectService.throttledOperations.cancel("".concat(this.getProjectName(), "FailedLookupInvalidation")); }; @@ -169350,7 +172092,7 @@ var ts; } server.updateProjectIfDirty(this); this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState, /*disableUseFileVersionAsSignature*/ true); - return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, ts.maybeBind(this.projectService.host, this.projectService.host.createHash)), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, ts.maybeBind(this.projectService.host, this.projectService.host.createHash), this.getCanonicalFileName), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; /** * Returns true if emit was conducted @@ -169774,7 +172516,7 @@ var ts; }; Project.prototype.updateGraphWorker = function () { var _this = this; - var oldProgram = this.program; + var oldProgram = this.languageService.getCurrentProgram(); ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); this.writeLog("Starting updateGraphWorker: Project: ".concat(this.getProjectName())); var start = ts.timestamp(); @@ -169783,7 +172525,7 @@ var ts; this.program = this.languageService.getProgram(); // TODO: GH#18217 this.dirty = false; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* tracing.Phase.Session */, "finishCachingPerDirectoryResolution"); - this.resolutionCache.finishCachingPerDirectoryResolution(); + this.resolutionCache.finishCachingPerDirectoryResolution(this.program, oldProgram); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); ts.Debug.assert(oldProgram === undefined || this.program !== undefined); // bump up the version if @@ -170151,7 +172893,7 @@ var ts; }; Project.prototype.enableGlobalPlugins = function (options, pluginConfigOverrides) { var host = this.projectService.host; - if (!host.require) { + if (!host.require && !host.importServicePlugin) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } @@ -170180,21 +172922,66 @@ var ts; } } }; - Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { + /** + * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin synchronously using 'require'. + */ + /*@internal*/ + Project.prototype.beginEnablePluginSync = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { var _this = this; - this.projectService.logger.info("Enabling plugin ".concat(pluginConfigEntry.name, " from candidate paths: ").concat(searchPaths.join(","))); - if (!pluginConfigEntry.name || ts.parsePackageName(pluginConfigEntry.name).rest) { - this.projectService.logger.info("Skipped loading plugin ".concat(pluginConfigEntry.name || JSON.stringify(pluginConfigEntry), " because only package name is allowed plugin name")); - return; - } - var log = function (message) { return _this.projectService.logger.info(message); }; + ts.Debug.assertIsDefined(this.projectService.host.require); var errorLogs; + var log = function (message) { return _this.projectService.logger.info(message); }; var logError = function (message) { - (errorLogs || (errorLogs = [])).push(message); + (errorLogs !== null && errorLogs !== void 0 ? errorLogs : (errorLogs = [])).push(message); }; var resolvedModule = ts.firstDefined(searchPaths, function (searchPath) { return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log, logError); }); + return { pluginConfigEntry: pluginConfigEntry, pluginConfigOverrides: pluginConfigOverrides, resolvedModule: resolvedModule, errorLogs: errorLogs }; + }; + /** + * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin asynchronously using dynamic `import`. + */ + /*@internal*/ + Project.prototype.beginEnablePluginAsync = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { + return __awaiter(this, void 0, void 0, function () { + var errorLogs, log, logError, resolvedModule, _i, searchPaths_1, searchPath; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + ts.Debug.assertIsDefined(this.projectService.host.importServicePlugin); + log = function (message) { return _this.projectService.logger.info(message); }; + logError = function (message) { + (errorLogs !== null && errorLogs !== void 0 ? errorLogs : (errorLogs = [])).push(message); + }; + _i = 0, searchPaths_1 = searchPaths; + _a.label = 1; + case 1: + if (!(_i < searchPaths_1.length)) return [3 /*break*/, 4]; + searchPath = searchPaths_1[_i]; + return [4 /*yield*/, Project.importServicePluginAsync(pluginConfigEntry.name, searchPath, this.projectService.host, log, logError)]; + case 2: + resolvedModule = (_a.sent()); + if (resolvedModule !== undefined) { + return [3 /*break*/, 4]; + } + _a.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/, { pluginConfigEntry: pluginConfigEntry, pluginConfigOverrides: pluginConfigOverrides, resolvedModule: resolvedModule, errorLogs: errorLogs }]; + } + }); + }); + }; + /** + * Performs the remaining steps of enabling a plugin after its module has been instantiated. + */ + /*@internal*/ + Project.prototype.endEnablePlugin = function (_a) { + var _this = this; + var pluginConfigEntry = _a.pluginConfigEntry, pluginConfigOverrides = _a.pluginConfigOverrides, resolvedModule = _a.resolvedModule, errorLogs = _a.errorLogs; if (resolvedModule) { var configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name); if (configurationOverride) { @@ -170206,10 +172993,13 @@ var ts; this.enableProxy(resolvedModule, pluginConfigEntry); } else { - ts.forEach(errorLogs, log); + ts.forEach(errorLogs, function (message) { return _this.projectService.logger.info(message); }); this.projectService.logger.info("Couldn't find ".concat(pluginConfigEntry.name)); } }; + Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { + this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths, pluginConfigOverrides); + }; Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) { try { if (typeof pluginModuleFactory !== "function") { @@ -170861,7 +173651,7 @@ var ts; /*@internal*/ ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) { var host = this.projectService.host; - if (!host.require) { + if (!host.require && !host.importServicePlugin) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } @@ -170880,7 +173670,7 @@ var ts; this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); } } - this.enableGlobalPlugins(options, pluginConfigOverrides); + return this.enableGlobalPlugins(options, pluginConfigOverrides); }; /** * Get the errors that dont have any file name associated @@ -172193,7 +174983,7 @@ var ts; // created when any of the script infos are added as root of inferred project if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { // If we cannot watch config file existence without configured project, close the configured file watcher - if (!ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath))) { + if (!ts.canWatchDirectoryOrFile(ts.getDirectoryPath(canonicalConfigFilePath))) { configFileExistenceInfo.watcher.close(); configFileExistenceInfo.watcher = noopConfigFileWatcher; } @@ -172273,7 +175063,7 @@ var ts; // Set this file as the root of inferred project (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = new ts.Map())).set(info.path, true); // If there is no configured project for this config file, add the file watcher - configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath)) ? + configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = ts.canWatchDirectoryOrFile(ts.getDirectoryPath(canonicalConfigFilePath)) ? _this.watchFactory.watchFile(configFileName, function (_filename, eventKind) { return _this.onConfigFileChanged(canonicalConfigFilePath, eventKind); }, ts.PollingInterval.High, _this.hostConfiguration.watchOptions, ts.WatchType.ConfigFileForInferredRoot) : noopConfigFileWatcher); }); @@ -174302,6 +177092,147 @@ var ts; } return false; }; + /*@internal*/ + ProjectService.prototype.requestEnablePlugin = function (project, pluginConfigEntry, searchPaths, pluginConfigOverrides) { + var _a; + if (!this.host.importServicePlugin && !this.host.require) { + this.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + this.logger.info("Enabling plugin ".concat(pluginConfigEntry.name, " from candidate paths: ").concat(searchPaths.join(","))); + if (!pluginConfigEntry.name || ts.parsePackageName(pluginConfigEntry.name).rest) { + this.logger.info("Skipped loading plugin ".concat(pluginConfigEntry.name || JSON.stringify(pluginConfigEntry), " because only package name is allowed plugin name")); + return; + } + // If the host supports dynamic import, begin enabling the plugin asynchronously. + if (this.host.importServicePlugin) { + var importPromise = project.beginEnablePluginAsync(pluginConfigEntry, searchPaths, pluginConfigOverrides); + (_a = this.pendingPluginEnablements) !== null && _a !== void 0 ? _a : (this.pendingPluginEnablements = new ts.Map()); + var promises = this.pendingPluginEnablements.get(project); + if (!promises) + this.pendingPluginEnablements.set(project, promises = []); + promises.push(importPromise); + return; + } + // Otherwise, load the plugin using `require` + project.endEnablePlugin(project.beginEnablePluginSync(pluginConfigEntry, searchPaths, pluginConfigOverrides)); + }; + /* @internal */ + ProjectService.prototype.hasNewPluginEnablementRequests = function () { + return !!this.pendingPluginEnablements; + }; + /* @internal */ + ProjectService.prototype.hasPendingPluginEnablements = function () { + return !!this.currentPluginEnablementPromise; + }; + /** + * Waits for any ongoing plugin enablement requests to complete. + */ + /* @internal */ + ProjectService.prototype.waitForPendingPlugins = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!this.currentPluginEnablementPromise) return [3 /*break*/, 2]; + return [4 /*yield*/, this.currentPluginEnablementPromise]; + case 1: + _a.sent(); + return [3 /*break*/, 0]; + case 2: return [2 /*return*/]; + } + }); + }); + }; + /** + * Starts enabling any requested plugins without waiting for the result. + */ + /* @internal */ + ProjectService.prototype.enableRequestedPlugins = function () { + if (this.pendingPluginEnablements) { + void this.enableRequestedPluginsAsync(); + } + }; + ProjectService.prototype.enableRequestedPluginsAsync = function () { + return __awaiter(this, void 0, void 0, function () { + var entries; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!this.currentPluginEnablementPromise) return [3 /*break*/, 2]; + // If we're already enabling plugins, wait for any existing operations to complete + return [4 /*yield*/, this.waitForPendingPlugins()]; + case 1: + // If we're already enabling plugins, wait for any existing operations to complete + _a.sent(); + _a.label = 2; + case 2: + // Skip if there are no new plugin enablement requests + if (!this.pendingPluginEnablements) { + return [2 /*return*/]; + } + entries = ts.arrayFrom(this.pendingPluginEnablements.entries()); + this.pendingPluginEnablements = undefined; + // Start processing the requests, keeping track of the promise for the operation so that + // project consumers can potentially wait for the plugins to load. + this.currentPluginEnablementPromise = this.enableRequestedPluginsWorker(entries); + return [4 /*yield*/, this.currentPluginEnablementPromise]; + case 3: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }; + ProjectService.prototype.enableRequestedPluginsWorker = function (pendingPlugins) { + return __awaiter(this, void 0, void 0, function () { + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + // This should only be called from `enableRequestedPluginsAsync`, which ensures this precondition is met. + ts.Debug.assert(this.currentPluginEnablementPromise === undefined); + // Process all pending plugins, partitioned by project. This way a project with few plugins doesn't need to wait + // on a project with many plugins. + return [4 /*yield*/, Promise.all(ts.map(pendingPlugins, function (_a) { + var project = _a[0], promises = _a[1]; + return _this.enableRequestedPluginsForProjectAsync(project, promises); + }))]; + case 1: + // Process all pending plugins, partitioned by project. This way a project with few plugins doesn't need to wait + // on a project with many plugins. + _a.sent(); + // Clear the pending operation and notify the client that projects have been updated. + this.currentPluginEnablementPromise = undefined; + this.sendProjectsUpdatedInBackgroundEvent(); + return [2 /*return*/]; + } + }); + }); + }; + ProjectService.prototype.enableRequestedPluginsForProjectAsync = function (project, promises) { + return __awaiter(this, void 0, void 0, function () { + var results, _i, results_1, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.all(promises)]; + case 1: + results = _a.sent(); + if (project.isClosed()) { + // project is not alive, so don't enable plugins. + return [2 /*return*/]; + } + for (_i = 0, results_1 = results; _i < results_1.length; _i++) { + result = results_1[_i]; + project.endEnablePlugin(result); + } + // Plugins may have modified external files, so mark the project as dirty. + this.delayUpdateProjectGraph(project); + return [2 /*return*/]; + } + }); + }); + }; ProjectService.prototype.configurePlugin = function (args) { // For any projects that already have the plugin loaded, configure the plugin this.forEachEnabledProject(function (project) { return project.onPluginConfigurationChanged(args.pluginName, args.configuration); }); @@ -174795,66 +177726,145 @@ var ts; return textSpan.start + 100003 * textSpan.length; }, ts.documentSpansEqual); } - function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments, _a) { + function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, _a) { var providePrefixAndSuffixTextForRename = _a.providePrefixAndSuffixTextForRename; - var outputs = []; + var perProjectResults = getPerProjectReferences(projects, defaultProject, initialLocation, + /*isForRename*/ true, function (project, position) { return project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, providePrefixAndSuffixTextForRename); }, function (renameLocation, cb) { return cb(documentSpanLocation(renameLocation)); }); + // No filtering or dedup'ing is required if there's exactly one project + if (ts.isArray(perProjectResults)) { + return perProjectResults; + } + var results = []; var seen = createDocumentSpanSet(); - combineProjectOutputWorker(projects, defaultProject, initialLocation, - /*isForRename*/ true, function (project, location, tryAddToTodo) { - var projectOutputs = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, providePrefixAndSuffixTextForRename); - if (projectOutputs) { - for (var _i = 0, projectOutputs_1 = projectOutputs; _i < projectOutputs_1.length; _i++) { - var output = projectOutputs_1[_i]; - if (!seen.has(output) && !tryAddToTodo(project, documentSpanLocation(output))) { - seen.add(output); - outputs.push(output); - } + perProjectResults.forEach(function (projectResults, project) { + for (var _i = 0, projectResults_1 = projectResults; _i < projectResults_1.length; _i++) { + var result = projectResults_1[_i]; + // If there's a mapped location, it'll appear in the results for another project + if (!seen.has(result) && !getMappedLocationForProject(documentSpanLocation(result), project)) { + results.push(result); + seen.add(result); } } }); - return outputs; + return results; } function getDefinitionLocation(defaultProject, initialLocation, isForRename) { - var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos, /*searchOtherFilesOnly*/ false, isForRename); + var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos, /*searchOtherFilesOnly*/ false, /*stopAtAlias*/ isForRename); var info = infos && ts.firstOrUndefined(infos); + // Note that the value of `isLocal` may depend on whether or not the checker has run on the containing file + // (implying that FAR cascading behavior may depend on request order) return info && !info.isLocal ? { fileName: info.fileName, pos: info.textSpan.start } : undefined; } - function combineProjectOutputForReferences(projects, defaultProject, initialLocation, logger) { - var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, - /*isForRename*/ false, function (project, location, getMappedLocation) { - var _a, _b; - logger.info("Finding references to ".concat(location.fileName, " position ").concat(location.pos, " in project ").concat(project.getProjectName())); - var projectOutputs = project.getLanguageService().findReferences(location.fileName, location.pos); - if (projectOutputs) { - var clearIsDefinition = ((_b = (_a = projectOutputs[0]) === null || _a === void 0 ? void 0 : _a.references[0]) === null || _b === void 0 ? void 0 : _b.isDefinition) === undefined; - var _loop_9 = function (referencedSymbol) { - var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(referencedSymbol.definition)); - var definition = mappedDefinitionFile === undefined ? - referencedSymbol.definition : __assign(__assign({}, referencedSymbol.definition), { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, referencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName, contextSpan: getMappedContextSpan(referencedSymbol.definition, project) }); - var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); - if (!symbolToAddTo) { - symbolToAddTo = { definition: definition, references: [] }; - outputs.push(symbolToAddTo); - } - for (var _c = 0, _d = referencedSymbol.references; _c < _d.length; _c++) { - var ref = _d[_c]; - // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. - if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { - if (clearIsDefinition) { - delete ref.isDefinition; - } - symbolToAddTo.references.push(ref); - } + function getReferencesWorker(projects, defaultProject, initialLocation, logger) { + var _a, _b; + var perProjectResults = getPerProjectReferences(projects, defaultProject, initialLocation, + /*isForRename*/ false, function (project, position) { + logger.info("Finding references to ".concat(position.fileName, " position ").concat(position.pos, " in project ").concat(project.getProjectName())); + return project.getLanguageService().findReferences(position.fileName, position.pos); + }, function (referencedSymbol, cb) { + cb(documentSpanLocation(referencedSymbol.definition)); + for (var _i = 0, _a = referencedSymbol.references; _i < _a.length; _i++) { + var ref = _a[_i]; + cb(documentSpanLocation(ref)); + } + }); + // No re-mapping or isDefinition updatses are required if there's exactly one project + if (ts.isArray(perProjectResults)) { + return perProjectResults; + } + // `isDefinition` is only (definitely) correct in `defaultProject` because we might + // have started the other project searches from related symbols. Propagate the + // correct results to all other projects. + var defaultProjectResults = perProjectResults.get(defaultProject); + if (((_b = (_a = defaultProjectResults === null || defaultProjectResults === void 0 ? void 0 : defaultProjectResults[0]) === null || _a === void 0 ? void 0 : _a.references[0]) === null || _b === void 0 ? void 0 : _b.isDefinition) === undefined) { + // Clear all isDefinition properties + perProjectResults.forEach(function (projectResults) { + for (var _i = 0, projectResults_2 = projectResults; _i < projectResults_2.length; _i++) { + var referencedSymbol = projectResults_2[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + delete ref.isDefinition; + } + } + }); + } + else { + // Correct isDefinition properties from projects other than defaultProject + var knownSymbolSpans_1 = createDocumentSpanSet(); + for (var _i = 0, defaultProjectResults_1 = defaultProjectResults; _i < defaultProjectResults_1.length; _i++) { + var referencedSymbol = defaultProjectResults_1[_i]; + for (var _c = 0, _d = referencedSymbol.references; _c < _d.length; _c++) { + var ref = _d[_c]; + if (ref.isDefinition) { + knownSymbolSpans_1.add(ref); + // One is enough - updateIsDefinitionOfReferencedSymbols will fill out the set based on symbols + break; } - }; - for (var _i = 0, projectOutputs_2 = projectOutputs; _i < projectOutputs_2.length; _i++) { - var referencedSymbol = projectOutputs_2[_i]; - _loop_9(referencedSymbol); } } + var updatedProjects_1 = new ts.Set(); + var _loop_9 = function () { + var progress = false; + perProjectResults.forEach(function (referencedSymbols, project) { + if (updatedProjects_1.has(project)) + return; + var updated = project.getLanguageService().updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans_1); + if (updated) { + updatedProjects_1.add(project); + progress = true; + } + }); + if (!progress) + return "break"; + }; + while (true) { + var state_2 = _loop_9(); + if (state_2 === "break") + break; + } + perProjectResults.forEach(function (referencedSymbols, project) { + if (updatedProjects_1.has(project)) + return; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + ref.isDefinition = false; + } + } + }); + } + // We need to de-duplicate and aggregate the results by choosing an authoritative version + // of each definition and merging references from all the projects where they appear. + var results = []; + var seenRefs = createDocumentSpanSet(); // It doesn't make sense to have a reference in two definition lists, so we de-dup globally + // TODO: We might end up with a more logical allocation of refs to defs if we pre-sorted the defs by descending ref-count. + // Otherwise, it just ends up attached to the first corresponding def we happen to process. The others may or may not be + // dropped later when we check for defs with ref-count 0. + perProjectResults.forEach(function (projectResults, project) { + var _loop_10 = function (referencedSymbol) { + var mappedDefinitionFile = getMappedLocationForProject(documentSpanLocation(referencedSymbol.definition), project); + var definition = mappedDefinitionFile === undefined ? + referencedSymbol.definition : __assign(__assign({}, referencedSymbol.definition), { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, referencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName, contextSpan: getMappedContextSpanForProject(referencedSymbol.definition, project) }); + var symbolToAddTo = ts.find(results, function (o) { return ts.documentSpansEqual(o.definition, definition); }); + if (!symbolToAddTo) { + symbolToAddTo = { definition: definition, references: [] }; + results.push(symbolToAddTo); + } + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + if (!seenRefs.has(ref) && !getMappedLocationForProject(documentSpanLocation(ref), project)) { + seenRefs.add(ref); + symbolToAddTo.references.push(ref); + } + } + }; + for (var _i = 0, projectResults_3 = projectResults; _i < projectResults_3.length; _i++) { + var referencedSymbol = projectResults_3[_i]; + _loop_10(referencedSymbol); + } }); - return outputs.filter(function (o) { return o.references.length !== 0; }); + return results.filter(function (o) { return o.references.length !== 0; }); } function forEachProjectInProjects(projects, path, cb) { for (var _i = 0, _a = ts.isArray(projects) ? projects : projects.projects; _i < _a.length; _i++) { @@ -174870,40 +177880,114 @@ var ts; }); } } - function combineProjectOutputWorker(projects, defaultProject, initialLocation, isForRename, cb) { - var projectService = defaultProject.projectService; - var toDo; - var seenProjects = new ts.Set(); - forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) { - // TLocation should be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. - var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined); - toDo = callbackProjectAndLocation(project, location, projectService, toDo, seenProjects, cb); + /** + * @param projects Projects initially known to contain {@link initialLocation} + * @param defaultProject The default project containing {@link initialLocation} + * @param initialLocation Where the search operation was triggered + * @param getResultsForPosition This is where you plug in `findReferences`, `renameLocation`, etc + * @param forPositionInResult Given an item returned by {@link getResultsForPosition} enumerate the positions referred to by that result + * @returns In the common case where there's only one project, returns an array of results from {@link getResultsForPosition}. + * If multiple projects were searched - even if they didn't return results - the result will be a map from project to per-project results. + */ + function getPerProjectReferences(projects, defaultProject, initialLocation, isForRename, getResultsForPosition, forPositionInResult) { + // If `getResultsForPosition` returns results for a project, they go in here + var resultsMap = new ts.Map(); + var queue = ts.createQueue(); + // In order to get accurate isDefinition values for `defaultProject`, + // we need to ensure that it is searched from `initialLocation`. + // The easiest way to do this is to search it first. + queue.enqueue({ project: defaultProject, location: initialLocation }); + // This will queue `defaultProject` a second time, but it will be dropped + // as a dup when it is dequeued. + forEachProjectInProjects(projects, initialLocation.fileName, function (project, path) { + var location = { fileName: path, pos: initialLocation.pos }; + queue.enqueue({ project: project, location: location }); }); - // After initial references are collected, go over every other project and see if it has a reference for the symbol definition. - if (initialLocation) { - var defaultDefinition_1 = getDefinitionLocation(defaultProject, initialLocation, isForRename); - if (defaultDefinition_1) { - var getGeneratedDefinition_1 = ts.memoize(function () { return defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition_1.fileName) ? - defaultDefinition_1 : - defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition_1); }); - var getSourceDefinition_1 = ts.memoize(function () { return defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition_1.fileName) ? - defaultDefinition_1 : - defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition_1); }); - projectService.loadAncestorProjectTree(seenProjects); + var projectService = defaultProject.projectService; + var cancellationToken = defaultProject.getCancellationToken(); + var defaultDefinition = getDefinitionLocation(defaultProject, initialLocation, isForRename); + // Don't call these unless !!defaultDefinition + var getGeneratedDefinition = ts.memoize(function () { return defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? + defaultDefinition : + defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition); }); + var getSourceDefinition = ts.memoize(function () { return defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? + defaultDefinition : + defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition); }); + // The keys of resultsMap allow us to check which projects have already been searched, but we also + // maintain a set of strings because that's what `loadAncestorProjectTree` wants. + var searchedProjectKeys = new ts.Set(); + onCancellation: while (!queue.isEmpty()) { + while (!queue.isEmpty()) { + if (cancellationToken.isCancellationRequested()) + break onCancellation; + var _a = queue.dequeue(), project = _a.project, location = _a.location; + if (resultsMap.has(project)) + continue; + if (isLocationProjectReferenceRedirect(project, location)) + continue; + var projectResults = searchPosition(project, location); + resultsMap.set(project, projectResults !== null && projectResults !== void 0 ? projectResults : server.emptyArray); + searchedProjectKeys.add(getProjectKey(project)); + } + // At this point, we know about all projects passed in as arguments and any projects in which + // `getResultsForPosition` has returned results. We expand that set to include any projects + // downstream from any of these and then queue new initial-position searches for any new project + // containing `initialLocation`. + if (defaultDefinition) { + // This seems to mean "load all projects downstream from any member of `seenProjects`". + projectService.loadAncestorProjectTree(searchedProjectKeys); projectService.forEachEnabledProject(function (project) { - if (!addToSeen(seenProjects, project)) - return; - var definition = mapDefinitionInProject(defaultDefinition_1, project, getGeneratedDefinition_1, getSourceDefinition_1); - if (definition) { - toDo = callbackProjectAndLocation(project, definition, projectService, toDo, seenProjects, cb); + if (cancellationToken.isCancellationRequested()) + return; // There's no mechanism for skipping the remaining projects + if (resultsMap.has(project)) + return; // Can loop forever without this (enqueue here, dequeue above, repeat) + var location = mapDefinitionInProject(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition); + if (location) { + queue.enqueue({ project: project, location: location }); } }); } } - while (toDo && toDo.length) { - var next = toDo.pop(); - ts.Debug.assertIsDefined(next); - toDo = callbackProjectAndLocation(next.project, next.location, projectService, toDo, seenProjects, cb); + // In the common case where there's only one project, return a simpler result to make + // it easier for the caller to skip post-processing. + if (resultsMap.size === 1) { + var it = resultsMap.values().next(); + ts.Debug.assert(!it.done); + return it.value; + } + return resultsMap; + function searchPosition(project, location) { + var projectResults = getResultsForPosition(project, location); + if (!projectResults) + return undefined; + for (var _i = 0, projectResults_4 = projectResults; _i < projectResults_4.length; _i++) { + var result = projectResults_4[_i]; + forPositionInResult(result, function (position) { + // This may trigger a search for a tsconfig, but there are several layers of caching that make it inexpensive + var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, position); + if (!originalLocation) + return; + var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); + for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { + var project_1 = _a[_i]; + if (!project_1.isOrphan() && !resultsMap.has(project_1)) { // Optimization: don't enqueue if will be discarded + queue.enqueue({ project: project_1, location: originalLocation }); + } + } + var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); + if (symlinkedProjectsMap) { + symlinkedProjectsMap.forEach(function (symlinkedProjects, symlinkedPath) { + for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) { + var symlinkedProject = symlinkedProjects_2[_i]; + if (!symlinkedProject.isOrphan() && !resultsMap.has(symlinkedProject)) { // Optimization: don't enqueue if will be discarded + queue.enqueue({ project: symlinkedProject, location: { fileName: symlinkedPath, pos: originalLocation.pos } }); + } + } + }); + } + }); + } + return projectResults; } } function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) { @@ -174934,43 +178018,6 @@ var ts; sourceFile.resolvedPath !== sourceFile.path && sourceFile.resolvedPath !== project.toPath(location.fileName); } - function callbackProjectAndLocation(project, location, projectService, toDo, seenProjects, cb) { - if (project.getCancellationToken().isCancellationRequested()) - return undefined; // Skip rest of toDo if cancelled - // If this is not the file we were actually looking, return rest of the toDo - if (isLocationProjectReferenceRedirect(project, location)) - return toDo; - cb(project, location, function (innerProject, location) { - addToSeen(seenProjects, project); - var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(innerProject, location); - if (!originalLocation) - return undefined; - var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); - toDo = toDo || []; - for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { - var project_1 = _a[_i]; - addToTodo(project_1, originalLocation, toDo, seenProjects); - } - var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); - if (symlinkedProjectsMap) { - symlinkedProjectsMap.forEach(function (symlinkedProjects, symlinkedPath) { - for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) { - var symlinkedProject = symlinkedProjects_2[_i]; - addToTodo(symlinkedProject, { fileName: symlinkedPath, pos: originalLocation.pos }, toDo, seenProjects); - } - }); - } - return originalLocation === location ? undefined : originalLocation; - }); - return toDo; - } - function addToTodo(project, location, toDo, seenProjects) { - if (!project.isOrphan() && addToSeen(seenProjects, project)) - toDo.push({ project: project, location: location }); - } - function addToSeen(seenProjects, project) { - return ts.tryAddToSet(seenProjects, getProjectKey(project)); - } function getProjectKey(project) { return server.isConfiguredProject(project) ? project.canonicalConfigFilePath : project.getProjectName(); } @@ -174978,32 +178025,14 @@ var ts; var fileName = _a.fileName, textSpan = _a.textSpan; return { fileName: fileName, pos: textSpan.start }; } - function getMappedLocation(location, project) { - var mapsTo = project.getSourceMapper().tryGetSourcePosition(location); - return mapsTo && project.projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined; + function getMappedLocationForProject(location, project) { + return ts.getMappedLocation(location, project.getSourceMapper(), function (p) { return project.projectService.fileExists(p); }); } - function getMappedDocumentSpan(documentSpan, project) { - var newPosition = getMappedLocation(documentSpanLocation(documentSpan), project); - if (!newPosition) - return undefined; - return { - fileName: newPosition.fileName, - textSpan: { - start: newPosition.pos, - length: documentSpan.textSpan.length - }, - originalFileName: documentSpan.fileName, - originalTextSpan: documentSpan.textSpan, - contextSpan: getMappedContextSpan(documentSpan, project), - originalContextSpan: documentSpan.contextSpan - }; + function getMappedDocumentSpanForProject(documentSpan, project) { + return ts.getMappedDocumentSpan(documentSpan, project.getSourceMapper(), function (p) { return project.projectService.fileExists(p); }); } - function getMappedContextSpan(documentSpan, project) { - var contextSpanStart = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, project); - var contextSpanEnd = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length }, project); - return contextSpanStart && contextSpanEnd ? - { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : - undefined; + function getMappedContextSpanForProject(documentSpan, project) { + return ts.getMappedContextSpan(documentSpan, project.getSourceMapper(), function (p) { return project.projectService.fileExists(p); }); } var invalidPartialSemanticModeCommands = [ server.CommandNames.OpenExternalProject, @@ -175033,7 +178062,6 @@ var ts; server.CommandNames.OrganizeImportsFull, server.CommandNames.GetEditsForFileRename, server.CommandNames.GetEditsForFileRenameFull, - server.CommandNames.ConfigurePlugin, server.CommandNames.PrepareCallHierarchy, server.CommandNames.ProvideCallHierarchyIncomingCalls, server.CommandNames.ProvideCallHierarchyOutgoingCalls, @@ -175896,7 +178924,7 @@ var ts; }; Session.prototype.mapDefinitionInfoLocations = function (definitions, project) { return definitions.map(function (info) { - var newDocumentSpan = getMappedDocumentSpan(info, project); + var newDocumentSpan = getMappedDocumentSpanForProject(info, project); return !newDocumentSpan ? info : __assign(__assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name, failedAliasResolution: info.failedAliasResolution }), info.unverified && { unverified: info.unverified }); }); }; @@ -175982,7 +179010,7 @@ var ts; var packageDirectory = fileName.substring(0, nodeModulesPathParts.packageRootIndex); var packageJsonCache = (_a = project.getModuleResolutionCache()) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfoCache(); var compilerOptions = project.getCompilationSettings(); - var packageJson = ts.getPackageScopeForPath(project.toPath(packageDirectory + "/package.json"), packageJsonCache, project, compilerOptions); + var packageJson = ts.getPackageScopeForPath(project.toPath(packageDirectory + "/package.json"), ts.getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions)); if (!packageJson) return undefined; // Use fake options instead of actual compiler options to avoid following export map if the project uses node16 or nodenext - @@ -176141,7 +179169,7 @@ var ts; }; Session.prototype.mapImplementationLocations = function (implementations, project) { return implementations.map(function (info) { - var newDocumentSpan = getMappedDocumentSpan(info, project); + var newDocumentSpan = getMappedDocumentSpanForProject(info, project); return !newDocumentSpan ? info : __assign(__assign({}, newDocumentSpan), { kind: info.kind, displayParts: info.displayParts }); }); }; @@ -176244,7 +179272,8 @@ var ts; Session.prototype.getRenameInfo = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }); + var preferences = this.getPreferences(file); + return project.getLanguageService().getRenameInfo(file, position, preferences); }; Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { var _a; @@ -176295,10 +179324,11 @@ var ts; var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); var defaultProject = this.getDefaultProject(args); - var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), ts.Debug.checkDefined(this.projectService.getScriptInfo(file))); + var preferences = this.getPreferences(file); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, preferences), ts.Debug.checkDefined(this.projectService.getScriptInfo(file))); if (!renameInfo.canRename) return simplifiedResult ? { info: renameInfo, locs: [] } : []; - var locations = combineProjectOutputForRenameLocations(projects, defaultProject, { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getPreferences(file)); + var locations = getRenameLocationsWorker(projects, defaultProject, { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, preferences); if (!simplifiedResult) return locations; return { info: renameInfo, locs: this.toSpanGroups(locations) }; @@ -176330,7 +179360,7 @@ var ts; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); var position = this.getPositionInFile(args, file); - var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, this.logger); + var references = getReferencesWorker(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, this.logger); if (!simplifiedResult) return references; var defaultProject = this.getDefaultProject(args); @@ -176356,8 +179386,8 @@ var ts; return; var projectOutputs = project.getLanguageService().getFileReferences(fileName); if (projectOutputs) { - for (var _i = 0, projectOutputs_3 = projectOutputs; _i < projectOutputs_3.length; _i++) { - var referenceEntry = projectOutputs_3[_i]; + for (var _i = 0, projectOutputs_1 = projectOutputs; _i < projectOutputs_1.length; _i++) { + var referenceEntry = projectOutputs_1[_i]; if (!seen.has(referenceEntry)) { references.push(referenceEntry); seen.add(referenceEntry); @@ -176822,7 +179852,8 @@ var ts; // `name` is a very cheap hash function, but we could incorporate other properties to reduce collisions. var seenItems = new ts.Map(); // name to items with that name if (!args.file && !projectFileName) { - // VS Code's `Go to symbol in workspaces` sends request like this + // VS Code's `Go to symbol in workspaces` sends request like this by default. + // There's a setting to have it send a file name (reverting to older behavior). // TODO (https://github.com/microsoft/TypeScript/issues/47839) // This appears to have been intended to search all projects but, in practice, it seems to only search // those that are downstream from already-loaded projects. @@ -176843,7 +179874,7 @@ var ts; // Mutates `outputs` function addItemsForProject(project) { var projectItems = project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*filename*/ undefined, /*excludeDts*/ project.isNonTsProject()); - var unseenItems = ts.filter(projectItems, function (item) { return tryAddSeenItem(item) && !getMappedLocation(documentSpanLocation(item), project); }); + var unseenItems = ts.filter(projectItems, function (item) { return tryAddSeenItem(item) && !getMappedLocationForProject(documentSpanLocation(item), project); }); if (unseenItems.length) { outputs.push({ project: project, navigateToItems: unseenItems }); } @@ -177300,7 +180331,9 @@ var ts; Session.prototype.executeCommand = function (request) { var handler = this.handlers.get(request.command); if (handler) { - return this.executeWithRequestId(request.seq, function () { return handler(request); }); + var response = this.executeWithRequestId(request.seq, function () { return handler(request); }); + this.projectService.enableRequestedPlugins(); + return response; } else { this.logger.msg("Unrecognized JSON command:".concat(server.stringifyIndented(request)), server.Msg.Err); @@ -178213,23 +181246,80 @@ var ts; }()); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +// The following are deprecations for the public API. Deprecated exports are removed from the compiler itself +// and compatible implementations are added here, along with an appropriate deprecation warning using +// the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. +// +// Deprecations fall into one of three categories: +// +// - "soft" - Soft deprecations are indicated with the `@deprecated` JSDoc Tag. +// - "warn" - Warning deprecations are indicated with the `@deprecated` JSDoc Tag and a diagnostic message (assuming a compatible host). +// - "error" - Error deprecations are either indicated with the `@deprecated` JSDoc tag and will throw a `TypeError` when invoked, or removed from the API entirely. +// +// Once we have determined enough time has passed after a deprecation has been marked as `"warn"` or `"error"`, it will be removed from the public API. +/* @internal */ +var ts; +(function (ts) { + function createOverload(name, overloads, binder, deprecations) { + Object.defineProperty(call, "name", __assign(__assign({}, Object.getOwnPropertyDescriptor(call, "name")), { value: name })); + if (deprecations) { + for (var _i = 0, _a = Object.keys(deprecations); _i < _a.length; _i++) { + var key = _a[_i]; + var index = +key; + if (!isNaN(index) && ts.hasProperty(overloads, "".concat(index))) { + overloads[index] = ts.Debug.deprecate(overloads[index], __assign(__assign({}, deprecations[index]), { name: name })); + } + } + } + var bind = createBinder(overloads, binder); + return call; + function call() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var index = bind(args); + var fn = index !== undefined ? overloads[index] : undefined; + if (typeof fn === "function") { + return fn.apply(void 0, args); + } + throw new TypeError("Invalid arguments"); + } + } + ts.createOverload = createOverload; + function createBinder(overloads, binder) { + return function (args) { + for (var i = 0; ts.hasProperty(overloads, "".concat(i)) && ts.hasProperty(binder, "".concat(i)); i++) { + var fn = binder[i]; + if (fn(args)) { + return i; + } + } + }; + } + // NOTE: We only use this "builder" because we don't infer correctly when calling `createOverload` directly in < TS 4.7, + // but lib is currently at TS 4.4. We can switch to directly calling `createOverload` when we update LKG in main. + function buildOverload(name) { + return { + overload: function (overloads) { return ({ + bind: function (binder) { return ({ + finish: function () { return createOverload(name, overloads, binder); }, + deprecate: function (deprecations) { return ({ + finish: function () { return createOverload(name, overloads, binder, deprecations); } + }); } + }); } + }); } + }; + } + ts.buildOverload = buildOverload; +})(ts || (ts = {})); +// DEPRECATION: Node factory top-level exports +// DEPRECATION PLAN: +// - soft: 4.0 +// - warn: 4.1 +// - error: 5.0 var ts; (function (ts) { - // The following are deprecations for the public API. Deprecated exports are removed from the compiler itself - // and compatible implementations are added here, along with an appropriate deprecation warning using - // the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. - // - // Deprecations fall into one of three categories: - // - // * "soft" - Soft deprecations are indicated with the `@deprecated` JSDoc Tag. - // * "warn" - Warning deprecations are indicated with the `@deprecated` JSDoc Tag and a diagnostic message (assuming a compatible host) - // * "error" - Error deprecations are indicated with the `@deprecated` JSDoc tag and will throw a `TypeError` when invoked. - // DEPRECATION: Node factory top-level exports - // DEPRECATION PLAN: - // - soft: 4.0 - // - warn: 4.1 - // - error: TBD - // #region Node factory top-level exports // NOTE: These exports are deprecated in favor of using a `NodeFactory` instance and exist here purely for backwards compatibility reasons. var factoryDeprecation = { since: "4.0", warnAfter: "4.1", message: "Use the appropriate method on 'ts.factory' or the 'factory' supplied by your transformation context instead." }; /** @deprecated Use `factory.createNodeArray` or the factory supplied by your transformation context instead. */ @@ -179099,13 +182189,14 @@ var ts; ts.setParent(clone, node.parent); return clone; }, { since: "4.0", warnAfter: "4.1", message: "Use an appropriate `factory.update...` method instead, use `setCommentRange` or `setSourceMapRange`, and avoid setting `parent`." }); - // #endregion Node Factory top-level exports - // DEPRECATION: Renamed node tests - // DEPRECATION PLAN: - // - soft: 4.0 - // - warn: 4.1 - // - error: TBD - // #region Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Renamed node tests +// DEPRECATION PLAN: +// - soft: 4.0 +// - warn: 4.1 +// - error: TBD +var ts; +(function (ts) { /** @deprecated Use `isTypeAssertionExpression` instead. */ ts.isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node) { return node.kind === 211 /* SyntaxKind.TypeAssertionExpression */; @@ -179114,13 +182205,14 @@ var ts; warnAfter: "4.1", message: "Use `isTypeAssertionExpression` instead." }); - // #endregion - // DEPRECATION: Renamed node tests - // DEPRECATION PLAN: - // - soft: 4.2 - // - warn: 4.3 - // - error: TBD - // #region Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Renamed node tests +// DEPRECATION PLAN: +// - soft: 4.2 +// - warn: 4.3 +// - error: 5.0 +var ts; +(function (ts) { /** * @deprecated Use `isMemberName` instead. */ @@ -179131,7 +182223,1406 @@ var ts; warnAfter: "4.3", message: "Use `isMemberName` instead." }); - // #endregion Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Overloads for createConstructorTypeNode/updateConstructorTypeNode that do not accept 'modifiers' +// DEPRECATION PLAN: +// - soft: 4.2 +// - warn: 4.3 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createConstructorTypeNode = factory.createConstructorTypeNode, updateConstructorTypeNode = factory.updateConstructorTypeNode; + factory.createConstructorTypeNode = ts.buildOverload("createConstructorTypeNode") + .overload({ + 0: function (modifiers, typeParameters, parameters, type) { + return createConstructorTypeNode(modifiers, typeParameters, parameters, type); + }, + 1: function (typeParameters, parameters, type) { + return createConstructorTypeNode(/*modifiers*/ undefined, typeParameters, parameters, type); + }, + }) + .bind({ + 0: function (args) { return args.length === 4; }, + 1: function (args) { return args.length === 3; }, + }) + .deprecate({ + 1: { since: "4.2", warnAfter: "4.3", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + factory.updateConstructorTypeNode = ts.buildOverload("updateConstructorTypeNode") + .overload({ + 0: function (node, modifiers, typeParameters, parameters, type) { + return updateConstructorTypeNode(node, modifiers, typeParameters, parameters, type); + }, + 1: function (node, typeParameters, parameters, type) { + return updateConstructorTypeNode(node, node.modifiers, typeParameters, parameters, type); + } + }) + .bind({ + 0: function (args) { return args.length === 5; }, + 1: function (args) { return args.length === 4; }, + }) + .deprecate({ + 1: { since: "4.2", warnAfter: "4.3", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Overloads to createImportTypeNode/updateImportTypeNode that do not accept `assertions` +// DEPRECATION PLAN: +// - soft: 4.6 +// - warn: 4.7 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createImportTypeNode = factory.createImportTypeNode, updateImportTypeNode = factory.updateImportTypeNode; + factory.createImportTypeNode = ts.buildOverload("createImportTypeNode") + .overload({ + 0: function (argument, assertions, qualifier, typeArguments, isTypeOf) { + return createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf); + }, + 1: function (argument, qualifier, typeArguments, isTypeOf) { + return createImportTypeNode(argument, /*assertions*/ undefined, qualifier, typeArguments, isTypeOf); + }, + }) + .bind({ + 0: function (_a) { + var assertions = _a[1], qualifier = _a[2], typeArguments = _a[3], isTypeOf = _a[4]; + return (assertions === undefined || ts.isImportTypeAssertionContainer(assertions)) && + (qualifier === undefined || !ts.isArray(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + 1: function (_a) { + var qualifier = _a[1], typeArguments = _a[2], isTypeOf = _a[3], other = _a[4]; + return (other === undefined) && + (qualifier === undefined || ts.isEntityName(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + }) + .deprecate({ + 1: { since: "4.6", warnAfter: "4.7", message: "Use the overload that accepts 'assertions'" } + }) + .finish(); + factory.updateImportTypeNode = ts.buildOverload("updateImportTypeNode") + .overload({ + 0: function (node, argument, assertions, qualifier, typeArguments, isTypeOf) { + return updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf); + }, + 1: function (node, argument, qualifier, typeArguments, isTypeOf) { + return updateImportTypeNode(node, argument, node.assertions, qualifier, typeArguments, isTypeOf); + }, + }) + .bind({ + 0: function (_a) { + var assertions = _a[2], qualifier = _a[3], typeArguments = _a[4], isTypeOf = _a[5]; + return (assertions === undefined || ts.isImportTypeAssertionContainer(assertions)) && + (qualifier === undefined || !ts.isArray(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + 1: function (_a) { + var qualifier = _a[2], typeArguments = _a[3], isTypeOf = _a[4], other = _a[5]; + return (other === undefined) && + (qualifier === undefined || ts.isEntityName(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + }). + deprecate({ + 1: { since: "4.6", warnAfter: "4.7", message: "Use the overload that accepts 'assertions'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Overloads to createTypeParameter/updateTypeParameter that does not accept `modifiers` +// DEPRECATION PLAN: +// - soft: 4.7 +// - warn: 4.8 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createTypeParameterDeclaration = factory.createTypeParameterDeclaration, updateTypeParameterDeclaration = factory.updateTypeParameterDeclaration; + factory.createTypeParameterDeclaration = ts.buildOverload("createTypeParameterDeclaration") + .overload({ + 0: function (modifiers, name, constraint, defaultType) { + return createTypeParameterDeclaration(modifiers, name, constraint, defaultType); + }, + 1: function (name, constraint, defaultType) { + return createTypeParameterDeclaration(/*modifiers*/ undefined, name, constraint, defaultType); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0]; + return (modifiers === undefined || ts.isArray(modifiers)); + }, + 1: function (_a) { + var name = _a[0]; + return (name !== undefined && !ts.isArray(name)); + }, + }) + .deprecate({ + 1: { since: "4.7", warnAfter: "4.8", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + factory.updateTypeParameterDeclaration = ts.buildOverload("updateTypeParameterDeclaration") + .overload({ + 0: function (node, modifiers, name, constraint, defaultType) { + return updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType); + }, + 1: function (node, name, constraint, defaultType) { + return updateTypeParameterDeclaration(node, node.modifiers, name, constraint, defaultType); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1]; + return (modifiers === undefined || ts.isArray(modifiers)); + }, + 1: function (_a) { + var name = _a[1]; + return (name !== undefined && !ts.isArray(name)); + }, + }) + .deprecate({ + 1: { since: "4.7", warnAfter: "4.8", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Deprecate passing `decorators` separate from `modifiers` +// DEPRECATION PLAN: +// - soft: 4.8 +// - warn: 4.9 +// - error: 5.0 +var ts; +(function (ts) { + var MUST_MERGE = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators have been combined with modifiers. Callers should switch to an overload that does not accept a 'decorators' parameter." }; + var DISALLOW_DECORATORS = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators are no longer supported for this function. Callers should switch to an overload that does not accept a 'decorators' parameter." }; + var DISALLOW_DECORATORS_AND_MODIFIERS = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators and modifiers are no longer supported for this function. Callers should switch to an overload that does not accept the 'decorators' and 'modifiers' parameters." }; + function patchNodeFactory(factory) { + var createParameterDeclaration = factory.createParameterDeclaration, updateParameterDeclaration = factory.updateParameterDeclaration, createPropertyDeclaration = factory.createPropertyDeclaration, updatePropertyDeclaration = factory.updatePropertyDeclaration, createMethodDeclaration = factory.createMethodDeclaration, updateMethodDeclaration = factory.updateMethodDeclaration, createConstructorDeclaration = factory.createConstructorDeclaration, updateConstructorDeclaration = factory.updateConstructorDeclaration, createGetAccessorDeclaration = factory.createGetAccessorDeclaration, updateGetAccessorDeclaration = factory.updateGetAccessorDeclaration, createSetAccessorDeclaration = factory.createSetAccessorDeclaration, updateSetAccessorDeclaration = factory.updateSetAccessorDeclaration, createIndexSignature = factory.createIndexSignature, updateIndexSignature = factory.updateIndexSignature, createClassStaticBlockDeclaration = factory.createClassStaticBlockDeclaration, updateClassStaticBlockDeclaration = factory.updateClassStaticBlockDeclaration, createClassExpression = factory.createClassExpression, updateClassExpression = factory.updateClassExpression, createFunctionDeclaration = factory.createFunctionDeclaration, updateFunctionDeclaration = factory.updateFunctionDeclaration, createClassDeclaration = factory.createClassDeclaration, updateClassDeclaration = factory.updateClassDeclaration, createInterfaceDeclaration = factory.createInterfaceDeclaration, updateInterfaceDeclaration = factory.updateInterfaceDeclaration, createTypeAliasDeclaration = factory.createTypeAliasDeclaration, updateTypeAliasDeclaration = factory.updateTypeAliasDeclaration, createEnumDeclaration = factory.createEnumDeclaration, updateEnumDeclaration = factory.updateEnumDeclaration, createModuleDeclaration = factory.createModuleDeclaration, updateModuleDeclaration = factory.updateModuleDeclaration, createImportEqualsDeclaration = factory.createImportEqualsDeclaration, updateImportEqualsDeclaration = factory.updateImportEqualsDeclaration, createImportDeclaration = factory.createImportDeclaration, updateImportDeclaration = factory.updateImportDeclaration, createExportAssignment = factory.createExportAssignment, updateExportAssignment = factory.updateExportAssignment, createExportDeclaration = factory.createExportDeclaration, updateExportDeclaration = factory.updateExportDeclaration; + factory.createParameterDeclaration = ts.buildOverload("createParameterDeclaration") + .overload({ + 0: function (modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer); + }, + 1: function (decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return createParameterDeclaration(ts.concatenate(decorators, modifiers), dotDotDotToken, name, questionToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var dotDotDotToken = _a[1], name = _a[2], questionToken = _a[3], type = _a[4], initializer = _a[5], other = _a[6]; + return (other === undefined) && + (dotDotDotToken === undefined || !ts.isArray(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[1], dotDotDotToken = _a[2], name = _a[3], questionToken = _a[4], type = _a[5], initializer = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (dotDotDotToken === undefined || typeof dotDotDotToken === "object" && ts.isDotDotDotToken(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateParameterDeclaration = ts.buildOverload("updateParameterDeclaration") + .overload({ + 0: function (node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer); + }, + 1: function (node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return updateParameterDeclaration(node, ts.concatenate(decorators, modifiers), dotDotDotToken, name, questionToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var dotDotDotToken = _a[2], name = _a[3], questionToken = _a[4], type = _a[5], initializer = _a[6], other = _a[7]; + return (other === undefined) && + (dotDotDotToken === undefined || !ts.isArray(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[2], dotDotDotToken = _a[3], name = _a[4], questionToken = _a[5], type = _a[6], initializer = _a[7]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (dotDotDotToken === undefined || typeof dotDotDotToken === "object" && ts.isDotDotDotToken(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createPropertyDeclaration = ts.buildOverload("createPropertyDeclaration") + .overload({ + 0: function (modifiers, name, questionOrExclamationToken, type, initializer) { + return createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer); + }, + 1: function (decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return createPropertyDeclaration(ts.concatenate(decorators, modifiers), name, questionOrExclamationToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], questionOrExclamationToken = _a[2], type = _a[3], initializer = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (questionOrExclamationToken === undefined || typeof questionOrExclamationToken === "object" && ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], questionOrExclamationToken = _a[3], type = _a[4], initializer = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionOrExclamationToken === undefined || ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updatePropertyDeclaration = ts.buildOverload("updatePropertyDeclaration") + .overload({ + 0: function (node, modifiers, name, questionOrExclamationToken, type, initializer) { + return updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer); + }, + 1: function (node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return updatePropertyDeclaration(node, ts.concatenate(decorators, modifiers), name, questionOrExclamationToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], questionOrExclamationToken = _a[3], type = _a[4], initializer = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (questionOrExclamationToken === undefined || typeof questionOrExclamationToken === "object" && ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], questionOrExclamationToken = _a[4], type = _a[5], initializer = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionOrExclamationToken === undefined || ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createMethodDeclaration = ts.buildOverload("createMethodDeclaration") + .overload({ + 0: function (modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + 1: function (decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return createMethodDeclaration(ts.concatenate(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[1], name = _a[2], questionToken = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7], other = _a[8]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || !ts.some(parameters, ts.isTypeParameterDeclaration)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], asteriskToken = _a[2], name = _a[3], questionToken = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken === "object" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || !ts.isArray(questionToken)) && + (typeParameters === undefined || !ts.some(typeParameters, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateMethodDeclaration = ts.buildOverload("updateMethodDeclaration") + .overload({ + 0: function (node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + 1: function (node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return updateMethodDeclaration(node, ts.concatenate(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[2], name = _a[3], questionToken = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8], other = _a[9]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || !ts.some(parameters, ts.isTypeParameterDeclaration)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], asteriskToken = _a[3], name = _a[4], questionToken = _a[5], typeParameters = _a[6], parameters = _a[7], type = _a[8], body = _a[9]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken === "object" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || !ts.isArray(questionToken)) && + (typeParameters === undefined || !ts.some(typeParameters, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createConstructorDeclaration = ts.buildOverload("createConstructorDeclaration") + .overload({ + 0: function (modifiers, parameters, body) { + return createConstructorDeclaration(modifiers, parameters, body); + }, + 1: function (_decorators, modifiers, parameters, body) { + return createConstructorDeclaration(modifiers, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], parameters = _a[1], body = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || !ts.some(modifiers, ts.isDecorator)) && + (parameters === undefined || !ts.some(parameters, ts.isModifier)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], parameters = _a[2], body = _a[3]; + return (decorators === undefined || !ts.some(decorators, ts.isModifier)) && + (modifiers === undefined || !ts.some(modifiers, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateConstructorDeclaration = ts.buildOverload("updateConstructorDeclaration") + .overload({ + 0: function (node, modifiers, parameters, body) { + return updateConstructorDeclaration(node, modifiers, parameters, body); + }, + 1: function (node, _decorators, modifiers, parameters, body) { + return updateConstructorDeclaration(node, modifiers, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], parameters = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || !ts.some(modifiers, ts.isDecorator)) && + (parameters === undefined || !ts.some(parameters, ts.isModifier)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], parameters = _a[3], body = _a[4]; + return (decorators === undefined || !ts.some(decorators, ts.isModifier)) && + (modifiers === undefined || !ts.some(modifiers, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createGetAccessorDeclaration = ts.buildOverload("createGetAccessorDeclaration") + .overload({ + 0: function (modifiers, name, parameters, type, body) { + return createGetAccessorDeclaration(modifiers, name, parameters, type, body); + }, + 1: function (decorators, modifiers, name, parameters, type, body) { + return createGetAccessorDeclaration(ts.concatenate(decorators, modifiers), name, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], parameters = _a[2], type = _a[3], body = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], parameters = _a[3], type = _a[4], body = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateGetAccessorDeclaration = ts.buildOverload("updateGetAccessorDeclaration") + .overload({ + 0: function (node, modifiers, name, parameters, type, body) { + return updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body); + }, + 1: function (node, decorators, modifiers, name, parameters, type, body) { + return updateGetAccessorDeclaration(node, ts.concatenate(decorators, modifiers), name, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], parameters = _a[3], type = _a[4], body = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], parameters = _a[4], type = _a[5], body = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createSetAccessorDeclaration = ts.buildOverload("createSetAccessorDeclaration") + .overload({ + 0: function (modifiers, name, parameters, body) { + return createSetAccessorDeclaration(modifiers, name, parameters, body); + }, + 1: function (decorators, modifiers, name, parameters, body) { + return createSetAccessorDeclaration(ts.concatenate(decorators, modifiers), name, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], parameters = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], parameters = _a[3], body = _a[4]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateSetAccessorDeclaration = ts.buildOverload("updateSetAccessorDeclaration") + .overload({ + 0: function (node, modifiers, name, parameters, body) { + return updateSetAccessorDeclaration(node, modifiers, name, parameters, body); + }, + 1: function (node, decorators, modifiers, name, parameters, body) { + return updateSetAccessorDeclaration(node, ts.concatenate(decorators, modifiers), name, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], parameters = _a[3], body = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], parameters = _a[4], body = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createIndexSignature = ts.buildOverload("createIndexSignature") + .overload({ + 0: function (modifiers, parameters, type) { + return createIndexSignature(modifiers, parameters, type); + }, + 1: function (_decorators, modifiers, parameters, type) { + return createIndexSignature(modifiers, parameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], parameters = _a[1], type = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], parameters = _a[2], type = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateIndexSignature = ts.buildOverload("updateIndexSignature") + .overload({ + 0: function (node, modifiers, parameters, type) { + return updateIndexSignature(node, modifiers, parameters, type); + }, + 1: function (node, _decorators, modifiers, parameters, type) { + return updateIndexSignature(node, modifiers, parameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], parameters = _a[2], type = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], parameters = _a[3], type = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createClassStaticBlockDeclaration = ts.buildOverload("createClassStaticBlockDeclaration") + .overload({ + 0: function (body) { + return createClassStaticBlockDeclaration(body); + }, + 1: function (_decorators, _modifiers, body) { + return createClassStaticBlockDeclaration(body); + }, + }) + .bind({ + 0: function (_a) { + var body = _a[0], other1 = _a[1], other2 = _a[2]; + return (other1 === undefined) && + (other2 === undefined) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], body = _a[2]; + return (decorators === undefined || ts.isArray(decorators)) && + (modifiers === undefined || ts.isArray(decorators)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS_AND_MODIFIERS + }) + .finish(); + factory.updateClassStaticBlockDeclaration = ts.buildOverload("updateClassStaticBlockDeclaration") + .overload({ + 0: function (node, body) { + return updateClassStaticBlockDeclaration(node, body); + }, + 1: function (node, _decorators, _modifiers, body) { + return updateClassStaticBlockDeclaration(node, body); + }, + }) + .bind({ + 0: function (_a) { + var body = _a[1], other1 = _a[2], other2 = _a[3]; + return (other1 === undefined) && + (other2 === undefined) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], body = _a[3]; + return (decorators === undefined || ts.isArray(decorators)) && + (modifiers === undefined || ts.isArray(decorators)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS_AND_MODIFIERS + }) + .finish(); + factory.createClassExpression = ts.buildOverload("createClassExpression") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createClassExpression(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createClassExpression(ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateClassExpression = ts.buildOverload("updateClassExpression") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassExpression(node, ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createFunctionDeclaration = ts.buildOverload("createFunctionDeclaration") + .overload({ + 0: function (modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + 1: function (_decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[1], name = _a[2], typeParameters = _a[3], parameters = _a[4], type = _a[5], body = _a[6], other = _a[7]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isIdentifier(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], asteriskToken = _a[2], name = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken !== "string" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateFunctionDeclaration = ts.buildOverload("updateFunctionDeclaration") + .overload({ + 0: function (node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + 1: function (node, _decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[2], name = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7], other = _a[8]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || ts.isIdentifier(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], asteriskToken = _a[3], name = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken !== "string" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createClassDeclaration = ts.buildOverload("createClassDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createClassDeclaration(ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function () { return true; }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateClassDeclaration = ts.buildOverload("updateClassDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createInterfaceDeclaration = ts.buildOverload("createInterfaceDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (_decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateInterfaceDeclaration = ts.buildOverload("updateInterfaceDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, _decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createTypeAliasDeclaration = ts.buildOverload("createTypeAliasDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, type) { + return createTypeAliasDeclaration(modifiers, name, typeParameters, type); + }, + 1: function (_decorators, modifiers, name, typeParameters, type) { + return createTypeAliasDeclaration(modifiers, name, typeParameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], typeParameters = _a[2], type = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], typeParameters = _a[3], type = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateTypeAliasDeclaration = ts.buildOverload("updateTypeAliasDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, type) { + return updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type); + }, + 1: function (node, _decorators, modifiers, name, typeParameters, type) { + return updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], type = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], typeParameters = _a[4], type = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createEnumDeclaration = ts.buildOverload("createEnumDeclaration") + .overload({ + 0: function (modifiers, name, members) { + return createEnumDeclaration(modifiers, name, members); + }, + 1: function (_decorators, modifiers, name, members) { + return createEnumDeclaration(modifiers, name, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], members = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], members = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateEnumDeclaration = ts.buildOverload("updateEnumDeclaration") + .overload({ + 0: function (node, modifiers, name, members) { + return updateEnumDeclaration(node, modifiers, name, members); + }, + 1: function (node, _decorators, modifiers, name, members) { + return updateEnumDeclaration(node, modifiers, name, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], members = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], members = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createModuleDeclaration = ts.buildOverload("createModuleDeclaration") + .overload({ + 0: function (modifiers, name, body, flags) { + return createModuleDeclaration(modifiers, name, body, flags); + }, + 1: function (_decorators, modifiers, name, body, flags) { + return createModuleDeclaration(modifiers, name, body, flags); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], body = _a[2], flags = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name !== undefined && !ts.isArray(name)) && + (body === undefined || ts.isModuleBody(body)) && + (flags === undefined || typeof flags === "number"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], body = _a[3], flags = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name !== undefined && ts.isModuleName(name)) && + (body === undefined || typeof body === "object") && + (flags === undefined || typeof flags === "number"); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateModuleDeclaration = ts.buildOverload("updateModuleDeclaration") + .overload({ + 0: function (node, modifiers, name, body) { + return updateModuleDeclaration(node, modifiers, name, body); + }, + 1: function (node, _decorators, modifiers, name, body) { + return updateModuleDeclaration(node, modifiers, name, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (body === undefined || ts.isModuleBody(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], body = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name !== undefined && ts.isModuleName(name)) && + (body === undefined || ts.isModuleBody(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createImportEqualsDeclaration = ts.buildOverload("createImportEqualsDeclaration") + .overload({ + 0: function (modifiers, isTypeOnly, name, moduleReference) { + return createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference); + }, + 1: function (_decorators, modifiers, isTypeOnly, name, moduleReference) { + return createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isTypeOnly = _a[1], name = _a[2], moduleReference = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name !== "boolean") && + (typeof moduleReference !== "string"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isTypeOnly = _a[2], name = _a[3], moduleReference = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name === "string" || ts.isIdentifier(name)) && + (moduleReference !== undefined && ts.isModuleReference(moduleReference)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateImportEqualsDeclaration = ts.buildOverload("updateImportEqualsDeclaration") + .overload({ + 0: function (node, modifiers, isTypeOnly, name, moduleReference) { + return updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference); + }, + 1: function (node, _decorators, modifiers, isTypeOnly, name, moduleReference) { + return updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], isTypeOnly = _a[2], name = _a[3], moduleReference = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name !== "boolean") && + (typeof moduleReference !== "string"); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], isTypeOnly = _a[3], name = _a[4], moduleReference = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name === "string" || ts.isIdentifier(name)) && + (moduleReference !== undefined && ts.isModuleReference(moduleReference)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createImportDeclaration = ts.buildOverload("createImportDeclaration") + .overload({ + 0: function (modifiers, importClause, moduleSpecifier, assertClause) { + return createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + }, + 1: function (_decorators, modifiers, importClause, moduleSpecifier, assertClause) { + return createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], importClause = _a[1], moduleSpecifier = _a[2], assertClause = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (importClause === undefined || !ts.isArray(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], importClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (importClause === undefined || ts.isImportClause(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateImportDeclaration = ts.buildOverload("updateImportDeclaration") + .overload({ + 0: function (node, modifiers, importClause, moduleSpecifier, assertClause) { + return updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause); + }, + 1: function (node, _decorators, modifiers, importClause, moduleSpecifier, assertClause) { + return updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], importClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (importClause === undefined || !ts.isArray(importClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], importClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (importClause === undefined || ts.isImportClause(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createExportAssignment = ts.buildOverload("createExportAssignment") + .overload({ + 0: function (modifiers, isExportEquals, expression) { + return createExportAssignment(modifiers, isExportEquals, expression); + }, + 1: function (_decorators, modifiers, isExportEquals, expression) { + return createExportAssignment(modifiers, isExportEquals, expression); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isExportEquals = _a[1], expression = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isExportEquals === undefined || typeof isExportEquals === "boolean") && + (typeof expression === "object"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isExportEquals = _a[2], expression = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isExportEquals === undefined || typeof isExportEquals === "boolean") && + (expression !== undefined && ts.isExpression(expression)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateExportAssignment = ts.buildOverload("updateExportAssignment") + .overload({ + 0: function (node, modifiers, expression) { + return updateExportAssignment(node, modifiers, expression); + }, + 1: function (node, _decorators, modifiers, expression) { + return updateExportAssignment(node, modifiers, expression); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], expression = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (expression !== undefined && !ts.isArray(expression)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], expression = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (expression !== undefined && ts.isExpression(expression)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createExportDeclaration = ts.buildOverload("createExportDeclaration") + .overload({ + 0: function (modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + 1: function (_decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isTypeOnly = _a[1], exportClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (typeof isTypeOnly === "boolean") && + (typeof exportClause !== "boolean") && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isTypeOnly = _a[2], exportClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (typeof isTypeOnly === "boolean") && + (exportClause === undefined || ts.isNamedExportBindings(exportClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateExportDeclaration = ts.buildOverload("updateExportDeclaration") + .overload({ + 0: function (node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + 1: function (node, _decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], isTypeOnly = _a[2], exportClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5], other = _a[6]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (typeof isTypeOnly === "boolean") && + (typeof exportClause !== "boolean") && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], isTypeOnly = _a[3], exportClause = _a[4], moduleSpecifier = _a[5], assertClause = _a[6]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (typeof isTypeOnly === "boolean") && + (exportClause === undefined || ts.isNamedExportBindings(exportClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); })(ts || (ts = {})); //# sourceMappingURL=tsserverlibrary.js.map diff --git a/tsserver/typescript.d.ts b/tsserver/typescript.d.ts index fb0a5a0c..0fd60ae8 100644 --- a/tsserver/typescript.d.ts +++ b/tsserver/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "4.7"; + const versionMajorMinor = "4.8"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -425,6 +425,7 @@ declare namespace ts { JSDocFunctionType = 317, JSDocVariadicType = 318, JSDocNamepathType = 319, + JSDoc = 320, /** @deprecated Use SyntaxKind.JSDoc */ JSDocComment = 320, JSDocText = 321, @@ -493,7 +494,6 @@ declare namespace ts { LastJSDocNode = 347, FirstJSDocTagNode = 327, LastJSDocTagNode = 347, - JSDoc = 320 } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; @@ -554,13 +554,15 @@ declare namespace ts { Override = 16384, In = 32768, Out = 65536, + Decorator = 131072, HasComputedFlags = 536870912, AccessibilityModifier = 28, ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, TypeScriptModifier = 116958, ExportDefault = 513, - All = 125951 + All = 257023, + Modifier = 125951 } export enum JsxFlags { None = 0, @@ -573,8 +575,6 @@ declare namespace ts { export interface Node extends ReadonlyTextRange { readonly kind: SyntaxKind; readonly flags: NodeFlags; - readonly decorators?: NodeArray; - readonly modifiers?: ModifiersArray; readonly parent: Node; } export interface JSDocContainer { @@ -583,7 +583,9 @@ declare namespace ts { export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; export type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; - export type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; + export type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | EnumMember; + export type HasDecorators = ParameterDeclaration | PropertyDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ClassExpression | ClassDeclaration; + export type HasModifiers = TypeParameterDeclaration | ParameterDeclaration | ConstructorTypeNode | PropertySignature | PropertyDeclaration | MethodSignature | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | IndexSignatureDeclaration | FunctionExpression | ArrowFunction | ClassExpression | VariableStatement | FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | ExportAssignment | ExportDeclaration; export interface NodeArray extends ReadonlyArray, ReadonlyTextRange { readonly hasTrailingComma: boolean; } @@ -632,6 +634,7 @@ declare namespace ts { /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | InKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OutKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; + export type ModifierLike = Modifier | Decorator; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; @@ -691,6 +694,7 @@ declare namespace ts { export interface TypeParameterDeclaration extends NamedDeclaration { readonly kind: SyntaxKind.TypeParameter; readonly parent: DeclarationWithTypeParameterChildren | InferTypeNode; + readonly modifiers?: NodeArray; readonly name: Identifier; /** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */ readonly constraint?: TypeNode; @@ -700,9 +704,9 @@ declare namespace ts { export interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { readonly kind: SignatureDeclaration["kind"]; readonly name?: PropertyName; - readonly typeParameters?: NodeArray; + readonly typeParameters?: NodeArray | undefined; readonly parameters: NodeArray; - readonly type?: TypeNode; + readonly type?: TypeNode | undefined; } export type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; export interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { @@ -728,6 +732,7 @@ declare namespace ts { export interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.Parameter; readonly parent: SignatureDeclaration; + readonly modifiers?: NodeArray; readonly dotDotDotToken?: DotDotDotToken; readonly name: BindingName; readonly questionToken?: QuestionToken; @@ -744,14 +749,15 @@ declare namespace ts { } export interface PropertySignature extends TypeElement, JSDocContainer { readonly kind: SyntaxKind.PropertySignature; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly questionToken?: QuestionToken; readonly type?: TypeNode; - initializer?: Expression; } export interface PropertyDeclaration extends ClassElement, JSDocContainer { readonly kind: SyntaxKind.PropertyDeclaration; readonly parent: ClassLikeDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly questionToken?: QuestionToken; readonly exclamationToken?: ExclamationToken; @@ -768,16 +774,12 @@ declare namespace ts { readonly kind: SyntaxKind.PropertyAssignment; readonly parent: ObjectLiteralExpression; readonly name: PropertyName; - readonly questionToken?: QuestionToken; - readonly exclamationToken?: ExclamationToken; readonly initializer: Expression; } export interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.ShorthandPropertyAssignment; readonly parent: ObjectLiteralExpression; readonly name: Identifier; - readonly questionToken?: QuestionToken; - readonly exclamationToken?: ExclamationToken; readonly equalsToken?: EqualsToken; readonly objectAssignmentInitializer?: Expression; } @@ -812,34 +814,38 @@ declare namespace ts { */ export interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { _functionLikeDeclarationBrand: any; - readonly asteriskToken?: AsteriskToken; - readonly questionToken?: QuestionToken; - readonly exclamationToken?: ExclamationToken; - readonly body?: Block | Expression; + readonly asteriskToken?: AsteriskToken | undefined; + readonly questionToken?: QuestionToken | undefined; + readonly exclamationToken?: ExclamationToken | undefined; + readonly body?: Block | Expression | undefined; } export type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; /** @deprecated Use SignatureDeclaration */ export type FunctionLike = SignatureDeclaration; export interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { readonly kind: SyntaxKind.FunctionDeclaration; + readonly modifiers?: NodeArray; readonly name?: Identifier; readonly body?: FunctionBody; } export interface MethodSignature extends SignatureDeclarationBase, TypeElement { readonly kind: SyntaxKind.MethodSignature; readonly parent: ObjectTypeDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; } export interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.MethodDeclaration; readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly modifiers?: NodeArray | undefined; readonly name: PropertyName; - readonly body?: FunctionBody; + readonly body?: FunctionBody | undefined; } export interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { readonly kind: SyntaxKind.Constructor; readonly parent: ClassLikeDeclaration; - readonly body?: FunctionBody; + readonly modifiers?: NodeArray | undefined; + readonly body?: FunctionBody | undefined; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ export interface SemicolonClassElement extends ClassElement { @@ -849,12 +855,14 @@ declare namespace ts { export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.GetAccessor; readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly body?: FunctionBody; } export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.SetAccessor; readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly body?: FunctionBody; } @@ -862,6 +870,7 @@ declare namespace ts { export interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { readonly kind: SyntaxKind.IndexSignature; readonly parent: ObjectTypeDeclaration; + readonly modifiers?: NodeArray; readonly type: TypeNode; } export interface ClassStaticBlockDeclaration extends ClassElement, JSDocContainer { @@ -901,6 +910,7 @@ declare namespace ts { } export interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase { readonly kind: SyntaxKind.ConstructorType; + readonly modifiers?: NodeArray; } export interface NodeWithTypeArguments extends TypeNode { readonly typeArguments?: NodeArray; @@ -1157,11 +1167,13 @@ declare namespace ts { export type ConciseBody = FunctionBody | Expression; export interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.FunctionExpression; + readonly modifiers?: NodeArray; readonly name?: Identifier; readonly body: FunctionBody; } export interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.ArrowFunction; + readonly modifiers?: NodeArray; readonly equalsGreaterThanToken: EqualsGreaterThanToken; readonly body: ConciseBody; readonly name: never; @@ -1388,8 +1400,9 @@ declare namespace ts { readonly kind: SyntaxKind.JsxAttribute; readonly parent: JsxAttributes; readonly name: Identifier; - readonly initializer?: StringLiteral | JsxExpression; + readonly initializer?: JsxAttributeValue; } + export type JsxAttributeValue = StringLiteral | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; export interface JsxSpreadAttribute extends ObjectLiteralElement { readonly kind: SyntaxKind.JsxSpreadAttribute; readonly parent: JsxAttributes; @@ -1442,6 +1455,7 @@ declare namespace ts { } export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; + readonly modifiers?: NodeArray; readonly declarationList: VariableDeclarationList; } export interface ExpressionStatement extends Statement { @@ -1558,11 +1572,13 @@ declare namespace ts { } export interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { readonly kind: SyntaxKind.ClassDeclaration; + readonly modifiers?: NodeArray; /** May be undefined in `export default class { ... }`. */ readonly name?: Identifier; } export interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { readonly kind: SyntaxKind.ClassExpression; + readonly modifiers?: NodeArray; } export type ClassLikeDeclaration = ClassDeclaration | ClassExpression; export interface ClassElement extends NamedDeclaration { @@ -1572,10 +1588,11 @@ declare namespace ts { export interface TypeElement extends NamedDeclaration { _typeElementBrand: any; readonly name?: PropertyName; - readonly questionToken?: QuestionToken; + readonly questionToken?: QuestionToken | undefined; } export interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.InterfaceDeclaration; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly typeParameters?: NodeArray; readonly heritageClauses?: NodeArray; @@ -1589,6 +1606,7 @@ declare namespace ts { } export interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.TypeAliasDeclaration; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly typeParameters?: NodeArray; readonly type: TypeNode; @@ -1601,6 +1619,7 @@ declare namespace ts { } export interface EnumDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.EnumDeclaration; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly members: NodeArray; } @@ -1609,6 +1628,7 @@ declare namespace ts { export interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ModuleDeclaration; readonly parent: ModuleBody | SourceFile; + readonly modifiers?: NodeArray; readonly name: ModuleName; readonly body?: ModuleBody | JSDocNamespaceDeclaration; } @@ -1636,6 +1656,7 @@ declare namespace ts { export interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ImportEqualsDeclaration; readonly parent: SourceFile | ModuleBlock; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly isTypeOnly: boolean; readonly moduleReference: ModuleReference; @@ -1648,6 +1669,7 @@ declare namespace ts { export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; + readonly modifiers?: NodeArray; readonly importClause?: ImportClause; /** If this is not a StringLiteral it will be a grammar error. */ readonly moduleSpecifier: Expression; @@ -1692,6 +1714,7 @@ declare namespace ts { export interface ExportDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ExportDeclaration; readonly parent: SourceFile | ModuleBlock; + readonly modifiers?: NodeArray; readonly isTypeOnly: boolean; /** Will not be assigned in the case of `export * from "foo";` */ readonly exportClause?: NamedExportBindings; @@ -1759,6 +1782,7 @@ declare namespace ts { export interface ExportAssignment extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ExportAssignment; readonly parent: SourceFile; + readonly modifiers?: NodeArray; readonly isExportEquals?: boolean; readonly expression: Expression; } @@ -2072,6 +2096,12 @@ declare namespace ts { * It is _public_ so that (pre)transformers can set this field, * since it switches the builtin `node` module transform. Generally speaking, if unset, * the field is treated as though it is `ModuleKind.CommonJS`. + * + * Note that this field is only set by the module resolution process when + * `moduleResolution` is `Node16` or `NodeNext`, which is implied by the `module` setting + * of `Node16` or `NodeNext`, respectively, but may be overriden (eg, by a `moduleResolution` + * of `node`). If so, this field will be unset and source files will be considered to be + * CommonJS-output-format by the node module transformer and type checker, regardless of extension or context. */ impliedNodeFormat?: ModuleKind.ESNext | ModuleKind.CommonJS; } @@ -2396,6 +2426,7 @@ declare namespace ts { UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, NoTypeReduction = 536870912, + OmitThisParameter = 33554432, AllowThisInObjectLiteral = 32768, AllowQualifiedNameInPlaceOfIdentifier = 65536, /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ @@ -2426,6 +2457,7 @@ declare namespace ts { UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, NoTypeReduction = 536870912, + OmitThisParameter = 33554432, AllowUniqueESSymbolType = 1048576, AddUndefined = 131072, WriteArrowStyleSignature = 262144, @@ -2434,7 +2466,7 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 814775659 + NodeBuilderFlagsMask = 848330091 } export enum SymbolFormatFlags { None = 0, @@ -3402,39 +3434,35 @@ declare namespace ts { createComputedPropertyName(expression: Expression): ComputedPropertyName; updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; createTypeParameterDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; - /** @deprecated */ - createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - /** @deprecated */ - updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - createParameterDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; - updateParameterDeclaration(node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + createParameterDeclaration(modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + updateParameterDeclaration(node: ParameterDeclaration, modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; createDecorator(expression: Expression): Decorator; updateDecorator(node: Decorator, expression: Expression): Decorator; createPropertySignature(modifiers: readonly Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature; updatePropertySignature(node: PropertySignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature; - createPropertyDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; - updatePropertyDeclaration(node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + createPropertyDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + updatePropertyDeclaration(node: PropertyDeclaration, modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; createMethodSignature(modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): MethodSignature; updateMethodSignature(node: MethodSignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): MethodSignature; - createMethodDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; - updateMethodDeclaration(node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; - createConstructorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; - updateConstructorDeclaration(node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; - createGetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - updateGetAccessorDeclaration(node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - createSetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; - updateSetAccessorDeclaration(node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + createMethodDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + updateMethodDeclaration(node: MethodDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + createConstructorDeclaration(modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + updateConstructorDeclaration(node: ConstructorDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + createGetAccessorDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + updateGetAccessorDeclaration(node: GetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + createSetAccessorDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + updateSetAccessorDeclaration(node: SetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; createCallSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; createConstructSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - createIndexSignature(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - updateIndexSignature(node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + createIndexSignature(modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + updateIndexSignature(node: IndexSignatureDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; createTemplateLiteralTypeSpan(type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan; updateTemplateLiteralTypeSpan(node: TemplateLiteralTypeSpan, type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan; - createClassStaticBlockDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; - updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; + createClassStaticBlockDeclaration(body: Block): ClassStaticBlockDeclaration; + updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, body: Block): ClassStaticBlockDeclaration; createKeywordTypeNode(kind: TKind): KeywordTypeNode; createTypePredicateNode(assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode | string, type: TypeNode | undefined): TypePredicateNode; updateTypePredicateNode(node: TypePredicateNode, assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode, type: TypeNode | undefined): TypePredicateNode; @@ -3443,11 +3471,7 @@ declare namespace ts { createFunctionTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): FunctionTypeNode; updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): FunctionTypeNode; createConstructorTypeNode(modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; - /** @deprecated */ - createConstructorTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; updateConstructorTypeNode(node: ConstructorTypeNode, modifiers: readonly Modifier[] | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; - /** @deprecated */ - updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; createTypeQueryNode(exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode; updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode; createTypeLiteralNode(members: readonly TypeElement[] | undefined): TypeLiteralNode; @@ -3470,9 +3494,7 @@ declare namespace ts { updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode; updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode; - createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; createImportTypeNode(argument: TypeNode, assertions?: ImportTypeAssertionContainer, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; - updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; @@ -3552,8 +3574,8 @@ declare namespace ts { updateYieldExpression(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression | undefined): YieldExpression; createSpreadElement(expression: Expression): SpreadElement; updateSpreadElement(node: SpreadElement, expression: Expression): SpreadElement; - createClassExpression(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; - updateClassExpression(node: ClassExpression, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + createClassExpression(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + updateClassExpression(node: ClassExpression, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; createOmittedExpression(): OmittedExpression; createExpressionWithTypeArguments(expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments; updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments; @@ -3608,28 +3630,28 @@ declare namespace ts { updateVariableDeclaration(node: VariableDeclaration, name: BindingName, exclamationToken: ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; createVariableDeclarationList(declarations: readonly VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; updateVariableDeclarationList(node: VariableDeclarationList, declarations: readonly VariableDeclaration[]): VariableDeclarationList; - createFunctionDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - updateFunctionDeclaration(node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - createClassDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; - updateClassDeclaration(node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; - createInterfaceDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; - updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; - createTypeAliasDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; - updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; - createEnumDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; - updateEnumDeclaration(node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; - createModuleDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; - updateModuleDeclaration(node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + createFunctionDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + updateFunctionDeclaration(node: FunctionDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + createClassDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + updateClassDeclaration(node: ClassDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + createInterfaceDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + updateInterfaceDeclaration(node: InterfaceDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + createTypeAliasDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + updateTypeAliasDeclaration(node: TypeAliasDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + createEnumDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + updateEnumDeclaration(node: EnumDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + createModuleDeclaration(modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + updateModuleDeclaration(node: ModuleDeclaration, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; createModuleBlock(statements: readonly Statement[]): ModuleBlock; updateModuleBlock(node: ModuleBlock, statements: readonly Statement[]): ModuleBlock; createCaseBlock(clauses: readonly CaseOrDefaultClause[]): CaseBlock; updateCaseBlock(node: CaseBlock, clauses: readonly CaseOrDefaultClause[]): CaseBlock; createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; - createImportEqualsDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - createImportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; - updateImportDeclaration(node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + createImportEqualsDeclaration(modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + updateImportEqualsDeclaration(node: ImportEqualsDeclaration, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + createImportDeclaration(modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; + updateImportDeclaration(node: ImportDeclaration, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; createAssertClause(elements: NodeArray, multiLine?: boolean): AssertClause; @@ -3646,10 +3668,10 @@ declare namespace ts { updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports; createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - createExportAssignment(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; - updateExportAssignment(node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; - createExportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; - updateExportDeclaration(node: ExportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; + createExportAssignment(modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + updateExportAssignment(node: ExportAssignment, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + createExportDeclaration(modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; + updateExportDeclaration(node: ExportDeclaration, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; createNamedExports(elements: readonly ExportSpecifier[]): NamedExports; updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports; createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; @@ -3746,8 +3768,8 @@ declare namespace ts { createJsxOpeningFragment(): JsxOpeningFragment; createJsxJsxClosingFragment(): JsxClosingFragment; updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment): JsxFragment; - createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression | undefined): JsxAttribute; - updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression | undefined): JsxAttribute; + createJsxAttribute(name: Identifier, initializer: JsxAttributeValue | undefined): JsxAttribute; + updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: JsxAttributeValue | undefined): JsxAttribute; createJsxAttributes(properties: readonly JsxAttributeLike[]): JsxAttributes; updateJsxAttributes(node: JsxAttributes, properties: readonly JsxAttributeLike[]): JsxAttributes; createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; @@ -4055,7 +4077,7 @@ declare namespace ts { NoSpaceIfEmpty = 524288, SingleElement = 1048576, SpaceAfterList = 2097152, - Modifiers = 262656, + Modifiers = 2359808, HeritageClauses = 512, SingleLineTypeLiteralMembers = 768, MultiLineTypeLiteralMembers = 32897, @@ -4119,9 +4141,12 @@ declare namespace ts { readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; readonly includeInlayFunctionParameterTypeHints?: boolean; readonly includeInlayVariableTypeHints?: boolean; + readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; readonly includeInlayPropertyDeclarationTypeHints?: boolean; readonly includeInlayFunctionLikeReturnTypeHints?: boolean; readonly includeInlayEnumMemberValueHints?: boolean; + readonly allowRenameOfImportPath?: boolean; + readonly autoImportFileExcludePatterns?: string[]; } /** Represents a bigint literal value without requiring bigint support */ export interface PseudoBigInt { @@ -4138,7 +4163,7 @@ declare namespace ts { Changed = 1, Deleted = 2 } - export type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; + export type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind, modifiedTime?: Date) => void; export type DirectoryWatcherCallback = (fileName: string) => void; export interface System { args: string[]; @@ -4349,6 +4374,8 @@ declare namespace ts { function symbolName(symbol: Symbol): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined; function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined; + function getDecorators(node: HasDecorators): readonly Decorator[] | undefined; + function getModifiers(node: HasModifiers): readonly Modifier[] | undefined; /** * Gets the JSDoc parameter tags for the node if present. * @@ -4437,6 +4464,12 @@ declare namespace ts { /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + * + * This does *not* return type parameters from a jsdoc reference to a generic type, eg + * + * type Id = (x: T) => T + * /** @type {Id} / + * function id(x) { return x } */ function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[]; function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; @@ -4482,6 +4515,7 @@ declare namespace ts { function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; + function isModifierLike(node: Node): node is ModifierLike; function isTypeElement(node: Node): node is TypeElement; function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement; function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; @@ -4510,6 +4544,8 @@ declare namespace ts { function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; function isStringLiteralLike(node: Node): node is StringLiteralLike; function isJSDocLinkLike(node: Node): node is JSDocLink | JSDocLinkCode | JSDocLinkPlain; + function hasRestParameter(s: SignatureDeclaration | JSDocSignature): boolean; + function isRestParameter(node: ParameterDeclaration | JSDocParameterTag): boolean; } declare namespace ts { const factory: NodeFactory; @@ -4720,6 +4756,7 @@ declare namespace ts { function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; function isImportDeclaration(node: Node): node is ImportDeclaration; function isImportClause(node: Node): node is ImportClause; + function isImportTypeAssertionContainer(node: Node): node is ImportTypeAssertionContainer; function isAssertClause(node: Node): node is AssertClause; function isAssertEntry(node: Node): node is AssertEntry; function isNamespaceImport(node: Node): node is NamespaceImport; @@ -4797,6 +4834,8 @@ declare namespace ts { } declare namespace ts { function setTextRange(range: T, location: TextRange | undefined): T; + function canHaveModifiers(node: Node): node is HasModifiers; + function canHaveDecorators(node: Node): node is HasDecorators; } declare namespace ts { /** @@ -5098,6 +5137,31 @@ declare namespace ts { export function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; export function formatDiagnosticsWithColorAndContext(diagnostics: readonly Diagnostic[], host: FormatDiagnosticsHost): string; export function flattenDiagnosticMessageText(diag: string | DiagnosticMessageChain | undefined, newLine: string, indent?: number): string; + /** + * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly + * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. + */ + export function getModeForFileReference(ref: FileReference | string, containingFileMode: SourceFile["impliedNodeFormat"]): ModuleKind.CommonJS | ModuleKind.ESNext | undefined; + /** + * Calculates the final resolution mode for an import at some index within a file's imports list. This is generally the explicitly + * defined mode of the import if provided, or, if not, the mode of the containing file (with some exceptions: import=require is always commonjs, dynamic import is always esm). + * If you have an actual import node, prefer using getModeForUsageLocation on the reference string node. + * @param file File to fetch the resolution mode within + * @param index Index into the file's complete resolution list to get the resolution of - this is a concatenation of the file's imports and module augmentations + */ + export function getModeForResolutionAtIndex(file: SourceFile, index: number): ModuleKind.CommonJS | ModuleKind.ESNext | undefined; + /** + * Calculates the final resolution mode for a given module reference node. This is generally the explicitly provided resolution mode, if + * one exists, or the mode of the containing source file. (Excepting import=require, which is always commonjs, and dynamic import, which is always esm). + * Notably, this function always returns `undefined` if the containing file has an `undefined` `impliedNodeFormat` - this field is only set when + * `moduleResolution` is `node16`+. + * @param file The file the import or import-like reference is contained within + * @param usage The module reference string + * @returns The final resolution mode of the import + */ + export function getModeForUsageLocation(file: { + impliedNodeFormat?: SourceFile["impliedNodeFormat"]; + }, usage: StringLiteralLike): ModuleKind.CommonJS | ModuleKind.ESNext | undefined; export function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): readonly Diagnostic[]; /** * A function for determining if a given file is esm or cjs format, assuming modern node module resolution rules, as configured by the @@ -5357,6 +5421,10 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile?: SourceFile): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: SourceFile["impliedNodeFormat"] | undefined): (ResolvedTypeReferenceDirective | undefined)[]; + /** + * Returns the module resolution cache used by a provided `resolveModuleNames` implementation so that any non-name module resolution operations (eg, package.json lookup) can reuse it + */ + getModuleResolutionCache?(): ModuleResolutionCache | undefined; } interface WatchCompilerHost extends ProgramHost, WatchHost { /** Instead of using output d.ts file from project reference, use its source file */ @@ -5871,6 +5939,8 @@ declare namespace ts { getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; + getRenameInfo(fileName: string, position: number, preferences: UserPreferences): RenameInfo; + /** @deprecated Use the signature with `UserPreferences` instead. */ getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo; findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): readonly RenameLocation[] | undefined; getSmartSelectionRange(fileName: string, position: number): SelectionRange; @@ -6250,6 +6320,7 @@ declare namespace ts { Insert = "insert", Remove = "remove" } + /** @deprecated - consider using EditorSettings instead */ interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -6267,6 +6338,7 @@ declare namespace ts { indentStyle?: IndentStyle; trimTrailingWhitespace?: boolean; } + /** @deprecated - consider using FormatCodeSettings instead */ interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; InsertSpaceAfterSemicolonInForStatements: boolean; @@ -6392,6 +6464,9 @@ declare namespace ts { canRename: false; localizedErrorMessage: string; } + /** + * @deprecated Use `UserPreferences` instead. + */ interface RenameInfoOptions { readonly allowRenameOfImportPath?: boolean; } @@ -6829,8 +6904,8 @@ declare namespace ts { * @param version Current version of the file. Only used if the file was not found * in the registry and a new one was created. */ - acquireDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; - acquireDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + acquireDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; + acquireDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; /** * Request an updated version of an already existing SourceFile with a given fileName * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile @@ -6846,8 +6921,8 @@ declare namespace ts { * @param scriptSnapshot Text of the file. * @param version Current version of the file. */ - updateDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; - updateDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + updateDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; + updateDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey; /** * Informs the DocumentRegistry that a file is not needed any longer. @@ -6857,9 +6932,10 @@ declare namespace ts { * * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file + * @param scriptKind The script kind of the file to be released */ - /**@deprecated pass scriptKind for correctness */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /**@deprecated pass scriptKind and impliedNodeFormat for correctness */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind?: ScriptKind): void; /** * Informs the DocumentRegistry that a file is not needed any longer. * @@ -6869,12 +6945,13 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file * @param scriptKind The script kind of the file to be released + * @param impliedNodeFormat The implied source file format of the file to be released */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind, impliedNodeFormat: SourceFile["impliedNodeFormat"]): void; /** - * @deprecated pass scriptKind for correctness */ - releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; - releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; + * @deprecated pass scriptKind for and impliedNodeFormat correctness */ + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind?: ScriptKind): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind, impliedNodeFormat: SourceFile["impliedNodeFormat"]): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { @@ -6983,33 +7060,69 @@ declare namespace ts { (node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; }; /** @deprecated Use `factory.createParameterDeclaration` or the factory supplied by your transformation context instead. */ - const createParameter: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined) => ParameterDeclaration; + const createParameter: { + (modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined): ParameterDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined): ParameterDeclaration; + }; /** @deprecated Use `factory.updateParameterDeclaration` or the factory supplied by your transformation context instead. */ - const updateParameter: (node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) => ParameterDeclaration; + const updateParameter: { + (node: ParameterDeclaration, modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + (node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + }; /** @deprecated Use `factory.createDecorator` or the factory supplied by your transformation context instead. */ const createDecorator: (expression: Expression) => Decorator; /** @deprecated Use `factory.updateDecorator` or the factory supplied by your transformation context instead. */ const updateDecorator: (node: Decorator, expression: Expression) => Decorator; /** @deprecated Use `factory.createPropertyDeclaration` or the factory supplied by your transformation context instead. */ - const createProperty: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) => PropertyDeclaration; + const createProperty: { + (modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + }; /** @deprecated Use `factory.updatePropertyDeclaration` or the factory supplied by your transformation context instead. */ - const updateProperty: (node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) => PropertyDeclaration; + const updateProperty: { + (node: PropertyDeclaration, modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + (node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + }; /** @deprecated Use `factory.createMethodDeclaration` or the factory supplied by your transformation context instead. */ - const createMethod: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => MethodDeclaration; + const createMethod: { + (modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + }; /** @deprecated Use `factory.updateMethodDeclaration` or the factory supplied by your transformation context instead. */ - const updateMethod: (node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => MethodDeclaration; + const updateMethod: { + (node: MethodDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + (node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + }; /** @deprecated Use `factory.createConstructorDeclaration` or the factory supplied by your transformation context instead. */ - const createConstructor: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined) => ConstructorDeclaration; + const createConstructor: { + (modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + }; /** @deprecated Use `factory.updateConstructorDeclaration` or the factory supplied by your transformation context instead. */ - const updateConstructor: (node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined) => ConstructorDeclaration; + const updateConstructor: { + (node: ConstructorDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + (node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + }; /** @deprecated Use `factory.createGetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const createGetAccessor: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => GetAccessorDeclaration; + const createGetAccessor: { + (modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + }; /** @deprecated Use `factory.updateGetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const updateGetAccessor: (node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => GetAccessorDeclaration; + const updateGetAccessor: { + (node: GetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + (node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + }; /** @deprecated Use `factory.createSetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const createSetAccessor: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined) => SetAccessorDeclaration; + const createSetAccessor: { + (modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + }; /** @deprecated Use `factory.updateSetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const updateSetAccessor: (node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined) => SetAccessorDeclaration; + const updateSetAccessor: { + (node: SetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + (node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + }; /** @deprecated Use `factory.createCallSignature` or the factory supplied by your transformation context instead. */ const createCallSignature: (typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined) => CallSignatureDeclaration; /** @deprecated Use `factory.updateCallSignature` or the factory supplied by your transformation context instead. */ @@ -7019,7 +7132,10 @@ declare namespace ts { /** @deprecated Use `factory.updateConstructSignature` or the factory supplied by your transformation context instead. */ const updateConstructSignature: (node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) => ConstructSignatureDeclaration; /** @deprecated Use `factory.updateIndexSignature` or the factory supplied by your transformation context instead. */ - const updateIndexSignature: (node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode) => IndexSignatureDeclaration; + const updateIndexSignature: { + (node: IndexSignatureDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + (node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + }; /** @deprecated Use `factory.createKeywordTypeNode` or the factory supplied by your transformation context instead. */ const createKeywordTypeNode: (kind: TKind) => KeywordTypeNode; /** @deprecated Use `factory.createTypePredicateNode` or the factory supplied by your transformation context instead. */ @@ -7080,13 +7196,14 @@ declare namespace ts { const updateInferTypeNode: (node: InferTypeNode, typeParameter: TypeParameterDeclaration) => InferTypeNode; /** @deprecated Use `factory.createImportTypeNode` or the factory supplied by your transformation context instead. */ const createImportTypeNode: { - (argument: TypeNode, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; (argument: TypeNode, assertions?: ImportTypeAssertionContainer | undefined, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; + (argument: TypeNode, assertions?: ImportTypeAssertionContainer | undefined, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; + (argument: TypeNode, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; }; /** @deprecated Use `factory.updateImportTypeNode` or the factory supplied by your transformation context instead. */ const updateImportTypeNode: { - (node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; (node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; + (node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; }; /** @deprecated Use `factory.createParenthesizedType` or the factory supplied by your transformation context instead. */ const createParenthesizedType: (type: TypeNode) => ParenthesizedTypeNode; @@ -7331,29 +7448,65 @@ declare namespace ts { /** @deprecated Use `factory.updateVariableDeclarationList` or the factory supplied by your transformation context instead. */ const updateVariableDeclarationList: (node: VariableDeclarationList, declarations: readonly VariableDeclaration[]) => VariableDeclarationList; /** @deprecated Use `factory.createFunctionDeclaration` or the factory supplied by your transformation context instead. */ - const createFunctionDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => FunctionDeclaration; + const createFunctionDeclaration: { + (modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + }; /** @deprecated Use `factory.updateFunctionDeclaration` or the factory supplied by your transformation context instead. */ - const updateFunctionDeclaration: (node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => FunctionDeclaration; + const updateFunctionDeclaration: { + (node: FunctionDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + (node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + }; /** @deprecated Use `factory.createClassDeclaration` or the factory supplied by your transformation context instead. */ - const createClassDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]) => ClassDeclaration; + const createClassDeclaration: { + (modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + }; /** @deprecated Use `factory.updateClassDeclaration` or the factory supplied by your transformation context instead. */ - const updateClassDeclaration: (node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]) => ClassDeclaration; + const updateClassDeclaration: { + (node: ClassDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + (node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + }; /** @deprecated Use `factory.createInterfaceDeclaration` or the factory supplied by your transformation context instead. */ - const createInterfaceDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]) => InterfaceDeclaration; + const createInterfaceDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + }; /** @deprecated Use `factory.updateInterfaceDeclaration` or the factory supplied by your transformation context instead. */ - const updateInterfaceDeclaration: (node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]) => InterfaceDeclaration; + const updateInterfaceDeclaration: { + (node: InterfaceDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + (node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + }; /** @deprecated Use `factory.createTypeAliasDeclaration` or the factory supplied by your transformation context instead. */ - const createTypeAliasDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode) => TypeAliasDeclaration; + const createTypeAliasDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + }; /** @deprecated Use `factory.updateTypeAliasDeclaration` or the factory supplied by your transformation context instead. */ - const updateTypeAliasDeclaration: (node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode) => TypeAliasDeclaration; + const updateTypeAliasDeclaration: { + (node: TypeAliasDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + (node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + }; /** @deprecated Use `factory.createEnumDeclaration` or the factory supplied by your transformation context instead. */ - const createEnumDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]) => EnumDeclaration; + const createEnumDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + }; /** @deprecated Use `factory.updateEnumDeclaration` or the factory supplied by your transformation context instead. */ - const updateEnumDeclaration: (node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]) => EnumDeclaration; + const updateEnumDeclaration: { + (node: EnumDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + (node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + }; /** @deprecated Use `factory.createModuleDeclaration` or the factory supplied by your transformation context instead. */ - const createModuleDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags | undefined) => ModuleDeclaration; + const createModuleDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags | undefined): ModuleDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags | undefined): ModuleDeclaration; + }; /** @deprecated Use `factory.updateModuleDeclaration` or the factory supplied by your transformation context instead. */ - const updateModuleDeclaration: (node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined) => ModuleDeclaration; + const updateModuleDeclaration: { + (node: ModuleDeclaration, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + (node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + }; /** @deprecated Use `factory.createModuleBlock` or the factory supplied by your transformation context instead. */ const createModuleBlock: (statements: readonly Statement[]) => ModuleBlock; /** @deprecated Use `factory.updateModuleBlock` or the factory supplied by your transformation context instead. */ @@ -7367,13 +7520,25 @@ declare namespace ts { /** @deprecated Use `factory.updateNamespaceExportDeclaration` or the factory supplied by your transformation context instead. */ const updateNamespaceExportDeclaration: (node: NamespaceExportDeclaration, name: Identifier) => NamespaceExportDeclaration; /** @deprecated Use `factory.createImportEqualsDeclaration` or the factory supplied by your transformation context instead. */ - const createImportEqualsDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference) => ImportEqualsDeclaration; + const createImportEqualsDeclaration: { + (modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + }; /** @deprecated Use `factory.updateImportEqualsDeclaration` or the factory supplied by your transformation context instead. */ - const updateImportEqualsDeclaration: (node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference) => ImportEqualsDeclaration; + const updateImportEqualsDeclaration: { + (node: ImportEqualsDeclaration, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + (node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + }; /** @deprecated Use `factory.createImportDeclaration` or the factory supplied by your transformation context instead. */ - const createImportDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause | undefined) => ImportDeclaration; + const createImportDeclaration: { + (modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause | undefined): ImportDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause | undefined): ImportDeclaration; + }; /** @deprecated Use `factory.updateImportDeclaration` or the factory supplied by your transformation context instead. */ - const updateImportDeclaration: (node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined) => ImportDeclaration; + const updateImportDeclaration: { + (node: ImportDeclaration, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + (node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + }; /** @deprecated Use `factory.createNamespaceImport` or the factory supplied by your transformation context instead. */ const createNamespaceImport: (name: Identifier) => NamespaceImport; /** @deprecated Use `factory.updateNamespaceImport` or the factory supplied by your transformation context instead. */ @@ -7387,9 +7552,15 @@ declare namespace ts { /** @deprecated Use `factory.updateImportSpecifier` or the factory supplied by your transformation context instead. */ const updateImportSpecifier: (node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) => ImportSpecifier; /** @deprecated Use `factory.createExportAssignment` or the factory supplied by your transformation context instead. */ - const createExportAssignment: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression) => ExportAssignment; + const createExportAssignment: { + (modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + }; /** @deprecated Use `factory.updateExportAssignment` or the factory supplied by your transformation context instead. */ - const updateExportAssignment: (node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression) => ExportAssignment; + const updateExportAssignment: { + (node: ExportAssignment, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + (node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + }; /** @deprecated Use `factory.createNamedExports` or the factory supplied by your transformation context instead. */ const createNamedExports: (elements: readonly ExportSpecifier[]) => NamedExports; /** @deprecated Use `factory.updateNamedExports` or the factory supplied by your transformation context instead. */ @@ -7479,9 +7650,9 @@ declare namespace ts { /** @deprecated Use `factory.updateJsxFragment` or the factory supplied by your transformation context instead. */ const updateJsxFragment: (node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment) => JsxFragment; /** @deprecated Use `factory.createJsxAttribute` or the factory supplied by your transformation context instead. */ - const createJsxAttribute: (name: Identifier, initializer: StringLiteral | JsxExpression | undefined) => JsxAttribute; + const createJsxAttribute: (name: Identifier, initializer: JsxAttributeValue | undefined) => JsxAttribute; /** @deprecated Use `factory.updateJsxAttribute` or the factory supplied by your transformation context instead. */ - const updateJsxAttribute: (node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression | undefined) => JsxAttribute; + const updateJsxAttribute: (node: JsxAttribute, name: Identifier, initializer: JsxAttributeValue | undefined) => JsxAttribute; /** @deprecated Use `factory.createJsxAttributes` or the factory supplied by your transformation context instead. */ const createJsxAttributes: (properties: readonly JsxAttributeLike[]) => JsxAttributes; /** @deprecated Use `factory.updateJsxAttributes` or the factory supplied by your transformation context instead. */ @@ -7693,8 +7864,12 @@ declare namespace ts { * @deprecated Use an appropriate `factory.update...` method instead, use `setCommentRange` or `setSourceMapRange`, and avoid setting `parent`. */ const getMutableClone: (node: T) => T; +} +declare namespace ts { /** @deprecated Use `isTypeAssertionExpression` instead. */ const isTypeAssertion: (node: Node) => node is TypeAssertion; +} +declare namespace ts { /** * @deprecated Use `ts.ReadonlyESMap` instead. */ @@ -7705,10 +7880,239 @@ declare namespace ts { */ interface Map extends ESMap { } +} +declare namespace ts { /** * @deprecated Use `isMemberName` instead. */ const isIdentifierOrPrivateIdentifier: (node: Node) => node is MemberName; } +declare namespace ts { + interface NodeFactory { + /** @deprecated Use the overload that accepts 'modifiers' */ + createConstructorTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; + /** @deprecated Use the overload that accepts 'modifiers' */ + updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; + } +} +declare namespace ts { + interface NodeFactory { + createImportTypeNode(argument: TypeNode, assertions?: ImportTypeAssertionContainer, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; + /** @deprecated Use the overload that accepts 'assertions' */ + createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; + /** @deprecated Use the overload that accepts 'assertions' */ + updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; + } +} +declare namespace ts { + interface NodeFactory { + /** @deprecated Use the overload that accepts 'modifiers' */ + createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + /** @deprecated Use the overload that accepts 'modifiers' */ + updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + } +} +declare namespace ts { + interface Node { + /** + * @deprecated `decorators` has been removed from `Node` and merged with `modifiers` on the `Node` subtypes that support them. + * Use `ts.canHaveDecorators()` to test whether a `Node` can have decorators. + * Use `ts.getDecorators()` to get the decorators of a `Node`. + * + * For example: + * ```ts + * const decorators = ts.canHaveDecorators(node) ? ts.getDecorators(node) : undefined; + * ``` + */ + readonly decorators?: undefined; + /** + * @deprecated `modifiers` has been removed from `Node` and moved to the `Node` subtypes that support them. + * Use `ts.canHaveModifiers()` to test whether a `Node` can have modifiers. + * Use `ts.getModifiers()` to get the modifiers of a `Node`. + * + * For example: + * ```ts + * const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined; + * ``` + */ + readonly modifiers?: NodeArray | undefined; + } + interface PropertySignature { + /** @deprecated A property signature cannot have an initializer */ + readonly initializer?: Expression | undefined; + } + interface PropertyAssignment { + /** @deprecated A property assignment cannot have a question token */ + readonly questionToken?: QuestionToken | undefined; + /** @deprecated A property assignment cannot have an exclamation token */ + readonly exclamationToken?: ExclamationToken | undefined; + } + interface ShorthandPropertyAssignment { + /** @deprecated A shorthand property assignment cannot have modifiers */ + readonly modifiers?: NodeArray | undefined; + /** @deprecated A shorthand property assignment cannot have a question token */ + readonly questionToken?: QuestionToken | undefined; + /** @deprecated A shorthand property assignment cannot have an exclamation token */ + readonly exclamationToken?: ExclamationToken | undefined; + } + interface FunctionTypeNode { + /** @deprecated A function type cannot have modifiers */ + readonly modifiers?: NodeArray | undefined; + } + interface NodeFactory { + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createParameterDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateParameterDeclaration(node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createPropertyDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updatePropertyDeclaration(node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createMethodDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateMethodDeclaration(node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + /** + * @deprecated This node does not support Decorators. Callers should use an overload that does not accept a `decorators` parameter. + */ + createConstructorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + /** + * @deprecated This node does not support Decorators. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateConstructorDeclaration(node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createGetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateGetAccessorDeclaration(node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createSetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateSetAccessorDeclaration(node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createIndexSignature(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + /** + * @deprecated Decorators and modifiers are no longer supported for this function. Callers should use an overload that does not accept the `decorators` and `modifiers` parameters. + */ + updateIndexSignature(node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + /** + * @deprecated Decorators and modifiers are no longer supported for this function. Callers should use an overload that does not accept the `decorators` and `modifiers` parameters. + */ + createClassStaticBlockDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createClassExpression(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassExpression(node: ClassExpression, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createFunctionDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateFunctionDeclaration(node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createClassDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassDeclaration(node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createInterfaceDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createTypeAliasDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createEnumDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateEnumDeclaration(node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createModuleDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateModuleDeclaration(node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createImportEqualsDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createImportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateImportDeclaration(node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createExportAssignment(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateExportAssignment(node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createExportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateExportDeclaration(node: ExportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; + } +} export = ts; \ No newline at end of file diff --git a/tsserver/typescript.js b/tsserver/typescript.js index 8f41c15f..49899ec4 100644 --- a/tsserver/typescript.js +++ b/tsserver/typescript.js @@ -290,11 +290,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.7"; + ts.versionMajorMinor = "4.8"; // 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 = "4.7.2"; + ts.version = "4.8.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -500,8 +500,10 @@ var ts; return true; } ts.every = every; - function find(array, predicate) { - for (var i = 0; i < array.length; i++) { + function find(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { var value = array[i]; if (predicate(value, i)) { return value; @@ -510,8 +512,10 @@ var ts; return undefined; } ts.find = find; - function findLast(array, predicate) { - for (var i = array.length - 1; i >= 0; i--) { + function findLast(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { var value = array[i]; if (predicate(value, i)) { return value; @@ -522,7 +526,9 @@ var ts; ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate, startIndex) { - for (var i = startIndex || 0; i < array.length; i++) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -531,7 +537,9 @@ var ts; } ts.findIndex = findIndex; function findLastIndex(array, predicate, startIndex) { - for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { if (predicate(array[i], i)) { return i; } @@ -1309,7 +1317,7 @@ var ts; * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return array.length === 0 ? undefined : array[0]; + return array === undefined || array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -1321,7 +1329,7 @@ var ts; * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return array.length === 0 ? undefined : array[array.length - 1]; + return array === undefined || array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -1662,6 +1670,43 @@ var ts; return createMultiMap(); } ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; + function createQueue(items) { + var elements = (items === null || items === void 0 ? void 0 : items.slice()) || []; + var headIndex = 0; + function isEmpty() { + return headIndex === elements.length; + } + function enqueue() { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + elements.push.apply(elements, items); + } + function dequeue() { + if (isEmpty()) { + throw new Error("Queue is empty"); + } + var result = elements[headIndex]; + elements[headIndex] = undefined; // Don't keep referencing dequeued item + headIndex++; + // If more than half of the queue is empty, copy the remaining elements to the + // front and shrink the array (unless we'd be saving fewer than 100 slots) + if (headIndex > 100 && headIndex > (elements.length >> 1)) { + var newLength = elements.length - headIndex; + elements.copyWithin(/*target*/ 0, /*start*/ headIndex); + elements.length = newLength; + headIndex = 0; + } + return result; + } + return { + enqueue: enqueue, + dequeue: dequeue, + isEmpty: isEmpty, + }; + } + ts.createQueue = createQueue; /** * Creates a Set with custom equality and hash code functionality. This is useful when you * want to use something looser than object identity - e.g. "has the same span". @@ -1850,6 +1895,10 @@ var ts; /** Does nothing. */ function noop(_) { } ts.noop = noop; + ts.noopPush = { + push: noop, + length: 0 + }; /** Do nothing and return false */ function returnFalse() { return false; @@ -2205,7 +2254,7 @@ var ts; * and 1 insertion/deletion at 3 characters) */ function getSpellingSuggestion(name, candidates, getName) { - var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var maximumLengthDifference = Math.max(2, Math.floor(name.length * 0.34)); var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother. var bestCandidate; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -2432,6 +2481,7 @@ var ts; startsWith(candidate, prefix) && endsWith(candidate, suffix); } + ts.isPatternMatch = isPatternMatch; function and(f, g) { return function (arg) { return f(arg) && g(arg); }; } @@ -2624,6 +2674,7 @@ var ts; var currentAssertionLevel = 0 /* AssertionLevel.None */; Debug.currentLogLevel = LogLevel.Warning; Debug.isDebugging = false; + Debug.enableDeprecationWarnings = true; function getTypeScriptVersion() { return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version)); } @@ -2842,7 +2893,7 @@ var ts; return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; } if (isFlags) { - var result = ""; + var result = []; var remainingFlags = value; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; @@ -2850,12 +2901,12 @@ var ts; break; } if (enumValue !== 0 && enumValue & value) { - result = "".concat(result).concat(result ? "|" : "").concat(enumName); + result.push(enumName); remainingFlags &= ~enumValue; } } if (remainingFlags === 0) { - return result; + return result.join("|"); } } else { @@ -2869,7 +2920,15 @@ var ts; return value.toString(); } Debug.formatEnum = formatEnum; + var enumMemberCache = new ts.Map(); function getEnumMembers(enumObject) { + // Assuming enum objects do not change at runtime, we can cache the enum members list + // to reuse later. This saves us from reconstructing this each and every time we call + // a formatting function (which can be expensive for large enums like SyntaxKind). + var existing = enumMemberCache.get(enumObject); + if (existing) { + return existing; + } var result = []; for (var name in enumObject) { var value = enumObject[name]; @@ -2877,7 +2936,9 @@ var ts; result.push([value, name]); } } - return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + var sorted = ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + enumMemberCache.set(enumObject, sorted); + return sorted; } function formatSyntaxKind(kind) { return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); @@ -2923,6 +2984,22 @@ var ts; return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true); } Debug.formatFlowFlags = formatFlowFlags; + function formatRelationComparisonResult(result) { + return formatEnum(result, ts.RelationComparisonResult, /*isFlags*/ true); + } + Debug.formatRelationComparisonResult = formatRelationComparisonResult; + function formatCheckMode(mode) { + return formatEnum(mode, ts.CheckMode, /*isFlags*/ true); + } + Debug.formatCheckMode = formatCheckMode; + function formatSignatureCheckMode(mode) { + return formatEnum(mode, ts.SignatureCheckMode, /*isFlags*/ true); + } + Debug.formatSignatureCheckMode = formatSignatureCheckMode; + function formatTypeFacts(facts) { + return formatEnum(facts, ts.TypeFacts, /*isFlags*/ true); + } + Debug.formatTypeFacts = formatTypeFacts; var isDebugInfoEnabled = false; var extendedDebugModule; function extendedDebug() { @@ -3221,7 +3298,7 @@ var ts; function createWarningDeprecation(name, errorAfter, since, message) { var hasWrittenDeprecation = false; return function () { - if (!hasWrittenDeprecation) { + if (Debug.enableDeprecationWarnings && !hasWrittenDeprecation) { log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message)); hasWrittenDeprecation = true; } @@ -3240,6 +3317,7 @@ var ts; warn ? createWarningDeprecation(name, errorAfter, since, options.message) : ts.noop; } + Debug.createDeprecation = createDeprecation; function wrapFunction(deprecation, func) { return function () { deprecation(); @@ -3247,10 +3325,53 @@ var ts; }; } function deprecate(func, options) { - var deprecation = createDeprecation(getFunctionName(func), options); + var _a; + var deprecation = createDeprecation((_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : getFunctionName(func), options); return wrapFunction(deprecation, func); } Debug.deprecate = deprecate; + function formatVariance(varianceFlags) { + var variance = varianceFlags & 7 /* VarianceFlags.VarianceMask */; + var result = variance === 0 /* VarianceFlags.Invariant */ ? "in out" : + variance === 3 /* VarianceFlags.Bivariant */ ? "[bivariant]" : + variance === 2 /* VarianceFlags.Contravariant */ ? "in" : + variance === 1 /* VarianceFlags.Covariant */ ? "out" : + variance === 4 /* VarianceFlags.Independent */ ? "[independent]" : ""; + if (varianceFlags & 8 /* VarianceFlags.Unmeasurable */) { + result += " (unmeasurable)"; + } + else if (varianceFlags & 16 /* VarianceFlags.Unreliable */) { + result += " (unreliable)"; + } + return result; + } + Debug.formatVariance = formatVariance; + var DebugTypeMapper = /** @class */ (function () { + function DebugTypeMapper() { + } + DebugTypeMapper.prototype.__debugToString = function () { + var _a; + type(this); + switch (this.kind) { + case 3 /* TypeMapKind.Function */: return ((_a = this.debugInfo) === null || _a === void 0 ? void 0 : _a.call(this)) || "(function mapper)"; + case 0 /* TypeMapKind.Simple */: return "".concat(this.source.__debugTypeToString(), " -> ").concat(this.target.__debugTypeToString()); + case 1 /* TypeMapKind.Array */: return ts.zipWith(this.sources, this.targets || ts.map(this.sources, function () { return "any"; }), function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(typeof t === "string" ? t : t.__debugTypeToString()); }).join(", "); + case 2 /* TypeMapKind.Deferred */: return ts.zipWith(this.sources, this.targets, function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(t().__debugTypeToString()); }).join(", "); + case 5 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: return "m1: ".concat(this.mapper1.__debugToString().split("\n").join("\n "), "\nm2: ").concat(this.mapper2.__debugToString().split("\n").join("\n ")); + default: return assertNever(this); + } + }; + return DebugTypeMapper; + }()); + Debug.DebugTypeMapper = DebugTypeMapper; + function attachDebugPrototypeIfDebug(mapper) { + if (Debug.isDebugging) { + return Object.setPrototypeOf(mapper, DebugTypeMapper.prototype); + } + return mapper; + } + Debug.attachDebugPrototypeIfDebug = attachDebugPrototypeIfDebug; })(Debug = ts.Debug || (ts.Debug = {})); })(ts || (ts = {})); /* @internal */ @@ -3992,9 +4113,9 @@ var ts; eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } tracingEnabled.push = push; - function pop() { + function pop(results) { ts.Debug.assert(eventStack.length > 0); - writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); + writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp(), results); eventStack.length--; } tracingEnabled.pop = pop; @@ -4008,14 +4129,15 @@ var ts; tracingEnabled.popAll = popAll; // sample every 10ms var sampleInterval = 1000 * 10; - function writeStackEvent(index, endTime) { + function writeStackEvent(index, endTime, results) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { + ts.Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`"); writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } // test if [time,endTime) straddles a sampling point else if (sampleInterval - (time % sampleInterval) <= endTime - time) { - writeEvent("X", phase, name, args, "\"dur\":".concat(endTime - time), time); + writeEvent("X", phase, name, __assign(__assign({}, args), { results: results }), "\"dur\":".concat(endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { @@ -4514,6 +4636,7 @@ var ts; SyntaxKind[SyntaxKind["JSDocFunctionType"] = 317] = "JSDocFunctionType"; SyntaxKind[SyntaxKind["JSDocVariadicType"] = 318] = "JSDocVariadicType"; SyntaxKind[SyntaxKind["JSDocNamepathType"] = 319] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; /** @deprecated Use SyntaxKind.JSDoc */ SyntaxKind[SyntaxKind["JSDocComment"] = 320] = "JSDocComment"; SyntaxKind[SyntaxKind["JSDocText"] = 321] = "JSDocText"; @@ -4588,7 +4711,6 @@ var ts; SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 347] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 126] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 160] = "LastContextualKeyword"; - SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4662,6 +4784,7 @@ var ts; ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["In"] = 32768] = "In"; ModifierFlags[ModifierFlags["Out"] = 65536] = "Out"; + ModifierFlags[ModifierFlags["Decorator"] = 131072] = "Decorator"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. @@ -4669,7 +4792,8 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 116958] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 125951] = "All"; + ModifierFlags[ModifierFlags["All"] = 257023] = "All"; + ModifierFlags[ModifierFlags["Modifier"] = 125951] = "Modifier"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4854,6 +4978,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + NodeBuilderFlags[NodeBuilderFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; @@ -4894,6 +5019,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + TypeFormatFlags[TypeFormatFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -4905,7 +5031,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 848330091] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -5294,6 +5420,11 @@ var ts; // Flags that require TypeFlags.Union /* @internal */ ObjectFlags[ObjectFlags["ContainsIntersections"] = 16777216] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnionComputed"] = 33554432] = "IsUnknownLikeUnionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnion"] = 67108864] = "IsUnknownLikeUnion"; + /* @internal */ // Flags that require TypeFlags.Intersection /* @internal */ ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 16777216] = "IsNeverIntersectionComputed"; @@ -5379,9 +5510,10 @@ var ts; (function (TypeMapKind) { TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple"; TypeMapKind[TypeMapKind["Array"] = 1] = "Array"; - TypeMapKind[TypeMapKind["Function"] = 2] = "Function"; - TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite"; - TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged"; + TypeMapKind[TypeMapKind["Deferred"] = 2] = "Deferred"; + TypeMapKind[TypeMapKind["Function"] = 3] = "Function"; + TypeMapKind[TypeMapKind["Composite"] = 4] = "Composite"; + TypeMapKind[TypeMapKind["Merged"] = 5] = "Merged"; })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {})); var InferencePriority; (function (InferencePriority) { @@ -5760,25 +5892,24 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 4096] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; - TransformFlags[TransformFlags["ContainsLexicalSuper"] = 33554432] = "ContainsLexicalSuper"; - TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 67108864] = "ContainsUpdateExpressionForIdentifier"; - // Please leave this as 1 << 29. - // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. - // It is a good reminder of how much room we have left - TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 8192] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 32768] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 65536] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 131072] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 262144] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 524288] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 1048576] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 2097152] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 4194304] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 8388608] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 16777216] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsDecorators"] = 33554432] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 67108864] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsLexicalSuper"] = 134217728] = "ContainsLexicalSuper"; + TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 268435456] = "ContainsUpdateExpressionForIdentifier"; + TransformFlags[TransformFlags["ContainsPrivateIdentifierInExpression"] = 536870912] = "ContainsPrivateIdentifierInExpression"; + TransformFlags[TransformFlags["HasComputedFlags"] = -2147483648] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; @@ -5797,27 +5928,27 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 591310848] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 591306752] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 574529536] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 570433536] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 589443072] = "ModuleExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = -2147483648] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = -2147483648] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = -2147483648] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = -2072174592] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = -1937940480] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = -1937948672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = -2005057536] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = -2013249536] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = -2147344384] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = -1941676032] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; - TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 33562624] = "ContainsLexicalThisOrSuper"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = -2147278848] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = -2147450880] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = -2146893824] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = -2147483648] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = -2147418112] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = -2147450880] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 134234112] = "ContainsLexicalThisOrSuper"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 33562624] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 134234112] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -5990,7 +6121,7 @@ var ts; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["Modifiers"] = 2359808] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; @@ -6385,7 +6516,7 @@ var ts; }; } function createDirectoryWatcher(dirName, dirPath, fallbackOptions) { - var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName) { + var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName, modifiedTime) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" if (!ts.isString(relativeFileName)) return; @@ -6395,7 +6526,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); + fileCallback(fileName, FileWatcherEventKind.Changed, modifiedTime); } } }, @@ -6449,7 +6580,7 @@ var ts; } else { cache.set(path, { - watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options), + watcher: watchFile(fileName, function (fileName, eventKind, modifiedTime) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind, modifiedTime); }); }, pollingInterval, options), refCount: 1 }); } @@ -6477,7 +6608,8 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + // Pass modified times so tsc --build can use it + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime), modifiedTime); return true; } return false; @@ -6512,7 +6644,7 @@ var ts; */ /*@internal*/ function createDirectoryWatcherSupportingRecursive(_a) { - var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, directoryExists = _a.directoryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, fileSystemEntryExists = _a.fileSystemEntryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; var cache = new ts.Map(); var callbackCache = ts.createMultiMap(); var cacheToUpdateChildWatches = new ts.Map(); @@ -6612,7 +6744,7 @@ var ts; function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) { // Iterate through existing children and update the watches if needed var parentWatcher = cache.get(dirPath); - if (parentWatcher && directoryExists(dirName)) { + if (parentWatcher && fileSystemEntryExists(dirName, 1 /* FileSystemEntryKind.Directory */)) { // Schedule the update and postpone invoke for callbacks scheduleUpdateChildWatches(dirName, dirPath, fileName, options); return; @@ -6685,7 +6817,7 @@ var ts; if (!parentWatcher) return false; var newChildWatches; - var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { + var hasChanges = ts.enumerateInsertsAndDeletes(fileSystemEntryExists(parentDir, 1 /* FileSystemEntryKind.Directory */) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch @@ -6728,17 +6860,19 @@ var ts; })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {})); /*@internal*/ function createFileWatcherCallback(callback) { - return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + return function (_fileName, eventKind, modifiedTime) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", "", modifiedTime); }; } ts.createFileWatcherCallback = createFileWatcherCallback; - function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) { - return function (eventName) { + function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime) { + return function (eventName, _relativeFileName, modifiedTime) { if (eventName === "rename") { - callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + // Check time stamps rather than file system entry checks + modifiedTime || (modifiedTime = getModifiedTime(fileName) || ts.missingFileModifiedTime); + callback(fileName, modifiedTime !== ts.missingFileModifiedTime ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted, modifiedTime); } else { // Change - callback(fileName, FileWatcherEventKind.Changed); + callback(fileName, FileWatcherEventKind.Changed, modifiedTime); } }; } @@ -6762,11 +6896,12 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; + var pollingWatchFile = _a.pollingWatchFile, 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 dynamicPollingWatchFile; var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; + var hitSystemWatcherLimit = false; return { watchFile: watchFile, watchDirectory: watchDirectory @@ -6784,7 +6919,7 @@ var ts; case ts.WatchFileKind.FixedChunkSizePolling: return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: - return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), + return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); case ts.WatchFileKind.UseFsEventsOnParentDirectory: if (!nonPollingWatchFile) { @@ -6845,7 +6980,7 @@ var ts; hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - directoryExists: directoryExists, + fileSystemEntryExists: fileSystemEntryExists, getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories, watchDirectory: nonRecursiveWatchDirectory, realpath: realpath, @@ -6896,6 +7031,124 @@ var ts; }; } } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { + var lastDirectoryPartWithDirectorySeparator; + var lastDirectoryPart; + if (inodeWatching) { + lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substring(fileOrDirectory.lastIndexOf(ts.directorySeparator)); + lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); + } + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + if (watcher) { + watcher.close(); + watcher = undefined; + } + } + }; + function updateWatcher(createWatcher) { + // If watcher is not closed, update it + if (watcher) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + if (hitSystemWatcherLimit) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + try { + var presentWatcher = fsWatchWorker(fileOrDirectory, recursive, inodeWatching ? + callbackChangingToMissingFileSystemEntry : + callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { + callback("rename", ""); + updateWatcher(watchMissingFileSystemEntry); + }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + function callbackChangingToMissingFileSystemEntry(event, relativeName) { + // In some scenarios, file save operation fires event with fileName.ext~ instead of fileName.ext + // To ensure we see the file going missing and coming back up (file delete and then recreated) + // and watches being updated correctly we are calling back with fileName.ext as well as fileName.ext~ + // The worst is we have fired event that was not needed but we wont miss any changes + // especially in cases where file goes missing and watches wrong inode + var originalRelativeName; + if (relativeName && ts.endsWith(relativeName, "~")) { + originalRelativeName = relativeName; + relativeName = relativeName.slice(0, relativeName.length - 1); + } + // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations + // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path + if (event === "rename" && + (!relativeName || + relativeName === lastDirectoryPart || + ts.endsWith(relativeName, lastDirectoryPartWithDirectorySeparator))) { + var modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime; + if (originalRelativeName) + callback(event, originalRelativeName, modifiedTime); + callback(event, relativeName, modifiedTime); + if (inodeWatching) { + // If this was rename event, inode has changed means we need to update watcher + updateWatcher(modifiedTime === ts.missingFileModifiedTime ? watchMissingFileSystemEntry : watchPresentFileSystemEntry); + } + else if (modifiedTime === ts.missingFileModifiedTime) { + updateWatcher(watchMissingFileSystemEntry); + } + } + else { + if (originalRelativeName) + callback(event, originalRelativeName); + callback(event, relativeName); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return watchFile(fileOrDirectory, function (_fileName, eventKind, modifiedTime) { + if (eventKind === FileWatcherEventKind.Created) { + modifiedTime || (modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime); + if (modifiedTime !== ts.missingFileModifiedTime) { + callback("rename", "", modifiedTime); + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + updateWatcher(watchPresentFileSystemEntry); + } + } + }, fallbackPollingInterval, fallbackOptions); + } + } } ts.createSystemWatchFunctions = createSystemWatchFunctions; /** @@ -6933,7 +7186,6 @@ var ts; // not actually work. var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { - var _a; var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/; var _fs = require("fs"); var _path = require("path"); @@ -6943,41 +7195,41 @@ var ts; try { _crypto = require("crypto"); } - catch (_b) { + catch (_a) { _crypto = undefined; } var activeSession; var profilePath = "./profile.cpuprofile"; - var hitSystemWatcherLimit = false; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; + var fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); - var _c = createSystemWatchFunctions({ + var _b = createSystemWatchFunctions({ pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames), getModifiedTime: getModifiedTime, setTimeout: setTimeout, clearTimeout: clearTimeout, - fsWatch: fsWatch, + fsWatchWorker: fsWatchWorker, useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - fileExists: fileExists, + fileSystemEntryExists: fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch, - directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, realpath: realpath, 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); }, - }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; + inodeWatching: isLinuxOrMacOs, + sysLog: sysLog, + }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -7226,110 +7478,14 @@ var ts; // File changed eventKind = FileWatcherEventKind.Changed; } - callback(fileName, eventKind); + callback(fileName, eventKind, curr.mtime); } } - function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { - var options; - var lastDirectoryPartWithDirectorySeparator; - var lastDirectoryPart; - if (isLinuxOrMacOs) { - lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator)); - lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); - } - /** Watcher for the file system entry depending on whether it is missing or present */ - var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? - watchMissingFileSystemEntry() : - watchPresentFileSystemEntry(); - return { - close: function () { - // Close the watcher (either existing file system entry watcher or missing file system entry watcher) - watcher.close(); - watcher = undefined; - } - }; - /** - * Invoke the callback with rename and update the watcher if not closed - * @param createWatcher - */ - function invokeCallbackAndUpdateWatcher(createWatcher) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); - // Call the callback for current directory - callback("rename", ""); - // If watcher is not closed, update it - if (watcher) { - watcher.close(); - watcher = createWatcher(); - } - } - /** - * Watch the file or directory that is currently present - * and when the watched file or directory is deleted, switch to missing file system entry watcher - */ - function watchPresentFileSystemEntry() { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows - // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) - if (options === undefined) { - if (fsSupportsRecursiveFsWatch) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - } - if (hitSystemWatcherLimit) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - try { - var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ? - callbackChangingToMissingFileSystemEntry : - callback); - // Watch the missing file or directory or error - presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); - return presentWatcher; - } - catch (e) { - // Catch the exception and use polling instead - // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - // so instead of throwing error, use fs.watchFile - hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - } - function callbackChangingToMissingFileSystemEntry(event, relativeName) { - // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations - // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path - return event === "rename" && - (!relativeName || - relativeName === lastDirectoryPart || - (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && - !fileSystemEntryExists(fileOrDirectory, entryKind) ? - invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : - callback(event, relativeName); - } - /** - * Watch the file or directory using fs.watchFile since fs.watch threw exception - * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - */ - function watchPresentFileSystemEntryWithFsWatchFile() { - return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); - } - /** - * Watch the file or directory that is missing - * and switch to existing file or directory when the missing filesystem entry is created - */ - function watchMissingFileSystemEntry() { - return watchFile(fileOrDirectory, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { - // Call the callback for current file or directory - // For now it could be callback for the inner directory creation, - // but just return current directory, better than current no-op - invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); - } - }, fallbackPollingInterval, fallbackOptions); - } + function fsWatchWorker(fileOrDirectory, recursive, callback) { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + return _fs.watch(fileOrDirectory, fsSupportsRecursiveFsWatch ? + { persistent: true, recursive: !!recursive } : { persistent: true }, callback); } function readFileWorker(fileName, _encoding) { var buffer; @@ -7466,9 +7622,12 @@ var ts; function getDirectories(path) { return getAccessibleFileSystemEntries(path).directories.slice(); } + function fsRealPathHandlingLongPath(path) { + return path.length < 260 ? _fs.realpathSync.native(path) : _fs.realpathSync(path); + } function realpath(path) { try { - return realpathSync(path); + return fsRealpath(path); } catch (_a) { return path; @@ -7476,12 +7635,19 @@ var ts; } function getModifiedTime(path) { var _a; + // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve + // the CPU time performance. + var originalStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; try { return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime; } catch (e) { return undefined; } + finally { + Error.stackTraceLimit = originalStackTraceLimit; + } } function setModifiedTime(path, time) { try { @@ -8336,6 +8502,7 @@ var ts; String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + or_JSX_element_expected: diag(1145, ts.DiagnosticCategory.Error, "or_JSX_element_expected_1145", "'{' or JSX element expected."), Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), @@ -8389,6 +8556,7 @@ var ts; Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), _0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module: diag(1208, ts.DiagnosticCategory.Error, "_0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_imp_1208", "'{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module."), + Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0: diag(1209, ts.DiagnosticCategory.Error, "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209", "Invalid optional chain from new expression. Did you mean to call '{0}()'?"), Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode: diag(1210, ts.DiagnosticCategory.Error, "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210", "Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of '{0}'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode."), A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), @@ -8481,6 +8649,7 @@ var ts; infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Class_constructor_may_not_be_an_accessor: diag(1341, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_an_accessor_1341", "Class constructor may not be an accessor."), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), @@ -8499,6 +8668,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Class_constructor_may_not_be_a_generator: diag(1360, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_a_generator_1360", "Class constructor may not be a generator."), _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."), _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), @@ -8583,18 +8753,30 @@ var ts; Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, ts.DiagnosticCategory.Message, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."), Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments: diag(1450, ts.DiagnosticCategory.Message, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional assertion as arguments"), Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"), - Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "Resolution modes are only supported when `moduleResolution` is `node16` or `nodenext`."), + resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "'resolution-mode' assertions are only supported when `moduleResolution` is `node16` or `nodenext`."), resolution_mode_should_be_either_require_or_import: diag(1453, ts.DiagnosticCategory.Error, "resolution_mode_should_be_either_require_or_import_1453", "`resolution-mode` should be either `require` or `import`."), resolution_mode_can_only_be_set_for_type_only_imports: diag(1454, ts.DiagnosticCategory.Error, "resolution_mode_can_only_be_set_for_type_only_imports_1454", "`resolution-mode` can only be set for type-only imports."), resolution_mode_is_the_only_valid_key_for_type_import_assertions: diag(1455, ts.DiagnosticCategory.Error, "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455", "`resolution-mode` is the only valid key for type import assertions."), Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require: diag(1456, ts.DiagnosticCategory.Error, "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456", "Type import assertions should have exactly one key - `resolution-mode` - with value `import` or `require`."), + Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk: diag(1457, ts.DiagnosticCategory.Message, "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457", "Matched by default include pattern '**/*'"), + File_is_ECMAScript_module_because_0_has_field_type_with_value_module: diag(1458, ts.DiagnosticCategory.Message, "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458", "File is ECMAScript module because '{0}' has field \"type\" with value \"module\""), + File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module: diag(1459, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459", "File is CommonJS module because '{0}' has field \"type\" whose value is not \"module\""), + File_is_CommonJS_module_because_0_does_not_have_field_type: diag(1460, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_does_not_have_field_type_1460", "File is CommonJS module because '{0}' does not have field \"type\""), + File_is_CommonJS_module_because_package_json_was_not_found: diag(1461, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_package_json_was_not_found_1461", "File is CommonJS module because 'package.json' was not found"), The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."), - Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."), + Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported with 'require'. Use an ECMAScript import instead."), catch_or_finally_expected: diag(1472, ts.DiagnosticCategory.Error, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), An_import_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1473, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473", "An import declaration can only be used at the top level of a module."), An_export_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1474, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474", "An export declaration can only be used at the top level of a module."), Control_what_method_is_used_to_detect_module_format_JS_files: diag(1475, ts.DiagnosticCategory.Message, "Control_what_method_is_used_to_detect_module_format_JS_files_1475", "Control what method is used to detect module-format JS files."), auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules: diag(1476, ts.DiagnosticCategory.Message, "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476", "\"auto\": Treat files with imports, exports, import.meta, jsx (with jsx: react-jsx), or esm format (with module: node16+) as modules."), + An_instantiation_expression_cannot_be_followed_by_a_property_access: diag(1477, ts.DiagnosticCategory.Error, "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477", "An instantiation expression cannot be followed by a property access."), + Identifier_or_string_literal_expected: diag(1478, ts.DiagnosticCategory.Error, "Identifier_or_string_literal_expected_1478", "Identifier or string literal expected."), + The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead: diag(1479, ts.DiagnosticCategory.Error, "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479", "The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import(\"{0}\")' call instead."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module: diag(1480, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480", "To convert this file to an ECMAScript module, change its file extension to '{0}' or create a local package.json file with `{ \"type\": \"module\" }`."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1: diag(1481, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481", "To convert this file to an ECMAScript module, change its file extension to '{0}', or add the field `\"type\": \"module\"` to '{1}'."), + To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0: diag(1482, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482", "To convert this file to an ECMAScript module, add the field `\"type\": \"module\"` to '{0}'."), + To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module: diag(1483, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483", "To convert this file to an ECMAScript module, create a local package.json file with `{ \"type\": \"module\" }`."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8603,8 +8785,11 @@ var ts; Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."), The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."), + This_type_parameter_might_need_an_extends_0_constraint: diag(2208, ts.DiagnosticCategory.Error, "This_type_parameter_might_need_an_extends_0_constraint_2208", "This type parameter might need an `extends {0}` constraint."), The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2209, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209", "The project root is ambiguous, but is required to resolve export map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2210, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210", "The project root is ambiguous, but is required to resolve import map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), + Add_extends_constraint: diag(2211, ts.DiagnosticCategory.Message, "Add_extends_constraint_2211", "Add `extends` constraint."), + Add_extends_constraint_to_all_type_parameters: diag(2212, ts.DiagnosticCategory.Message, "Add_extends_constraint_to_all_type_parameters_2212", "Add `extends` constraint to all type parameters"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -8805,6 +8990,7 @@ var ts; Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + A_tuple_type_cannot_be_indexed_with_a_negative_value: diag(2514, ts.DiagnosticCategory.Error, "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514", "A tuple type cannot be indexed with a negative value."), Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), @@ -9087,6 +9273,12 @@ var ts; Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls: diag(2836, ts.DiagnosticCategory.Error, "Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls_2836", "Import assertions are not allowed on statements that transpile to commonjs 'require' calls."), Import_assertion_values_must_be_string_literal_expressions: diag(2837, ts.DiagnosticCategory.Error, "Import_assertion_values_must_be_string_literal_expressions_2837", "Import assertion values must be string literal expressions."), All_declarations_of_0_must_have_identical_constraints: diag(2838, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_constraints_2838", "All declarations of '{0}' must have identical constraints."), + This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value: diag(2839, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839", "This condition will always return '{0}' since JavaScript compares objects by reference, not value."), + An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes: diag(2840, ts.DiagnosticCategory.Error, "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840", "An interface cannot extend a primitive type like '{0}'; an interface can only extend named types and classes"), + The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(2841, ts.DiagnosticCategory.Error, "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841", "The type of this expression cannot be named without a 'resolution-mode' assertion, which is an unstable feature. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + _0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation: diag(2842, ts.DiagnosticCategory.Error, "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842", "'{0}' is an unused renaming of '{1}'. Did you intend to use it as a type annotation?"), + We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here: diag(2843, ts.DiagnosticCategory.Error, "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843", "We can only write a type for '{0}' by adding a type for the entire parameter here."), + Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2844, ts.DiagnosticCategory.Error, "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844", "Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -9194,7 +9386,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), - Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "Resolution mode assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "'resolution-mode' assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -9497,8 +9689,8 @@ var ts; Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Referenced_project_0_may_not_disable_emit: diag(6310, ts.DiagnosticCategory.Error, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."), - Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), - Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_1_is_older_than_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350", "Project '{0}' is out of date because output '{1}' is older than input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than output '{2}'"), Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), @@ -9542,6 +9734,8 @@ var ts; Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6396, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6397, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."), + 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"), 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."), @@ -9782,6 +9976,8 @@ var ts; Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, ts.DiagnosticCategory.Error, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."), The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."), + You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder: diag(8035, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035", "You cannot rename elements that are defined in a 'node_modules' folder."), + You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -10052,6 +10248,9 @@ var ts; For_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, ts.DiagnosticCategory.Error, "For_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'For await' loops cannot be used inside a class static block."), Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, ts.DiagnosticCategory.Error, "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."), A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, ts.DiagnosticCategory.Error, "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."), + _0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation: diag(18042, ts.DiagnosticCategory.Error, "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042", "'{0}' is a type and cannot be imported in JavaScript files. Use '{1}' in a JSDoc type annotation."), + Types_cannot_appear_in_export_declarations_in_JavaScript_files: diag(18043, ts.DiagnosticCategory.Error, "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043", "Types cannot appear in export declarations in JavaScript files."), + _0_is_automatically_exported_here: diag(18044, ts.DiagnosticCategory.Message, "_0_is_automatically_exported_here_18044", "'{0}' is automatically exported here."), }; })(ts || (ts = {})); var ts; @@ -12939,6 +13138,18 @@ var ts; } } ts.getAssignedName = getAssignedName; + function getDecorators(node) { + if (ts.hasDecorators(node)) { + return ts.filter(node.modifiers, ts.isDecorator); + } + } + ts.getDecorators = getDecorators; + function getModifiers(node) { + if (ts.hasSyntacticModifier(node, 125951 /* ModifierFlags.Modifier */)) { + return ts.filter(node.modifiers, isModifier); + } + } + ts.getModifiers = getModifiers; function getJSDocParameterTagsWorker(param, noCache) { if (param.name) { if (ts.isIdentifier(param.name)) { @@ -13209,6 +13420,12 @@ var ts; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + * + * This does *not* return type parameters from a jsdoc reference to a generic type, eg + * + * type Id = (x: T) => T + * /** @type {Id} / + * function id(x) { return x } */ function getEffectiveTypeParameterDeclarations(node) { if (ts.isJSDocSignature(node)) { @@ -13221,6 +13438,9 @@ var ts; if (node.typeParameters) { return node.typeParameters; } + if (ts.canHaveIllegalTypeParameters(node) && node.typeParameters) { + return node.typeParameters; + } if (ts.isInJSFile(node)) { var decls = ts.getJSDocTypeParameterDeclarations(node); if (decls.length) { @@ -13397,6 +13617,19 @@ var ts; return isLiteralKind(node.kind); } ts.isLiteralExpression = isLiteralExpression; + /** @internal */ + function isLiteralExpressionOfObject(node) { + switch (node.kind) { + case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 13 /* SyntaxKind.RegularExpressionLiteral */: + case 213 /* SyntaxKind.FunctionExpression */: + case 226 /* SyntaxKind.ClassExpression */: + return true; + } + return false; + } + ts.isLiteralExpressionOfObject = isLiteralExpressionOfObject; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { @@ -13606,6 +13839,10 @@ var ts; } ts.isMethodOrAccessor = isMethodOrAccessor; // Type members + function isModifierLike(node) { + return isModifier(node) || ts.isDecorator(node); + } + ts.isModifierLike = isModifierLike; function isTypeElement(node) { var kind = node.kind; return kind === 175 /* SyntaxKind.ConstructSignature */ @@ -14215,7 +14452,6 @@ var ts; case 254 /* SyntaxKind.VariableDeclaration */: case 164 /* SyntaxKind.Parameter */: case 203 /* SyntaxKind.BindingElement */: - case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: case 296 /* SyntaxKind.PropertyAssignment */: case 299 /* SyntaxKind.EnumMember */: @@ -14267,6 +14503,16 @@ var ts; return node.kind === 324 /* SyntaxKind.JSDocLink */ || node.kind === 325 /* SyntaxKind.JSDocLinkCode */ || node.kind === 326 /* SyntaxKind.JSDocLinkPlain */; } ts.isJSDocLinkLike = isJSDocLinkLike; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; // #endregion })(ts || (ts = {})); /* @internal */ @@ -14747,10 +14993,11 @@ var ts; } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { - if (nodeIsMissing(node) || !node.decorators) { + var lastDecorator = !nodeIsMissing(node) && ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + if (!lastDecorator) { return getTokenPosOfNode(node, sourceFile); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastDecorator.end); } ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { @@ -16136,7 +16383,7 @@ var ts; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { - return node.decorators !== undefined + return hasDecorators(node) && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; @@ -16212,6 +16459,8 @@ var ts; case 218 /* SyntaxKind.AwaitExpression */: case 231 /* SyntaxKind.MetaProperty */: return true; + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + return !ts.isHeritageClause(node.parent); case 161 /* SyntaxKind.QualifiedName */: while (node.parent.kind === 161 /* SyntaxKind.QualifiedName */) { node = node.parent; @@ -16383,9 +16632,6 @@ var ts; } ts.isVariableDeclarationInitializedToBareOrAccessedRequire = isVariableDeclarationInitializedToBareOrAccessedRequire; function isVariableDeclarationInitializedWithRequireHelper(node, allowAccessedRequire) { - if (node.kind === 203 /* SyntaxKind.BindingElement */) { - node = node.parent.parent; - } return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, /*requireStringLiteralLikeArgument*/ true); @@ -17037,16 +17283,6 @@ var ts; return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function hasRestParameter(s) { - var last = ts.lastOrUndefined(s.parameters); - return !!last && isRestParameter(last); - } - ts.hasRestParameter = hasRestParameter; - function isRestParameter(node) { - var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; - } - ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { return !!node.typeArguments; } @@ -17168,6 +17404,12 @@ var ts; return [child, node]; } ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild; + function skipTypeParentheses(node) { + while (ts.isParenthesizedTypeNode(node)) + node = node.type; + return node; + } + ts.skipTypeParentheses = skipTypeParentheses; function skipParentheses(node, excludeJSDocTypeAssertions) { var flags = excludeJSDocTypeAssertions ? 1 /* OuterExpressionKinds.Parentheses */ | 16 /* OuterExpressionKinds.ExcludeJSDocTypeAssertion */ : @@ -18914,6 +19156,10 @@ var ts; return hasEffectiveModifier(node, 64 /* ModifierFlags.Readonly */); } ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier; + function hasDecorators(node) { + return hasSyntacticModifier(node, 131072 /* ModifierFlags.Decorator */); + } + ts.hasDecorators = hasDecorators; function getSelectedEffectiveModifierFlags(node, flags) { return getEffectiveModifierFlags(node) & flags; } @@ -18991,7 +19237,7 @@ var ts; * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc. */ function getSyntacticModifierFlagsNoCache(node) { - var flags = modifiersToFlags(node.modifiers); + var flags = ts.canHaveModifiers(node) ? modifiersToFlags(node.modifiers) : 0 /* ModifierFlags.None */; if (node.flags & 4 /* NodeFlags.NestedNamespace */ || (node.kind === 79 /* SyntaxKind.Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* ModifierFlags.Export */; } @@ -19025,6 +19271,7 @@ var ts; case 159 /* SyntaxKind.OverrideKeyword */: return 16384 /* ModifierFlags.Override */; case 101 /* SyntaxKind.InKeyword */: return 32768 /* ModifierFlags.In */; case 144 /* SyntaxKind.OutKeyword */: return 65536 /* ModifierFlags.Out */; + case 165 /* SyntaxKind.Decorator */: return 131072 /* ModifierFlags.Decorator */; } return 0 /* ModifierFlags.None */; } @@ -19402,8 +19649,9 @@ var ts; * Moves the start position of a range past any decorators. */ function moveRangePastDecorators(node) { - return node.decorators && node.decorators.length > 0 - ? moveRangePos(node, node.decorators.end) + var lastDecorator = ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + return lastDecorator && !positionIsSynthesized(lastDecorator.end) + ? moveRangePos(node, lastDecorator.end) : node; } ts.moveRangePastDecorators = moveRangePastDecorators; @@ -19411,8 +19659,9 @@ var ts; * Moves the start position of a range past any decorators or modifiers. */ function moveRangePastModifiers(node) { - return node.modifiers && node.modifiers.length > 0 - ? moveRangePos(node, node.modifiers.end) + var lastModifier = ts.canHaveModifiers(node) ? ts.lastOrUndefined(node.modifiers) : undefined; + return lastModifier && !positionIsSynthesized(lastModifier.end) + ? moveRangePos(node, lastModifier.end) : moveRangePastDecorators(node); } ts.moveRangePastModifiers = moveRangePastModifiers; @@ -19534,7 +19783,8 @@ var ts; function getDeclarationModifierFlagsFromSymbol(s, isWrite) { if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 173 /* SyntaxKind.SetAccessor */; })) || s.valueDeclaration; + var declaration = (isWrite && s.declarations && ts.find(s.declarations, ts.isSetAccessorDeclaration)) + || (s.flags & 32768 /* SymbolFlags.GetAccessor */ && ts.find(s.declarations, ts.isGetAccessorDeclaration)) || s.valueDeclaration; var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* SymbolFlags.Class */ ? flags : flags & ~28 /* ModifierFlags.AccessibilityModifier */; } @@ -20207,8 +20457,9 @@ var ts; */ function isFileForcedToBeModuleByFormat(file) { // Excludes declaration files - they still require an explicit `export {}` or the like - // for back compat purposes. - return file.impliedNodeFormat === ts.ModuleKind.ESNext && !file.isDeclarationFile ? true : undefined; + // for back compat purposes. The only non-declaration files _not_ forced to be a module are `.js` files + // that aren't esm-mode (meaning not in a `type: module` scope). + return (file.impliedNodeFormat === ts.ModuleKind.ESNext || (ts.fileExtensionIsOneOf(file.fileName, [".cjs" /* Extension.Cjs */, ".cts" /* Extension.Cts */, ".mjs" /* Extension.Mjs */, ".mts" /* Extension.Mts */]))) && !file.isDeclarationFile ? true : undefined; } function getSetExternalModuleIndicator(options) { // TODO: Should this callback be cached? @@ -20216,7 +20467,7 @@ var ts; case ts.ModuleDetectionKind.Force: // All non-declaration files are modules, declaration files still do the usual isFileProbablyExternalModule return function (file) { - file.externalModuleIndicator = !file.isDeclarationFile || ts.isFileProbablyExternalModule(file); + file.externalModuleIndicator = ts.isFileProbablyExternalModule(file) || !file.isDeclarationFile || undefined; }; case ts.ModuleDetectionKind.Legacy: // Files are modules if they have imports, exports, or import.meta @@ -20231,10 +20482,7 @@ var ts; if (options.jsx === 4 /* JsxEmit.ReactJSX */ || options.jsx === 5 /* JsxEmit.ReactJSXDev */) { checks.push(isFileModuleFromUsingJSXTag); } - var moduleKind = getEmitModuleKind(options); - if (moduleKind === ts.ModuleKind.Node16 || moduleKind === ts.ModuleKind.NodeNext) { - checks.push(isFileForcedToBeModuleByFormat); - } + checks.push(isFileForcedToBeModuleByFormat); var combined_1 = ts.or.apply(void 0, checks); var callback = function (file) { return void (file.externalModuleIndicator = combined_1(file)); }; return callback; @@ -20276,7 +20524,8 @@ var ts; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; function getEmitModuleDetectionKind(options) { - return options.moduleDetection || ts.ModuleDetectionKind.Auto; + return options.moduleDetection || + (getEmitModuleKind(options) === ts.ModuleKind.Node16 || getEmitModuleKind(options) === ts.ModuleKind.NodeNext ? ts.ModuleDetectionKind.Force : ts.ModuleDetectionKind.Auto); } ts.getEmitModuleDetectionKind = getEmitModuleDetectionKind; function hasJsonModuleEmitEnabled(options) { @@ -20359,6 +20608,10 @@ var ts; return optionsHaveChanges(oldOptions, newOptions, ts.affectsEmitOptionDeclarations); } ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit; + function compilerOptionsAffectDeclarationPath(newOptions, oldOptions) { + return optionsHaveChanges(oldOptions, newOptions, ts.affectsDeclarationPathOptionDeclarations); + } + ts.compilerOptionsAffectDeclarationPath = compilerOptionsAffectDeclarationPath; function getCompilerOptionValue(options, option) { return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; } @@ -21299,8 +21552,12 @@ var ts; return node.parent.templateSpans; case 233 /* SyntaxKind.TemplateSpan */: return node.parent.templateSpans; - case 165 /* SyntaxKind.Decorator */: - return node.parent.decorators; + case 165 /* SyntaxKind.Decorator */: { + var parent_2 = node.parent; + return ts.canHaveDecorators(parent_2) ? parent_2.modifiers : + ts.canHaveIllegalDecorators(parent_2) ? parent_2.illegalDecorators : + undefined; + } case 291 /* SyntaxKind.HeritageClause */: return node.parent.heritageClauses; } @@ -21814,7 +22071,7 @@ var ts; * Wraps an expression in parentheses if it is needed in order to use the expression for * property or element access. */ - function parenthesizeLeftSideOfAccess(expression) { + function parenthesizeLeftSideOfAccess(expression, optionalChain) { // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exception is: // @@ -21823,7 +22080,8 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments) + && (optionalChain || !ts.isOptionalChain(emittedExpression))) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -22770,13 +23028,8 @@ var ts; function createBaseNode(kind) { return baseFactory.createBaseNode(kind); } - function createBaseDeclaration(kind, decorators, modifiers) { + function createBaseDeclaration(kind) { var node = createBaseNode(kind); - node.decorators = asNodeArray(decorators); - node.modifiers = asNodeArray(modifiers); - node.transformFlags |= - propagateChildrenFlags(node.decorators) | - propagateChildrenFlags(node.modifiers); // NOTE: The following properties are commonly set by the binder and are added here to // ensure declarations have a stable shape. node.symbol = undefined; // initialized by binder @@ -22785,10 +23038,15 @@ var ts; node.nextContainer = undefined; // initialized by binder return node; } - function createBaseNamedDeclaration(kind, decorators, modifiers, name) { - var node = createBaseDeclaration(kind, decorators, modifiers); + function createBaseNamedDeclaration(kind, modifiers, name) { + var node = createBaseDeclaration(kind); name = asName(name); node.name = name; + if (ts.canHaveModifiers(node)) { + node.modifiers = asNodeArray(modifiers); + node.transformFlags |= propagateChildrenFlags(node.modifiers); + // node.decorators = filter(node.modifiers, isDecorator); + } // The PropertyName of a member is allowed to be `await`. // We don't need to exclude `await` for type signatures since types // don't propagate child flags. @@ -22811,16 +23069,16 @@ var ts; } return node; } - function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.typeParameters = asNodeArray(typeParameters); node.transformFlags |= propagateChildrenFlags(node.typeParameters); if (typeParameters) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.parameters = createNodeArray(parameters); node.type = type; node.transformFlags |= @@ -22828,50 +23086,45 @@ var ts; propagateChildFlags(node.type); if (type) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used for quick info + node.typeArguments = undefined; return node; } - function updateBaseSignatureDeclaration(updated, original) { - // copy children used only for error reporting - if (original.typeArguments) + function finishUpdateBaseSignatureDeclaration(updated, original) { + if (updated !== original) { + // copy children used for quick info updated.typeArguments = original.typeArguments; + } return update(updated, original); } - function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { - var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); + function createBaseFunctionLikeDeclaration(kind, modifiers, name, typeParameters, parameters, type, body) { + var node = createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateBaseFunctionLikeDeclaration(updated, original) { - // copy children used only for error reporting - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - if (original.typeArguments) - updated.typeArguments = original.typeArguments; - return updateBaseSignatureDeclaration(updated, original); - } - function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.heritageClauses = asNodeArray(heritageClauses); node.transformFlags |= propagateChildrenFlags(node.heritageClauses); return node; } - function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses); + function createBaseClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members); return node; } - function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseBindingLikeDeclaration(kind, modifiers, name, initializer) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.initializer = initializer; node.transformFlags |= propagateChildFlags(node.initializer); return node; } - function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) { - var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer); + function createBaseVariableLikeDeclaration(kind, modifiers, name, type, initializer) { + var node = createBaseBindingLikeDeclaration(kind, modifiers, name, initializer); node.type = type; node.transformFlags |= propagateChildFlags(type); if (type) @@ -22967,7 +23220,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 132 /* SyntaxKind.AwaitKeyword */) { - node.transformFlags |= 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } return node; } @@ -23019,7 +23272,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(80 /* SyntaxKind.PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags |= 16777216 /* TransformFlags.ContainsClassFields */; return node; } // @@ -23066,14 +23319,14 @@ var ts; transformFlags = 1 /* TransformFlags.ContainsTypeScript */; break; case 106 /* SyntaxKind.SuperKeyword */: - transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 33554432 /* TransformFlags.ContainsLexicalSuper */; + transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 134217728 /* TransformFlags.ContainsLexicalSuper */; break; case 124 /* SyntaxKind.StaticKeyword */: transformFlags = 1024 /* TransformFlags.ContainsES2015 */; break; case 108 /* SyntaxKind.ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 8192 /* TransformFlags.ContainsLexicalThis */; + transformFlags = 16384 /* TransformFlags.ContainsLexicalThis */; break; } if (transformFlags) { @@ -23171,7 +23424,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 65536 /* TransformFlags.ContainsComputedPropertyName */; + 131072 /* TransformFlags.ContainsComputedPropertyName */; return node; } // @api @@ -23180,41 +23433,19 @@ var ts; ? update(createComputedPropertyName(expression), node) : node; } - function createTypeParameterDeclaration(modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } - var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, - /*decorators*/ undefined, modifiers, name); + // + // Signature elements + // + // @api + function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) { + var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, modifiers, name); node.constraint = constraint; node.default = defaultType; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateTypeParameterDeclaration(node, modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } + // @api + function updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType) { return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint @@ -23223,8 +23454,8 @@ var ts; : node; } // @api - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -23237,32 +23468,32 @@ var ts; if (questionToken) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; if (ts.modifiersToFlags(node.modifiers) & 16476 /* ModifierFlags.ParameterPropertyModifier */) - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; } return node; } // @api - function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } // @api function createDecorator(expression) { var node = createBaseNode(165 /* SyntaxKind.Decorator */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */ | - 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */ | + 33554432 /* TransformFlags.ContainsDecorators */; return node; } // @api @@ -23276,11 +23507,12 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, - /*decorators*/ undefined, modifiers, name); + var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, modifiers, name); node.type = type; node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.initializer = undefined; return node; } // @api @@ -23289,20 +23521,27 @@ var ts; || node.name !== name || node.questionToken !== questionToken || node.type !== type - ? update(createPropertySignature(modifiers, name, questionToken, type), node) + ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) : node; } + function finishUpdatePropertySignature(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.initializer = original.initializer; + } + return update(updated, original); + } // @api - function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, decorators, modifiers, name, type, initializer); + function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 8388608 /* TransformFlags.ContainsClassFields */; + 16777216 /* TransformFlags.ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; @@ -23310,21 +23549,19 @@ var ts; return node; } // @api - function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.modifiers !== modifiers || node.name !== name || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer - ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23337,12 +23574,12 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node; } // @api - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= @@ -23363,12 +23600,13 @@ var ts; else if (asteriskToken) { node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } + // The following properties are used only to report grammar errors + node.exclamationToken = undefined; return node; } // @api - function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.questionToken !== questionToken @@ -23376,80 +23614,123 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } + function finishUpdateMethodDeclaration(updated, original) { + if (updated !== original) { + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api - function createClassStaticBlockDeclaration(decorators, modifiers, body) { - var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, decorators, modifiers, + function createClassStaticBlockDeclaration(body) { + var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, + /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined); node.body = body; - node.transformFlags = propagateChildFlags(body) | 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags = propagateChildFlags(body) | 16777216 /* TransformFlags.ContainsClassFields */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api - function updateClassStaticBlockDeclaration(node, decorators, modifiers, body) { - return node.decorators !== decorators - || node.modifier !== modifiers - || node.body !== body - ? update(createClassStaticBlockDeclaration(decorators, modifiers, body), node) + function updateClassStaticBlockDeclaration(node, body) { + return node.body !== body + ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) : node; } + function finishUpdateClassStaticBlockDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, decorators, modifiers, + function createConstructorDeclaration(modifiers, parameters, body) { + var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.typeParameters = undefined; + node.type = undefined; return node; } // @api - function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateConstructorDeclaration(node, modifiers, parameters, body) { + return node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node) + ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) : node; } + function finishUpdateConstructorDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, decorators, modifiers, name, + function createGetAccessorDeclaration(modifiers, name, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + return node; } // @api - function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node) + ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) : node; } + function finishUpdateGetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, decorators, modifiers, name, + function createSetAccessorDeclaration(modifiers, name, parameters, body) { + var node = createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + node.type = undefined; + return node; } // @api - function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateSetAccessorDeclaration(node, modifiers, name, parameters, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node) + ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) : node; } + function finishUpdateSetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createCallSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(174 /* SyntaxKind.CallSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23460,13 +23741,12 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node; } // @api function createConstructSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(175 /* SyntaxKind.ConstructSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23477,24 +23757,23 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node; } // @api - function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, decorators, modifiers, + function createIndexSignature(modifiers, parameters, type) { + var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } // @api - function updateIndexSignature(node, decorators, modifiers, parameters, type) { + function updateIndexSignature(node, modifiers, parameters, type) { return node.parameters !== parameters || node.type !== type - || node.decorators !== decorators || node.modifiers !== modifiers - ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node; } // @api @@ -23554,10 +23833,11 @@ var ts; // @api function createFunctionTypeNode(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(179 /* SyntaxKind.FunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.modifiers = undefined; return node; } // @api @@ -23565,9 +23845,15 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node) + ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) : node; } + function finishUpdateFunctionTypeNode(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createConstructorTypeNode() { var args = []; @@ -23579,8 +23865,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, - /*decorators*/ undefined, modifiers, + var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23604,7 +23889,7 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node; } /** @deprecated */ @@ -23784,33 +24069,27 @@ var ts; ? update(createTemplateLiteralType(head, templateSpans), node) : node; } - function createImportTypeNode(argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : false; + // @api + function createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = false; } var node = createBaseNode(200 /* SyntaxKind.ImportType */); node.argument = argument; - node.assertions = assertion; + node.assertions = assertions; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.isTypeOf = isTypeOf; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateImportTypeNode(node, argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : node.isTypeOf; + // @api + function updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; } return node.argument !== argument - || node.assertions !== assertion + || node.assertions !== assertions || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf - ? update(createImportTypeNode(argument, assertion, qualifier, typeArguments, isTypeOf), node) + ? update(createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf), node) : node; } // @api @@ -23909,11 +24188,11 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + 524288 /* TransformFlags.ContainsBindingPattern */; + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } return node; } @@ -23930,7 +24209,7 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; + 524288 /* TransformFlags.ContainsBindingPattern */; return node; } // @api @@ -23942,7 +24221,6 @@ var ts; // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(203 /* SyntaxKind.BindingElement */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; @@ -23955,7 +24233,7 @@ var ts; propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 16384 /* TransformFlags.ContainsRestOrSpread */; + node.transformFlags |= 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -24011,13 +24289,13 @@ var ts; // @api function createPropertyAccessExpression(expression, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.name = asName(name); node.transformFlags = propagateChildFlags(node.expression) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); if (ts.isSuperKeyword(expression)) { // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators @@ -24041,7 +24319,7 @@ var ts; function createPropertyAccessChain(expression, questionDotToken, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= @@ -24050,7 +24328,7 @@ var ts; propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); return node; } // @api @@ -24067,7 +24345,7 @@ var ts; // @api function createElementAccessExpression(expression, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.argumentExpression = asExpression(index); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24095,7 +24373,7 @@ var ts; function createElementAccessChain(expression, questionDotToken, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.argumentExpression = asExpression(index); node.transformFlags |= @@ -24119,7 +24397,7 @@ var ts; // @api function createCallExpression(expression, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); node.transformFlags |= @@ -24130,10 +24408,10 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 4194304 /* TransformFlags.ContainsDynamicImport */; + node.transformFlags |= 8388608 /* TransformFlags.ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24152,7 +24430,7 @@ var ts; function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -24166,7 +24444,7 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24207,7 +24485,7 @@ var ts; // @api function createTaggedTemplateExpression(tag, typeArguments, template) { var node = createBaseExpression(210 /* SyntaxKind.TaggedTemplateExpression */); - node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); + node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.template = template; node.transformFlags |= @@ -24264,8 +24542,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); if (node.typeParameters) { @@ -24293,20 +24570,19 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, - /*decorators*/ undefined, modifiers, + var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* SyntaxKind.EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | 1024 /* TransformFlags.ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { - node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24318,7 +24594,7 @@ var ts; || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } // @api @@ -24368,7 +24644,7 @@ var ts; propagateChildFlags(node.expression) | 256 /* TransformFlags.ContainsES2017 */ | 128 /* TransformFlags.ContainsES2018 */ | - 1048576 /* TransformFlags.ContainsAwait */; + 2097152 /* TransformFlags.ContainsAwait */; return node; } // @api @@ -24389,7 +24665,7 @@ var ts; ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -24410,7 +24686,7 @@ var ts; if (ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -24456,11 +24732,14 @@ var ts; else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { node.transformFlags |= 16 /* TransformFlags.ContainsES2021 */; } + if (operatorKind === 101 /* SyntaxKind.InKeyword */ && ts.isPrivateIdentifier(node.left)) { + node.transformFlags |= 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */; + } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; if (node.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer @@ -24468,8 +24747,8 @@ var ts; var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (target.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } if (target.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); @@ -24595,7 +24874,7 @@ var ts; propagateChildFlags(node.asteriskToken) | 1024 /* TransformFlags.ContainsES2015 */ | 128 /* TransformFlags.ContainsES2018 */ | - 524288 /* TransformFlags.ContainsYield */; + 1048576 /* TransformFlags.ContainsYield */; return node; } // @api @@ -24612,7 +24891,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 16384 /* TransformFlags.ContainsRestOrSpread */; + 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -24622,20 +24901,19 @@ var ts; : node; } // @api - function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, modifiers, name, typeParameters, heritageClauses, members); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; return node; } // @api - function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api @@ -24645,7 +24923,7 @@ var ts; // @api function createExpressionWithTypeArguments(expression, typeArguments) { var node = createBaseNode(228 /* SyntaxKind.ExpressionWithTypeArguments */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24681,7 +24959,7 @@ var ts; // @api function createNonNullExpression(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -24700,7 +24978,7 @@ var ts; function createNonNullChain(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -24783,10 +25061,12 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */); + node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= - propagateChildFlags(node.declarationList); + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.declarationList); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } @@ -24945,7 +25225,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24960,7 +25240,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24977,7 +25257,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -25077,7 +25357,6 @@ var ts; // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { var node = createBaseVariableLikeDeclaration(254 /* SyntaxKind.VariableDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; node.transformFlags |= propagateChildFlags(node.exclamationToken); @@ -25103,11 +25382,11 @@ var ts; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* NodeFlags.BlockScoped */) { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */ | - 131072 /* TransformFlags.ContainsBlockScopedBinding */; + 262144 /* TransformFlags.ContainsBlockScopedBinding */; } return node; } @@ -25118,8 +25397,8 @@ var ts; : node; } // @api - function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -25127,7 +25406,7 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { if (node.asteriskToken) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */; @@ -25140,104 +25419,133 @@ var ts; node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } } + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } + function finishUpdateFunctionDeclaration(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.illegalDecorators = original.illegalDecorators; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } else { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; - if (node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */) { + if (node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } } return node; } // @api - function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api - function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? finishUpdateInterfaceDeclaration(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } + function finishUpdateInterfaceDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + function createTypeAliasDeclaration(modifiers, name, typeParameters, type) { + var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type - ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + ? finishUpdateTypeAliasDeclaration(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; } + function finishUpdateTypeAliasDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, decorators, modifiers, name); + function createEnumDeclaration(modifiers, name, members) { + var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateEnumDeclaration(node, decorators, modifiers, name, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateEnumDeclaration(node, modifiers, name, members) { + return node.modifiers !== modifiers || node.name !== name || node.members !== members - ? update(createEnumDeclaration(decorators, modifiers, name, members), node) + ? finishUpdateEnumDeclaration(createEnumDeclaration(modifiers, name, members), node) : node; } + function finishUpdateEnumDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createModuleDeclaration(decorators, modifiers, name, body, flags) { + function createModuleDeclaration(modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* NodeFlags.None */; } - var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */); + node.modifiers = asNodeArray(modifiers); node.flags |= flags & (16 /* NodeFlags.Namespace */ | 4 /* NodeFlags.NestedNamespace */ | 1024 /* NodeFlags.GlobalAugmentation */); node.name = name; node.body = body; @@ -25246,22 +25554,30 @@ var ts; } else { node.transformFlags |= - propagateChildFlags(node.name) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateModuleDeclaration(node, decorators, modifiers, name, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateModuleDeclaration(node, modifiers, name, body) { + return node.modifiers !== modifiers || node.name !== name || node.body !== body - ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + ? finishUpdateModuleDeclaration(createModuleDeclaration(modifiers, name, body, node.flags), node) : node; } + function finishUpdateModuleDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createModuleBlock(statements) { var node = createBaseNode(262 /* SyntaxKind.ModuleBlock */); @@ -25291,60 +25607,84 @@ var ts; // @api function createNamespaceExportDeclaration(name) { var node = createBaseNamedDeclaration(264 /* SyntaxKind.NamespaceExportDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api function updateNamespaceExportDeclaration(node, name) { return node.name !== name - ? update(createNamespaceExportDeclaration(name), node) + ? finishUpdateNamespaceExportDeclaration(createNamespaceExportDeclaration(name), node) : node; } + function finishUpdateNamespaceExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, decorators, modifiers, name); + function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) { + var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference - ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node) + ? finishUpdateImportEqualsDeclaration(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; } + function finishUpdateImportEqualsDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */, decorators, modifiers); + function createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause), node) + ? finishUpdateImportDeclaration(createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateImportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createImportClause(isTypeOnly, name, namedBindings) { var node = createBaseNode(267 /* SyntaxKind.ImportClause */); @@ -25357,7 +25697,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25417,7 +25757,7 @@ var ts; var node = createBaseNode(268 /* SyntaxKind.NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25433,7 +25773,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.name) | 4 /* TransformFlags.ContainsESNext */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25447,7 +25787,7 @@ var ts; var node = createBaseNode(269 /* SyntaxKind.NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25465,7 +25805,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25477,54 +25817,71 @@ var ts; : node; } // @api - function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */, decorators, modifiers); + function createExportAssignment(modifiers, isExportEquals, expression) { + var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */); + node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(63 /* SyntaxKind.EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); - node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportAssignment(node, decorators, modifiers, expression) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportAssignment(node, modifiers, expression) { + return node.modifiers !== modifiers || node.expression !== expression - ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + ? finishUpdateExportAssignment(createExportAssignment(modifiers, node.isExportEquals, expression), node) : node; } + function finishUpdateExportAssignment(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */, decorators, modifiers); + function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= - propagateChildFlags(node.exportClause) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) + ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createNamedExports(elements) { var node = createBaseNode(273 /* SyntaxKind.NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25542,7 +25899,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25555,9 +25912,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */, - /*decorators*/ undefined, - /*modifiers*/ undefined); + var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */); return node; } // @@ -25568,7 +25923,7 @@ var ts; var node = createBaseNode(277 /* SyntaxKind.ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25624,7 +25979,6 @@ var ts; // @api function createJSDocFunctionType(parameters, type) { var node = createBaseSignatureDeclaration(317 /* SyntaxKind.JSDocFunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); @@ -26276,26 +26630,18 @@ var ts; // @api function createPropertyAssignment(name, initializer) { var node = createBaseNamedDeclaration(296 /* SyntaxKind.PropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer); + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdatePropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updatePropertyAssignment(node, name, initializer) { return node.name !== name @@ -26303,31 +26649,32 @@ var ts; ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) : node; } + function finishUpdatePropertyAssignment(updated, original) { + // copy children used only for error reporting + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { var node = createBaseNamedDeclaration(297 /* SyntaxKind.ShorthandPropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.equalsToken = undefined; + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdateShorthandPropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.equalsToken) - updated.equalsToken = original.equalsToken; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { return node.name !== name @@ -26335,6 +26682,17 @@ var ts; ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) : node; } + function finishUpdateShorthandPropertyAssignment(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.equalsToken = original.equalsToken; + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createSpreadAssignment(expression) { var node = createBaseNode(298 /* SyntaxKind.SpreadAssignment */); @@ -26342,7 +26700,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; return node; } // @api @@ -26662,13 +27020,11 @@ var ts; } function createExportDefault(expression) { return createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); } function createExternalModuleExport(exportName) { return createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, createNamedExports([ createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName) @@ -26826,7 +27182,7 @@ var ts; } else if (ts.getEmitFlags(callee) & 4096 /* EmitFlags.HelperName */) { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee, /*optionalChain*/ false); } else if (ts.isPropertyAccessExpression(callee)) { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { @@ -26855,7 +27211,7 @@ var ts; else { // for `a()` target is `a` and thisArg is `void 0` thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); } return { target: target, thisArg: thisArg }; } @@ -26864,9 +27220,7 @@ var ts; // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560) createParenthesizedExpression(createObjectLiteralExpression([ createSetAccessorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, "value", [createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, paramName, /*questionToken*/ undefined, @@ -27168,30 +27522,32 @@ var ts; else { modifierArray = modifiers; } - return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : - ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : - ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : - ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifierArray, node.parameters, node.body) : - ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.type, node.body) : - ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.body) : - ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifierArray, node.parameters, node.type) : - ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : - ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : - ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.type) : - ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifierArray, node.name, node.members) : - ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifierArray, node.name, node.body) : - ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : - ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : - ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifierArray, node.expression) : - ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : - ts.Debug.assertNever(node); + return ts.isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : + ts.isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : + ts.isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : + ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : + ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : + ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : + ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : + ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : + ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : + ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : + ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : + ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : + ts.isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : + ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : + ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : + ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : + ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : + ts.isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : + ts.isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : + ts.isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : + ts.Debug.assertNever(node); } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -27299,10 +27655,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 33562624 /* TransformFlags.PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 134234112 /* TransformFlags.PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -27333,29 +27689,29 @@ var ts; case 208 /* SyntaxKind.CallExpression */: case 209 /* SyntaxKind.NewExpression */: case 204 /* SyntaxKind.ArrayLiteralExpression */: - return 536887296 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; + return -2147450880 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; case 261 /* SyntaxKind.ModuleDeclaration */: - return 589443072 /* TransformFlags.ModuleExcludes */; + return -1941676032 /* TransformFlags.ModuleExcludes */; case 164 /* SyntaxKind.Parameter */: - return 536870912 /* TransformFlags.ParameterExcludes */; + return -2147483648 /* TransformFlags.ParameterExcludes */; case 214 /* SyntaxKind.ArrowFunction */: - return 557748224 /* TransformFlags.ArrowFunctionExcludes */; + return -2072174592 /* TransformFlags.ArrowFunctionExcludes */; case 213 /* SyntaxKind.FunctionExpression */: case 256 /* SyntaxKind.FunctionDeclaration */: - return 591310848 /* TransformFlags.FunctionExcludes */; + return -1937940480 /* TransformFlags.FunctionExcludes */; case 255 /* SyntaxKind.VariableDeclarationList */: - return 537165824 /* TransformFlags.VariableDeclarationListExcludes */; + return -2146893824 /* TransformFlags.VariableDeclarationListExcludes */; case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return 536940544 /* TransformFlags.ClassExcludes */; + return -2147344384 /* TransformFlags.ClassExcludes */; case 171 /* SyntaxKind.Constructor */: - return 591306752 /* TransformFlags.ConstructorExcludes */; + return -1937948672 /* TransformFlags.ConstructorExcludes */; case 167 /* SyntaxKind.PropertyDeclaration */: - return 570433536 /* TransformFlags.PropertyExcludes */; + return -2013249536 /* TransformFlags.PropertyExcludes */; case 169 /* SyntaxKind.MethodDeclaration */: case 172 /* SyntaxKind.GetAccessor */: case 173 /* SyntaxKind.SetAccessor */: - return 574529536 /* TransformFlags.MethodOrAccessorExcludes */; + return -2005057536 /* TransformFlags.MethodOrAccessorExcludes */; case 130 /* SyntaxKind.AnyKeyword */: case 147 /* SyntaxKind.NumberKeyword */: case 158 /* SyntaxKind.BigIntKeyword */: @@ -27375,23 +27731,23 @@ var ts; case 259 /* SyntaxKind.TypeAliasDeclaration */: return -2 /* TransformFlags.TypeExcludes */; case 205 /* SyntaxKind.ObjectLiteralExpression */: - return 536973312 /* TransformFlags.ObjectLiteralExcludes */; + return -2147278848 /* TransformFlags.ObjectLiteralExcludes */; case 292 /* SyntaxKind.CatchClause */: - return 536903680 /* TransformFlags.CatchClauseExcludes */; + return -2147418112 /* TransformFlags.CatchClauseExcludes */; case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: - return 536887296 /* TransformFlags.BindingPatternExcludes */; + return -2147450880 /* TransformFlags.BindingPatternExcludes */; case 211 /* SyntaxKind.TypeAssertionExpression */: case 229 /* SyntaxKind.AsExpression */: case 350 /* SyntaxKind.PartiallyEmittedExpression */: case 212 /* SyntaxKind.ParenthesizedExpression */: case 106 /* SyntaxKind.SuperKeyword */: - return 536870912 /* TransformFlags.OuterExpressionExcludes */; + return -2147483648 /* TransformFlags.OuterExpressionExcludes */; case 206 /* SyntaxKind.PropertyAccessExpression */: case 207 /* SyntaxKind.ElementAccessExpression */: - return 536870912 /* TransformFlags.PropertyAccessExcludes */; + return -2147483648 /* TransformFlags.PropertyAccessExcludes */; default: - return 536870912 /* TransformFlags.NodeExcludes */; + return -2147483648 /* TransformFlags.NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -28801,6 +29157,11 @@ var ts; return node.kind === 126 /* SyntaxKind.AbstractKeyword */; } ts.isAbstractModifier = isAbstractModifier; + /* @internal */ + function isOverrideModifier(node) { + return node.kind === 159 /* SyntaxKind.OverrideKeyword */; + } + ts.isOverrideModifier = isOverrideModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 106 /* SyntaxKind.SuperKeyword */; @@ -29256,6 +29617,10 @@ var ts; return node.kind === 267 /* SyntaxKind.ImportClause */; } ts.isImportClause = isImportClause; + function isImportTypeAssertionContainer(node) { + return node.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */; + } + ts.isImportTypeAssertionContainer = isImportTypeAssertionContainer; function isAssertClause(node) { return node.kind === 293 /* SyntaxKind.AssertClause */; } @@ -29593,7 +29958,7 @@ var ts; (function (ts) { // Compound nodes function createEmptyExports(factory) { - return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); + return factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); } ts.createEmptyExports = createEmptyExports; function createMemberAccessForPropertyName(factory, target, memberName, location) { @@ -29743,13 +30108,13 @@ var ts; return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({ enumerable: factory.createFalse(), configurable: true, - get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, + get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(getAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, /*type*/ undefined, getAccessor.body // TODO: GH#18217 ), getAccessor), getAccessor), - set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, + set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(setAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, @@ -29768,7 +30133,7 @@ var ts; /*original*/ property); } function createExpressionForMethodDeclaration(factory, method, receiver) { - return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken, + return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(ts.getModifiers(method), method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, /*type*/ undefined, method.body // TODO: GH#18217 @@ -30001,7 +30366,6 @@ var ts; } if (namedBindings) { var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText), /*assertClause*/ undefined); ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* EmitFlags.NeverApplyImportHelper */); @@ -30320,33 +30684,50 @@ var ts; } } ts.getJSDocTypeAliasName = getJSDocTypeAliasName; - function canHaveModifiers(node) { + function canHaveIllegalType(node) { var kind = node.kind; - return kind === 164 /* SyntaxKind.Parameter */ - || kind === 166 /* SyntaxKind.PropertySignature */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 168 /* SyntaxKind.MethodSignature */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ + return kind === 171 /* SyntaxKind.Constructor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalType = canHaveIllegalType; + function canHaveIllegalTypeParameters(node) { + var kind = node.kind; + return kind === 171 /* SyntaxKind.Constructor */ || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalTypeParameters = canHaveIllegalTypeParameters; + function canHaveIllegalDecorators(node) { + var kind = node.kind; + return kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 213 /* SyntaxKind.FunctionExpression */ - || kind === 214 /* SyntaxKind.ArrowFunction */ - || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ || kind === 237 /* SyntaxKind.VariableStatement */ - || kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 257 /* SyntaxKind.ClassDeclaration */ || kind === 258 /* SyntaxKind.InterfaceDeclaration */ || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ || kind === 260 /* SyntaxKind.EnumDeclaration */ || kind === 261 /* SyntaxKind.ModuleDeclaration */ || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ || kind === 266 /* SyntaxKind.ImportDeclaration */ - || kind === 271 /* SyntaxKind.ExportAssignment */ - || kind === 272 /* SyntaxKind.ExportDeclaration */; + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ + || kind === 272 /* SyntaxKind.ExportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */; } - ts.canHaveModifiers = canHaveModifiers; + ts.canHaveIllegalDecorators = canHaveIllegalDecorators; + function canHaveIllegalModifiers(node) { + var kind = node.kind; + return kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 179 /* SyntaxKind.FunctionType */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */; + } + ts.canHaveIllegalModifiers = canHaveIllegalModifiers; ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); @@ -30610,6 +30991,14 @@ var ts; } } ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; + function elideNodes(factory, nodes) { + if (nodes === undefined) + return undefined; + if (nodes.length === 0) + return nodes; + return ts.setTextRange(factory.createNodeArray([], nodes.hasTrailingComma), nodes); + } + ts.elideNodes = elideNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -30617,6 +31006,46 @@ var ts; return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range; } ts.setTextRange = setTextRange; + function canHaveModifiers(node) { + var kind = node.kind; + return kind === 163 /* SyntaxKind.TypeParameter */ + || kind === 164 /* SyntaxKind.Parameter */ + || kind === 166 /* SyntaxKind.PropertySignature */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 168 /* SyntaxKind.MethodSignature */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 176 /* SyntaxKind.IndexSignature */ + || kind === 180 /* SyntaxKind.ConstructorType */ + || kind === 213 /* SyntaxKind.FunctionExpression */ + || kind === 214 /* SyntaxKind.ArrowFunction */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 237 /* SyntaxKind.VariableStatement */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 257 /* SyntaxKind.ClassDeclaration */ + || kind === 258 /* SyntaxKind.InterfaceDeclaration */ + || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 260 /* SyntaxKind.EnumDeclaration */ + || kind === 261 /* SyntaxKind.ModuleDeclaration */ + || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 266 /* SyntaxKind.ImportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */ + || kind === 272 /* SyntaxKind.ExportDeclaration */; + } + ts.canHaveModifiers = canHaveModifiers; + function canHaveDecorators(node) { + var kind = node.kind; + return kind === 164 /* SyntaxKind.Parameter */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 257 /* SyntaxKind.ClassDeclaration */; + } + ts.canHaveDecorators = canHaveDecorators; })(ts || (ts = {})); var ts; (function (ts) { @@ -30686,7 +31115,7 @@ var ts; } ts.isFileProbablyExternalModule = isFileProbablyExternalModule; function isAnExternalModuleIndicatorNode(node) { - return hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) + return ts.canHaveModifiers(node) && hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) || ts.isImportDeclaration(node) || ts.isExportAssignment(node) @@ -30735,7 +31164,7 @@ var ts; visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || @@ -30745,79 +31174,128 @@ var ts; case 298 /* SyntaxKind.SpreadAssignment */: return visitNode(cbNode, node.expression); case 164 /* SyntaxKind.Parameter */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 167 /* SyntaxKind.PropertyDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 166 /* SyntaxKind.PropertySignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 296 /* SyntaxKind.PropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.initializer); case 254 /* SyntaxKind.VariableDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || + return visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 203 /* SyntaxKind.BindingElement */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.dotDotDotToken) || + return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: case 176 /* SyntaxKind.IndexSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); + case 180 /* SyntaxKind.ConstructorType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 179 /* SyntaxKind.FunctionType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + return visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 169 /* SyntaxKind.MethodDeclaration */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 168 /* SyntaxKind.MethodSignature */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 171 /* SyntaxKind.Constructor */: + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 172 /* SyntaxKind.GetAccessor */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 256 /* SyntaxKind.FunctionDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 214 /* SyntaxKind.ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.body); case 178 /* SyntaxKind.TypeReference */: @@ -30945,7 +31423,7 @@ var ts; return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); case 237 /* SyntaxKind.VariableStatement */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); case 255 /* SyntaxKind.VariableDeclarationList */: @@ -31010,27 +31488,26 @@ var ts; return visitNode(cbNode, node.expression); case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 258 /* SyntaxKind.InterfaceDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); case 260 /* SyntaxKind.EnumDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); @@ -31038,17 +31515,17 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 261 /* SyntaxKind.ModuleDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); case 266 /* SyntaxKind.ImportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -31062,7 +31539,8 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.value); case 264 /* SyntaxKind.NamespaceExportDeclaration */: - return visitNode(cbNode, node.name); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNode(cbNode, node.name); case 268 /* SyntaxKind.NamespaceImport */: return visitNode(cbNode, node.name); case 274 /* SyntaxKind.NamespaceExport */: @@ -31071,7 +31549,7 @@ var ts; case 273 /* SyntaxKind.NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); case 272 /* SyntaxKind.ExportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -31081,17 +31559,21 @@ var ts; return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); case 271 /* SyntaxKind.ExportAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); case 223 /* SyntaxKind.TemplateExpression */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 233 /* SyntaxKind.TemplateSpan */: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.literal); case 198 /* SyntaxKind.TemplateLiteralType */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 199 /* SyntaxKind.TemplateLiteralTypeSpan */: - return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.literal); case 162 /* SyntaxKind.ComputedPropertyName */: return visitNode(cbNode, node.expression); case 291 /* SyntaxKind.HeritageClause */: @@ -31102,7 +31584,8 @@ var ts; case 277 /* SyntaxKind.ExternalModuleReference */: return visitNode(cbNode, node.expression); case 276 /* SyntaxKind.MissingDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers); case 351 /* SyntaxKind.CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 278 /* SyntaxKind.JsxElement */: @@ -31781,7 +32264,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* NodeFlags.AwaitContext */) - && !!(node.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -31822,7 +32305,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setFields(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); setFields(sourceFile); } @@ -32750,7 +33233,7 @@ var ts; } return parseElement(); } - function currentNode(parsingContext) { + function currentNode(parsingContext, pos) { // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. // // If there is an outstanding parse error that we've encountered, but not attached to @@ -32763,7 +33246,7 @@ var ts; if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } - var node = syntaxCursor.currentNode(scanner.getStartPos()); + var node = syntaxCursor.currentNode(pos !== null && pos !== void 0 ? pos : scanner.getStartPos()); // Can't reuse a missing node. // Can't reuse a node that intersected the change range. // Can't reuse a node that contains a parse error. This is necessary so that we @@ -33038,7 +33521,9 @@ var ts; case 23 /* ParsingContext.ImportOrExportSpecifiers */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 13 /* ParsingContext.JsxAttributes */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 14 /* ParsingContext.JsxChildren */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - default: return [undefined]; // TODO: GH#18217 `default: Debug.assertNever(context);` + case 24 /* ParsingContext.AssertEntries */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_or_string_literal_expected); // AssertionKey. + case 25 /* ParsingContext.Count */: return ts.Debug.fail("ParsingContext.Count used as a context"); // Not a real context, only a marker. + default: ts.Debug.assertNever(context); } } function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { @@ -33354,7 +33839,6 @@ var ts; parseExpected(58 /* SyntaxKind.ColonToken */); } return finishNode(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier? @@ -33480,10 +33964,9 @@ var ts; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : doOutsideOfAwaitContext(parseDecorators); if (token() === 108 /* SyntaxKind.ThisKeyword */) { var node_1 = factory.createParameterDeclaration(decorators, - /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); @@ -33494,12 +33977,12 @@ var ts; } var savedTopLevel = topLevel; topLevel = false; - var modifiers = parseModifiers(); + var modifiers = combineDecoratorsAndModifiers(decorators, parseModifiers()); var dotDotDotToken = parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */); if (!allowAmbiguity && !isParameterNameStart()) { return undefined; } - var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createParameterDeclaration(modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); topLevel = savedTopLevel; return node; } @@ -33651,7 +34134,8 @@ var ts; var parameters = parseBracketedList(16 /* ParsingContext.Parameters */, function () { return parseParameter(/*inOuterAwaitContext*/ false); }, 22 /* SyntaxKind.OpenBracketToken */, 23 /* SyntaxKind.CloseBracketToken */); var type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - var node = factory.createIndexSignature(decorators, modifiers, parameters, type); + var node = factory.createIndexSignature(modifiers, parameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) { @@ -33724,10 +34208,10 @@ var ts; var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */, 4 /* SignatureFlags.Type */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */, 4 /* SignatureFlags.Type */); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); @@ -34365,10 +34849,10 @@ var ts; setDecoratorContext(/*val*/ false); } var pos = getNodePos(); - var expr = parseAssignmentExpressionOrHigher(); + var expr = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); var operatorToken; while ((operatorToken = parseOptionalToken(27 /* SyntaxKind.CommaToken */))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos); + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), pos); } if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -34376,9 +34860,9 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true) : undefined; } - function parseAssignmentExpressionOrHigher() { + function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) { // AssignmentExpression[in,yield]: // 1) ConditionalExpression[?in,?yield] // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] @@ -34404,7 +34888,7 @@ var ts; // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + var arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction); if (arrowExpression) { return arrowExpression; } @@ -34423,7 +34907,7 @@ var ts; // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. if (expr.kind === 79 /* SyntaxKind.Identifier */ && token() === 38 /* SyntaxKind.EqualsGreaterThanToken */) { - return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, /*asyncModifier*/ undefined); } // Now see if we might be in cases '2' or '3'. // If the expression was a LHS expression, and we have an assignment operator, then @@ -34432,10 +34916,10 @@ var ts; // Note: we call reScanGreaterToken so that we get an appropriately merged token // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos); + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); } // It wasn't an assignment or a lambda. This is a conditional expression: - return parseConditionalExpressionRest(expr, pos); + return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction); } function isYieldExpression() { if (token() === 125 /* SyntaxKind.YieldKeyword */) { @@ -34475,7 +34959,7 @@ var ts; nextToken(); if (!scanner.hasPrecedingLineBreak() && (token() === 41 /* SyntaxKind.AsteriskToken */ || isStartOfExpression())) { - return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher()), pos); + return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)), pos); } else { // if the next token is not on the same line as yield. or we don't have an '*' or @@ -34483,10 +34967,9 @@ var ts; return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { ts.Debug.assert(token() === 38 /* SyntaxKind.EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var parameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, identifier, /*questionToken*/ undefined, @@ -34495,11 +34978,11 @@ var ts; finishNode(parameter, identifier.pos); var parameters = createNodeArray([parameter], parameter.pos, parameter.end); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); - var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier, allowReturnTypeInArrowFunction); var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body); return addJSDocComment(finishNode(node, pos)); } - function tryParseParenthesizedArrowFunctionExpression() { + function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var triState = isParenthesizedArrowFunctionExpression(); if (triState === 0 /* Tristate.False */) { // It's definitely not a parenthesized arrow function expression. @@ -34510,8 +34993,8 @@ var ts; // it out, but don't allow any ambiguity, and return 'undefined' if this could be an // expression instead. return triState === 1 /* Tristate.True */ ? - parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) : - tryParse(parsePossibleParenthesizedArrowFunctionExpression); + parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true, /*allowReturnTypeInArrowFunction*/ true) : + tryParse(function () { return parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction); }); } // True -> We definitely expect a parenthesized arrow function here. // False -> There *cannot* be a parenthesized arrow function here. @@ -34576,7 +35059,7 @@ var ts; // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. if (ts.isModifierKind(second) && second !== 131 /* SyntaxKind.AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { - if (lookAhead(function () { return nextToken() === 127 /* SyntaxKind.AsKeyword */; })) { + if (nextToken() === 127 /* SyntaxKind.AsKeyword */) { // https://github.com/microsoft/TypeScript/issues/44466 return 0 /* Tristate.False */; } @@ -34645,25 +35128,25 @@ var ts; return 2 /* Tristate.Unknown */; } } - function parsePossibleParenthesizedArrowFunctionExpression() { + function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var tokenPos = scanner.getTokenPos(); if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) { return undefined; } - var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false); + var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false, allowReturnTypeInArrowFunction); if (!result) { (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos); } return result; } - function tryParseAsyncSimpleArrowFunctionExpression() { + function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() === 131 /* SyntaxKind.AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* Tristate.True */) { var pos = getNodePos(); var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0 /* OperatorPrecedence.Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); } } return undefined; @@ -34687,7 +35170,7 @@ var ts; } return 0 /* Tristate.False */; } - function parseParenthesizedArrowFunctionExpression(allowAmbiguity) { + function parseParenthesizedArrowFunctionExpression(allowAmbiguity, allowReturnTypeInArrowFunction) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiersForArrowFunction(); @@ -34722,6 +35205,7 @@ var ts; return undefined; } } + var hasReturnColon = token() === 58 /* SyntaxKind.ColonToken */; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) { return undefined; @@ -34750,12 +35234,37 @@ var ts; var lastToken = token(); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); var body = (lastToken === 38 /* SyntaxKind.EqualsGreaterThanToken */ || lastToken === 18 /* SyntaxKind.OpenBraceToken */) - ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier)) + ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier(); + // Given: + // x ? y => ({ y }) : z => ({ z }) + // We try to parse the body of the first arrow function by looking at: + // ({ y }) : z => ({ z }) + // This is a valid arrow function with "z" as the return type. + // + // But, if we're in the true side of a conditional expression, this colon + // terminates the expression, so we cannot allow a return type if we aren't + // certain whether or not the preceding text was parsed as a parameter list. + // + // For example, + // a() ? (b: number, c?: string): void => d() : e + // is determined by isParenthesizedArrowFunctionExpression to unambiguously + // be an arrow expression, so we allow a return type. + if (!allowReturnTypeInArrowFunction && hasReturnColon) { + // However, if the arrow function we were able to parse is followed by another colon + // as in: + // a ? (x): string => x : null + // Then allow the arrow function, and treat the second colon as terminating + // the conditional expression. It's okay to do this because this code would + // be a syntax error in JavaScript (as the second colon shouldn't be there). + if (token() !== 58 /* SyntaxKind.ColonToken */) { + return undefined; + } + } var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseArrowFunctionExpressionBody(isAsync) { + function parseArrowFunctionExpressionBody(isAsync, allowReturnTypeInArrowFunction) { if (token() === 18 /* SyntaxKind.OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* SignatureFlags.Await */ : 0 /* SignatureFlags.None */); } @@ -34783,12 +35292,12 @@ var ts; var savedTopLevel = topLevel; topLevel = false; var node = isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + ? doInAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }) + : doOutsideOfAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }); topLevel = savedTopLevel; return node; } - function parseConditionalExpressionRest(leftOperand, pos) { + function parseConditionalExpressionRest(leftOperand, pos, allowReturnTypeInArrowFunction) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. var questionToken = parseOptionalToken(57 /* SyntaxKind.QuestionToken */); if (!questionToken) { @@ -34797,8 +35306,8 @@ var ts; // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. var colonToken; - return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) - ? parseAssignmentExpressionOrHigher() + return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ false); }), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) + ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(79 /* SyntaxKind.Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* SyntaxKind.ColonToken */))), pos); } function parseBinaryExpressionOrHigher(precedence) { @@ -35183,6 +35692,9 @@ var ts; var typeArguments = tryParse(parseTypeArgumentsInExpression); if (typeArguments !== undefined) { parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments); + if (!isTemplateStartOfTaggedTemplate()) { + expression = factory.createExpressionWithTypeArguments(expression, typeArguments); + } } } if (token() === 20 /* SyntaxKind.OpenParenToken */ || token() === 24 /* SyntaxKind.DotToken */ || token() === 22 /* SyntaxKind.OpenBracketToken */) { @@ -35395,9 +35907,22 @@ var ts; } scanJsxIdentifier(); var pos = getNodePos(); - return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 63 /* SyntaxKind.EqualsToken */ ? undefined : - scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */ ? parseLiteralNode() : - parseJsxExpression(/*inExpressionContext*/ true)), pos); + return finishNode(factory.createJsxAttribute(parseIdentifierName(), parseJsxAttributeValue()), pos); + } + function parseJsxAttributeValue() { + if (token() === 63 /* SyntaxKind.EqualsToken */) { + if (scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */) { + return parseLiteralNode(); + } + if (token() === 18 /* SyntaxKind.OpenBraceToken */) { + return parseJsxExpression(/*inExpressionContext*/ true); + } + if (token() === 29 /* SyntaxKind.LessThanToken */) { + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + parseErrorAtCurrentToken(ts.Diagnostics.or_JSX_element_expected); + } + return undefined; } function parseJsxSpreadAttribute() { var pos = getNodePos(); @@ -35487,6 +36012,11 @@ var ts; if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) { parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers); } + if (ts.isExpressionWithTypeArguments(expression) && expression.typeArguments) { + var pos_2 = expression.typeArguments.pos - 1; + var end = ts.skipTrivia(sourceText, expression.typeArguments.end) + 1; + parseErrorAt(pos_2, end, ts.Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access); + } return finishNode(propertyAccess, pos); } function parseElementAccessExpressionRest(pos, expression, questionDotToken) { @@ -35612,10 +36142,11 @@ var ts; } nextToken(); var typeArguments = parseDelimitedList(20 /* ParsingContext.TypeArguments */, parseType); - if (!parseExpected(31 /* SyntaxKind.GreaterThanToken */)) { + if (reScanGreaterToken() !== 31 /* SyntaxKind.GreaterThanToken */) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } + nextToken(); // We successfully parsed a type argument list. The next token determines whether we want to // treat it as such. If the type argument list is followed by `(` or a template literal, as in // `f(42)`, we favor the type argument interpretation even though JavaScript would view @@ -35629,9 +36160,18 @@ var ts; case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: // foo `...` case 15 /* SyntaxKind.TemplateHead */: // foo `...${100}...` return true; + // A type argument list followed by `<` never makes sense, and a type argument list followed + // by `>` is ambiguous with a (re-scanned) `>>` operator, so we disqualify both. Also, in + // this context, `+` and `-` are unary operators, not binary operators. + case 29 /* SyntaxKind.LessThanToken */: + case 31 /* SyntaxKind.GreaterThanToken */: + case 39 /* SyntaxKind.PlusToken */: + case 40 /* SyntaxKind.MinusToken */: + return false; } - // Consider something a type argument list only if the following token can't start an expression. - return !isStartOfExpression(); + // We favor the type argument list interpretation when it is immediately followed by + // a line break, a binary operator, or something that can't start an expression. + return scanner.hasPrecedingLineBreak() || isBinaryOperator() || !isStartOfExpression(); } function parsePrimaryExpression() { switch (token()) { @@ -35690,13 +36230,13 @@ var ts; function parseSpreadElement() { var pos = getNodePos(); parseExpected(25 /* SyntaxKind.DotDotDotToken */); - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createSpreadElement(expression), pos); } function parseArgumentOrArrayLiteralElement() { return token() === 25 /* SyntaxKind.DotDotDotToken */ ? parseSpreadElement() : token() === 27 /* SyntaxKind.CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) : - parseAssignmentExpressionOrHigher(); + parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); @@ -35714,16 +36254,16 @@ var ts; var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); if (parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */)) { - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc); } var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } var asteriskToken = parseOptionalToken(41 /* SyntaxKind.AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -35743,7 +36283,7 @@ var ts; var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* SyntaxKind.ColonToken */); if (isShorthandPropertyAssignment) { var equalsToken = parseOptionalToken(63 /* SyntaxKind.EqualsToken */); - var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined; + var objectAssignmentInitializer = equalsToken ? allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }) : undefined; node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer); // Save equals token for error reporting. // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful. @@ -35751,11 +36291,11 @@ var ts; } else { parseExpected(58 /* SyntaxKind.ColonToken */); - var initializer = allowInAnd(parseAssignmentExpressionOrHigher); + var initializer = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); node = factory.createPropertyAssignment(name, initializer); } // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; node.questionToken = questionToken; node.exclamationToken = exclamationToken; @@ -35815,6 +36355,9 @@ var ts; typeArguments = expression.typeArguments; expression = expression.expression; } + if (token() === 28 /* SyntaxKind.QuestionDotToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, ts.getTextOfNodeFromSourceText(sourceText, expression)); + } var argumentList = token() === 20 /* SyntaxKind.OpenParenToken */ ? parseArgumentList() : undefined; return finishNode(factory.createNewExpression(expression, typeArguments, argumentList), pos); } @@ -35925,7 +36468,7 @@ var ts; } var node; if (awaitToken ? parseExpected(160 /* SyntaxKind.OfKeyword */) : parseOptional(160 /* SyntaxKind.OfKeyword */)) { - var expression = allowInAnd(parseAssignmentExpressionOrHigher); + var expression = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); parseExpected(21 /* SyntaxKind.CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); } @@ -36330,24 +36873,19 @@ var ts; return modifier.kind === 135 /* SyntaxKind.DeclareKeyword */; } function parseDeclaration() { - // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner - // if we can't reuse the declaration, so that we don't do this work twice? - // // `parseListElement` attempted to get the reused node at this position, // but the ambient context flag was not yet set, so the node appeared // not reusable in that context. - var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier); - if (isAmbient) { - var node = tryReuseAmbientDeclaration(); - if (node) { - return node; - } - } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var decorators = parseDecorators(); var modifiers = parseModifiers(); + var isAmbient = ts.some(modifiers, isDeclareModifier); if (isAmbient) { + var node = tryReuseAmbientDeclaration(pos); + if (node) { + return node; + } for (var _i = 0, _a = modifiers; _i < _a.length; _i++) { var m = _a[_i]; m.flags |= 16777216 /* NodeFlags.Ambient */; @@ -36358,9 +36896,9 @@ var ts; return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); } } - function tryReuseAmbientDeclaration() { + function tryReuseAmbientDeclaration(pos) { return doInsideOfContext(16777216 /* NodeFlags.Ambient */, function () { - var node = currentNode(parsingContext); + var node = currentNode(parsingContext, pos); if (node) { return consumeNode(node); } @@ -36405,7 +36943,7 @@ var ts; // would follow. For recovery and error reporting purposes, return an incomplete declaration. var missing = createMissingNode(276 /* SyntaxKind.MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); - missing.decorators = decorators; + missing.illegalDecorators = decorators; missing.modifiers = modifiers; return missing; } @@ -36417,9 +36955,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* SyntaxKind.StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 18 /* SyntaxKind.OpenBraceToken */ && canParseSemicolon()) { - parseSemicolon(); - return; + if (token() !== 18 /* SyntaxKind.OpenBraceToken */) { + if (flags & 4 /* SignatureFlags.Type */) { + parseTypeMemberSemicolon(); + return; + } + if (canParseSemicolon()) { + parseSemicolon(); + return; + } } return parseFunctionBlock(flags, diagnosticMessage); } @@ -36542,7 +37086,7 @@ var ts; parseSemicolon(); var node = factory.createVariableStatement(modifiers, declarationList); // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker. - node.decorators = decorators; + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36561,7 +37105,8 @@ var ts; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); setAwaitContext(savedAwaitContext); - var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + var node = factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseConstructorName() { @@ -36582,8 +37127,9 @@ var ts; var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */, ts.Diagnostics.or_expected); - var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body); - // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker. + var node = factory.createConstructorDeclaration(modifiers, parameters, body); + // Attach invalid nodes if they exist so that we can report them in the grammar checker. + node.illegalDecorators = decorators; node.typeParameters = typeParameters; node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36597,7 +37143,7 @@ var ts; var parameters = parseParameters(isGenerator | isAsync); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + var node = factory.createMethodDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); // An exclamation token on a method is invalid syntax and will be handled by the grammar checker node.exclamationToken = exclamationToken; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36607,7 +37153,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = doOutsideOfContext(8192 /* NodeFlags.YieldContext */ | 32768 /* NodeFlags.AwaitContext */ | 4096 /* NodeFlags.DisallowInContext */, parseInitializer); parseSemicolonAfterPropertyName(name, type, initializer); - var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer); + var node = factory.createPropertyDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, questionToken || exclamationToken, type, initializer); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36621,18 +37167,18 @@ var ts; } return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken); } - function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) { + function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind, flags) { var name = parsePropertyName(); var typeParameters = parseTypeParameters(); var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); - var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */); + var body = parseFunctionBlockOrSemicolon(flags); var node = kind === 172 /* SyntaxKind.GetAccessor */ - ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) - : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); + ? factory.createGetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, type, body) + : factory.createSetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 173 /* SyntaxKind.SetAccessor */) + if (ts.isSetAccessorDeclaration(node)) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -36698,7 +37244,10 @@ var ts; function parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers) { parseExpectedToken(124 /* SyntaxKind.StaticKeyword */); var body = parseClassStaticBlockBody(); - return withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(decorators, modifiers, body), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(body), pos), hasJSDoc); + node.illegalDecorators = decorators; + node.modifiers = modifiers; + return node; } function parseClassStaticBlockBody() { var savedYieldContext = inYieldContext(); @@ -36761,6 +37310,15 @@ var ts; } return finishNode(factory.createToken(kind), pos); } + function combineDecoratorsAndModifiers(decorators, modifiers) { + if (!decorators) + return modifiers; + if (!modifiers) + return decorators; + var decoratorsAndModifiers = factory.createNodeArray(ts.concatenate(decorators, modifiers)); + ts.setTextRangePosEnd(decoratorsAndModifiers, decorators.pos, modifiers.end); + return decoratorsAndModifiers; + } /* * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect @@ -36801,10 +37359,10 @@ var ts; return parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers); } if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } if (token() === 134 /* SyntaxKind.ConstructorKeyword */ || token() === 10 /* SyntaxKind.StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -36869,8 +37427,8 @@ var ts; } setAwaitContext(savedAwaitContext); var node = kind === 257 /* SyntaxKind.ClassDeclaration */ - ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) - : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); + ? factory.createClassDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members) + : factory.createClassExpression(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseNameOfClassDeclarationOrExpression() { @@ -36927,7 +37485,8 @@ var ts; var typeParameters = parseTypeParameters(); var heritageClauses = parseHeritageClauses(); var members = parseObjectTypeMembers(); - var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = factory.createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36937,7 +37496,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var type = token() === 138 /* SyntaxKind.IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); parseSemicolon(); - var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type); + var node = factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } // In an ambient declaration, the grammar only allows integer literals as initializers. @@ -36962,7 +37522,8 @@ var ts; else { members = createMissingList(); } - var node = factory.createEnumDeclaration(decorators, modifiers, name, members); + var node = factory.createEnumDeclaration(modifiers, name, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleBlock() { @@ -36985,7 +37546,8 @@ var ts; var body = parseOptional(24 /* SyntaxKind.DotToken */) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NodeFlags.NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -37007,7 +37569,8 @@ var ts; else { parseSemicolon(); } - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -37047,7 +37610,7 @@ var ts; parseSemicolon(); var node = factory.createNamespaceExportDeclaration(name); // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -37086,14 +37649,15 @@ var ts; assertClause = parseAssertClause(); } parseSemicolon(); - var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause); + var node = factory.createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAssertEntry() { var pos = getNodePos(); var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* SyntaxKind.StringLiteral */); parseExpected(58 /* SyntaxKind.ColonToken */); - var value = parseAssignmentExpressionOrHigher(); + var value = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createAssertEntry(name, value), pos); } function parseAssertClause(skipAssertKeyword) { @@ -37130,7 +37694,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var moduleReference = parseModuleReference(); parseSemicolon(); - var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference); + var node = factory.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference); + node.illegalDecorators = decorators; var finished = withJSDoc(finishNode(node, pos), hasJSDoc); return finished; } @@ -37319,7 +37884,8 @@ var ts; } parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + var node = factory.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) { @@ -37332,10 +37898,11 @@ var ts; else { parseExpected(88 /* SyntaxKind.DefaultKeyword */); } - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression); + var node = factory.createExportAssignment(modifiers, isExportEquals, expression); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } var ParsingContext; @@ -38126,7 +38693,6 @@ var ts; if (parseOptional(24 /* SyntaxKind.DotToken */)) { var body = parseJSDocTypeNameWithNamespace(/*nested*/ true); var jsDocNamespaceNode = factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NodeFlags.NestedNamespace */ : undefined); return finishNode(jsDocNamespaceNode, pos); } @@ -38563,10 +39129,10 @@ var ts; } function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { - var pos_2 = node.pos; + var pos_3 = node.pos; var visitNode_1 = function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; + ts.Debug.assert(child.pos >= pos_3); + pos_3 = child.end; }; if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -38575,7 +39141,7 @@ var ts; } } forEachChild(node, visitNode_1); - ts.Debug.assert(pos_2 <= node.end); + ts.Debug.assert(pos_3 <= node.end); } } function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { @@ -39173,6 +39739,7 @@ var ts; ["es2022.error", "lib.es2022.error.d.ts"], ["es2022.intl", "lib.es2022.intl.d.ts"], ["es2022.object", "lib.es2022.object.d.ts"], + ["es2022.sharedmemory", "lib.es2022.sharedmemory.d.ts"], ["es2022.string", "lib.es2022.string.d.ts"], ["esnext.array", "lib.es2022.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], @@ -39386,6 +39953,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, defaultValueDescription: false, @@ -39420,12 +39988,40 @@ var ts; affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, defaultValueDescription: 0 /* ScriptTarget.ES3 */, }; + /*@internal*/ + ts.moduleOptionDeclaration = { + name: "module", + shortName: "m", + type: new ts.Map(ts.getEntries({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + es2020: ts.ModuleKind.ES2020, + es2022: ts.ModuleKind.ES2022, + esnext: ts.ModuleKind.ESNext, + node16: ts.ModuleKind.Node16, + nodenext: ts.ModuleKind.NodeNext, + })), + affectsModuleResolution: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Modules, + description: ts.Diagnostics.Specify_what_module_code_is_generated, + defaultValueDescription: undefined, + }; var commandOptionsWithoutBuild = [ // CommandLine only options { @@ -39487,37 +40083,14 @@ var ts; category: ts.Diagnostics.Command_line_Options, affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, isCommandLineOnly: true, description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, defaultValueDescription: false, }, // Basic ts.targetOptionDeclaration, - { - name: "module", - shortName: "m", - type: new ts.Map(ts.getEntries({ - none: ts.ModuleKind.None, - commonjs: ts.ModuleKind.CommonJS, - amd: ts.ModuleKind.AMD, - system: ts.ModuleKind.System, - umd: ts.ModuleKind.UMD, - es6: ts.ModuleKind.ES2015, - es2015: ts.ModuleKind.ES2015, - es2020: ts.ModuleKind.ES2020, - es2022: ts.ModuleKind.ES2022, - esnext: ts.ModuleKind.ESNext, - node16: ts.ModuleKind.Node16, - nodenext: ts.ModuleKind.NodeNext, - })), - affectsModuleResolution: true, - affectsEmit: true, - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Modules, - description: ts.Diagnostics.Specify_what_module_code_is_generated, - defaultValueDescription: undefined, - }, + ts.moduleOptionDeclaration, { name: "lib", type: "list", @@ -39554,6 +40127,7 @@ var ts; type: jsxOptionMap, affectsSourceFile: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -39566,6 +40140,7 @@ var ts; shortName: "d", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -39576,6 +40151,7 @@ var ts; name: "declarationMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -39586,6 +40162,7 @@ var ts; name: "emitDeclarationOnly", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, @@ -39596,6 +40173,7 @@ var ts; name: "sourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -39605,6 +40183,9 @@ var ts; name: "outFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, showInSimplifiedHelpView: true, @@ -39616,6 +40197,8 @@ var ts; name: "outDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, showInSimplifiedHelpView: true, @@ -39626,6 +40209,8 @@ var ts; name: "rootDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Modules, @@ -39636,6 +40221,8 @@ var ts; name: "composite", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isTSConfigOnly: true, category: ts.Diagnostics.Projects, transpileOptionValue: undefined, @@ -39646,6 +40233,8 @@ var ts; name: "tsBuildInfoFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, category: ts.Diagnostics.Projects, @@ -39657,6 +40246,7 @@ var ts; name: "removeComments", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -39675,6 +40265,7 @@ var ts; name: "importHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, defaultValueDescription: false, @@ -39688,6 +40279,7 @@ var ts; })), affectsEmit: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, defaultValueDescription: 0 /* ImportsNotUsedAsValues.Remove */, @@ -39696,6 +40288,7 @@ var ts; name: "downlevelIteration", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, defaultValueDescription: false, @@ -39714,6 +40307,9 @@ var ts; type: "boolean", // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here // The value of each strictFlag depends on own strictFlag value or this and never accessed directly. + // But we need to store `strict` in builf info, even though it won't be examined directly, so that the + // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_all_strict_type_checking_options, @@ -39723,6 +40319,7 @@ var ts; name: "noImplicitAny", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, @@ -39732,6 +40329,7 @@ var ts; name: "strictNullChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_type_checking_take_into_account_null_and_undefined, @@ -39740,6 +40338,8 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, @@ -39748,6 +40348,8 @@ var ts; { name: "strictBindCallApply", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, @@ -39757,6 +40359,7 @@ var ts; name: "strictPropertyInitialization", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, @@ -39766,6 +40369,7 @@ var ts; name: "noImplicitThis", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, @@ -39775,6 +40379,7 @@ var ts; name: "useUnknownInCatchVariables", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, @@ -39784,6 +40389,8 @@ var ts; name: "alwaysStrict", type: "boolean", affectsSourceFile: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_use_strict_is_always_emitted, @@ -39794,6 +40401,7 @@ var ts; name: "noUnusedLocals", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, defaultValueDescription: false, @@ -39802,6 +40410,7 @@ var ts; name: "noUnusedParameters", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, defaultValueDescription: false, @@ -39810,6 +40419,7 @@ var ts; name: "exactOptionalPropertyTypes", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, defaultValueDescription: false, @@ -39818,6 +40428,7 @@ var ts; name: "noImplicitReturns", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, defaultValueDescription: false, @@ -39827,6 +40438,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, defaultValueDescription: false, @@ -39835,6 +40447,7 @@ var ts; name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, defaultValueDescription: false, @@ -39843,6 +40456,7 @@ var ts; name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, defaultValueDescription: false, @@ -39850,6 +40464,8 @@ var ts; { name: "noPropertyAccessFromIndexSignature", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: false, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, @@ -39935,6 +40551,7 @@ var ts; name: "allowSyntheticDefaultImports", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, defaultValueDescription: ts.Diagnostics.module_system_or_esModuleInterop @@ -39944,6 +40561,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, @@ -39960,6 +40578,7 @@ var ts; name: "allowUmdGlobalAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules, defaultValueDescription: false, @@ -39981,6 +40600,7 @@ var ts; name: "sourceRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code, @@ -39989,6 +40609,7 @@ var ts; name: "mapRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, @@ -39997,6 +40618,7 @@ var ts; name: "inlineSourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -40005,6 +40627,7 @@ var ts; name: "inlineSources", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -40014,6 +40637,7 @@ var ts; name: "experimentalDecorators", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, defaultValueDescription: false, @@ -40023,6 +40647,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, defaultValueDescription: false, @@ -40047,6 +40672,7 @@ var ts; type: "string", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, @@ -40064,6 +40690,9 @@ var ts; name: "out", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: false, // for correct behaviour, please use outFile category: ts.Diagnostics.Backwards_Compatibility, @@ -40075,6 +40704,7 @@ var ts; name: "reactNamespace", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, defaultValueDescription: "`React`", @@ -40082,6 +40712,8 @@ var ts; { name: "skipDefaultLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, defaultValueDescription: false, @@ -40097,6 +40729,7 @@ var ts; name: "emitBOM", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, defaultValueDescription: false, @@ -40108,6 +40741,7 @@ var ts; lf: 1 /* NewLineKind.LineFeed */ })), affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Set_the_newline_character_for_emitting_files, @@ -40117,6 +40751,7 @@ var ts; name: "noErrorTruncation", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_truncating_types_in_error_messages, defaultValueDescription: false, @@ -40147,6 +40782,7 @@ var ts; name: "stripInternal", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, defaultValueDescription: false, @@ -40187,6 +40823,7 @@ var ts; name: "noImplicitUseStrict", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, defaultValueDescription: false, @@ -40195,6 +40832,7 @@ var ts; name: "noEmitHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, defaultValueDescription: false, @@ -40203,6 +40841,7 @@ var ts; name: "noEmitOnError", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, @@ -40212,6 +40851,7 @@ var ts; name: "preserveConstEnums", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, defaultValueDescription: false, @@ -40220,6 +40860,8 @@ var ts; name: "declarationDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, category: ts.Diagnostics.Emit, @@ -40229,6 +40871,8 @@ var ts; { name: "skipLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_all_d_ts_files, defaultValueDescription: false, @@ -40238,6 +40882,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unused_labels, defaultValueDescription: undefined, @@ -40247,6 +40892,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code, defaultValueDescription: undefined, @@ -40255,6 +40901,7 @@ var ts; name: "suppressExcessPropertyErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, defaultValueDescription: false, @@ -40263,6 +40910,7 @@ var ts; name: "suppressImplicitAnyIndexErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, defaultValueDescription: false, @@ -40287,6 +40935,7 @@ var ts; name: "noStrictGenericChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, defaultValueDescription: false, @@ -40296,6 +40945,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, defaultValueDescription: ts.Diagnostics.true_for_ES2022_and_above_including_ESNext @@ -40304,6 +40954,7 @@ var ts; name: "preserveValueImports", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, defaultValueDescription: false, @@ -40347,6 +40998,8 @@ var ts; /* @internal */ ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; }); /* @internal */ + ts.affectsDeclarationPathOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsDeclarationPath; }); + /* @internal */ ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); /* @internal */ ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { @@ -41169,7 +41822,7 @@ var ts; return undefined; if (ts.length(specs) !== 1) return specs; - if (specs[0] === "**/*") + if (specs[0] === ts.defaultIncludeSpec) return undefined; return specs; } @@ -41202,6 +41855,7 @@ var ts; return optionDefinition.type; } } + /* @internal */ function getNameOfCompilerOptionValue(value, customTypeMap) { // There is a typeMap associated with this command-line option so use it to map value back to its name return ts.forEachEntry(customTypeMap, function (mapValue, key) { @@ -41210,6 +41864,7 @@ var ts; } }); } + ts.getNameOfCompilerOptionValue = getNameOfCompilerOptionValue; function serializeCompilerOptions(options, pathOptions) { return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); } @@ -41447,6 +42102,8 @@ var ts; // until consistent casing errors are reported return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } + /*@internal*/ + ts.defaultIncludeSpec = "**/*"; /** * Parse the contents of a config file from json or json source file (tsconfig.json). * @param json The contents of the config file to parse @@ -41512,6 +42169,7 @@ var ts; } var includeSpecs = toPropValue(getSpecsFromRaw("include")); var excludeOfRaw = getSpecsFromRaw("exclude"); + var isDefaultIncludeSpec = false; var excludeSpecs = toPropValue(excludeOfRaw); if (excludeOfRaw === "no-prop" && raw.compilerOptions) { var outDir = raw.compilerOptions.outDir; @@ -41521,7 +42179,8 @@ var ts; } } if (filesSpecs === undefined && includeSpecs === undefined) { - includeSpecs = ["**/*"]; + includeSpecs = [ts.defaultIncludeSpec]; + isDefaultIncludeSpec = true; } var validatedIncludeSpecs, validatedExcludeSpecs; // The exclude spec list is converted into a regular expression, which allows us to quickly @@ -41540,7 +42199,8 @@ var ts; validatedFilesSpec: ts.filter(filesSpecs, ts.isString), validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, - pathPatterns: undefined, // Initialized on first use + pathPatterns: undefined, + isDefaultIncludeSpec: isDefaultIncludeSpec, }; } function getFileNames(basePath) { @@ -42200,7 +42860,7 @@ var ts; } if (ts.isImplicitGlob(spec.substring(spec.lastIndexOf(ts.directorySeparator) + 1))) { return { - key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec), + key: ts.removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec)), flags: 1 /* WatchDirectoryFlags.Recursive */ }; } @@ -42370,16 +43030,18 @@ var ts; ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, diagnostics, resultFromCache) { - var _a; + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache) { + var _a, _b; if (resultFromCache) { (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = resultFromCache.affectingLocations).push.apply(_b, affectingLocations); return resultFromCache; } return { resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations, - resolutionDiagnostics: diagnostics + affectingLocations: affectingLocations, + resolutionDiagnostics: diagnostics, }; } function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { @@ -42568,6 +43230,7 @@ var ts; } } var failedLookupLocations = []; + var affectingLocations = []; var features = getDefaultNodeResolutionFeatures(options); // Unlike `import` statements, whose mode-calculating APIs are all guaranteed to return `undefined` if we're in an un-mode-ed module resolution // setting, type references will return their target mode regardless of options because of how the parser works, so we guard against the mode being @@ -42586,6 +43249,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -42602,15 +43266,17 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + var pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host); resolvedTypeReferenceDirective = { primary: primary, - resolvedFileName: resolvedFileName, - originalPath: arePathsEqual(fileName, resolvedFileName, host) ? undefined : fileName, + // If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedFileName: pathsAreEqual ? fileName : resolvedFileName, + originalPath: pathsAreEqual ? undefined : fileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName), }; } - result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, resolutionDiagnostics: diagnostics }; + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, affectingLocations: affectingLocations, resolutionDiagnostics: diagnostics }; perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, /*mode*/ resolutionMode, result); if (traceEnabled) traceResult(result); @@ -42685,17 +43351,7 @@ var ts; * Does not try `@types/${packageName}` - use a second pass if needed. */ function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ts.emptyArray, - features: NodeResolutionFeatures.None, - requestContainingDirectory: containingDirectory, - reportDiagnostic: ts.noop - }; + var moduleResolutionState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); return ts.forEachAncestorDirectory(containingDirectory, function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var nodeModulesFolder = ts.combinePaths(ancestorDirectory, "node_modules"); @@ -42792,7 +43448,7 @@ var ts; ts.createCacheWithRedirects = createCacheWithRedirects; function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { var cache; - return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries }; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries, getInternalMap: getInternalMap }; function getPackageJsonInfo(packageJsonPath) { return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); } @@ -42806,6 +43462,9 @@ var ts; var iter = cache === null || cache === void 0 ? void 0 : cache.entries(); return iter ? ts.arrayFrom(iter) : []; } + function getInternalMap() { + return cache; + } } function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); @@ -42909,15 +43568,18 @@ var ts; } ts.zipToModeAwareCache = zipToModeAwareCache; function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; }, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); - moduleNameToDirectoryMap.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + } function update(options) { updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); } @@ -42993,13 +43655,16 @@ var ts; } ts.createModuleResolutionCache = createModuleResolutionCache; function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { clear: clear, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + } } ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { @@ -43305,16 +43970,20 @@ var ts; function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.NodeNextDefault, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); + var tsconfigExtensions = [Extensions.TSConfig]; function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { var containingDirectory = ts.getDirectoryPath(containingFile); // es module file or cjs-like input file, use a variant of the legacy cjs resolver that supports the selected modern features var esmMode = resolutionMode === ts.ModuleKind.ESNext ? NodeResolutionFeatures.EsmMode : 0; - return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions, redirectedReference); + var extensions = compilerOptions.noDtsResolution ? [Extensions.TsOnly, Extensions.JavaScript] : tsExtensions; + if (compilerOptions.resolveJsonModule) { + extensions = __spreadArray(__spreadArray([], extensions, true), [Extensions.Json], false); + } + return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference); } - var jsOnlyExtensions = [Extensions.JavaScript]; - var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; - var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); - var tsconfigExtensions = [Extensions.TSConfig]; function tryResolveJSModuleWorker(moduleName, initialDir, host) { return nodeModuleNameResolverWorker(NodeResolutionFeatures.None, moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); } @@ -43340,6 +44009,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; // conditions are only used by the node16/nodenext resolver - there's no priority order in the list, //it's essentially a set (priority is determined by object insertion order in the object we look at). var conditions = features & NodeResolutionFeatures.EsmMode ? ["node", "import", "types"] : ["node", "require", "types"]; @@ -43352,6 +44022,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -43359,7 +44030,7 @@ var ts; reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; 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, diagnostics, state.resultFromCache); + 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) { var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); @@ -43385,8 +44056,10 @@ var ts; var resolvedValue = resolved_1.value; if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - var originalPath = arePathsEqual(path, resolvedValue.path, host) ? undefined : resolvedValue.path; - resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath }); + var pathsAreEqual = arePathsEqual(path, resolvedValue.path, host); + var originalPath = pathsAreEqual ? undefined : resolvedValue.path; + // If the path and realpath are differing only in casing prefer path so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedValue = __assign(__assign({}, resolvedValue), { path: pathsAreEqual ? resolvedValue.path : path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; @@ -43649,17 +44322,9 @@ var ts; var entrypoints; var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript; var features = getDefaultNodeResolutionFeatures(options); - var requireState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ["node", "require", "types"], - features: features, - requestContainingDirectory: packageJsonInfo.packageDirectory, - reportDiagnostic: ts.noop - }; + var requireState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); + requireState.conditions = ["node", "require", "types"]; + requireState.requestContainingDirectory = packageJsonInfo.packageDirectory; var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, /*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths); entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path); @@ -43732,22 +44397,27 @@ var ts; } } } - /** - * A function for locating the package.json scope for a given path - */ /*@internal*/ - function getPackageScopeForPath(fileName, packageJsonInfoCache, host, options) { - var state = { + function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) { + return { host: host, compilerOptions: options, traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], + failedLookupLocations: ts.noopPush, + affectingLocations: ts.noopPush, packageJsonInfoCache: packageJsonInfoCache, - features: 0, - conditions: [], + features: NodeResolutionFeatures.None, + conditions: ts.emptyArray, requestContainingDirectory: undefined, reportDiagnostic: ts.noop }; + } + ts.getTemporaryModuleResolutionState = getTemporaryModuleResolutionState; + /** + * A function for locating the package.json scope for a given path + */ + /*@internal*/ + function getPackageScopeForPath(fileName, state) { var parts = ts.getPathComponents(fileName); parts.pop(); while (parts.length > 0) { @@ -43774,6 +44444,7 @@ var ts; if (typeof existing !== "boolean") { if (traceEnabled) trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + state.affectingLocations.push(packageJsonPath); return existing; } else { @@ -43792,6 +44463,7 @@ var ts; var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined }; (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + state.affectingLocations.push(packageJsonPath); return result; } else { @@ -43916,7 +44588,7 @@ var ts; var _a, _b; var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope || !scope.packageJsonContent.exports) { return undefined; } @@ -43975,7 +44647,7 @@ var ts; } var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath); @@ -43997,13 +44669,38 @@ var ts; } return toSearchResult(/*value*/ undefined); } + /** + * @internal + * From https://github.com/nodejs/node/blob/8f39f51cbbd3b2de14b9ee896e26421cc5b20121/lib/internal/modules/esm/resolve.js#L722 - + * "longest" has some nuance as to what "longest" means in the presence of pattern trailers + */ + function comparePatternKeys(a, b) { + var aPatternIndex = a.indexOf("*"); + var bPatternIndex = b.indexOf("*"); + var baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + var baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + if (baseLenA > baseLenB) + return -1; + if (baseLenB > baseLenA) + return 1; + if (aPatternIndex === -1) + return 1; + if (bPatternIndex === -1) + return -1; + if (a.length > b.length) + return -1; + if (b.length > a.length) + return 1; + return 0; + } + ts.comparePatternKeys = comparePatternKeys; function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { 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); } - var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), function (a, b) { return a.length - b.length; }); + 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++) { var potentialTarget = expandingKeys_1[_i]; if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) { @@ -44322,8 +45019,8 @@ var ts; var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths); if (!pathAndExtension && packageInfo - && packageInfo.packageJsonContent.exports === undefined - && packageInfo.packageJsonContent.main === undefined + // eslint-disable-next-line no-null/no-null + && (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null) && state.features & NodeResolutionFeatures.EsmMode) { // EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume // a default `index.js` entrypoint if no `main` or `exports` are present @@ -44432,12 +45129,25 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: cache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: containingDirectory, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, + /*isExternalLibraryImport*/ false, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { @@ -44480,10 +45190,23 @@ var ts; trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; + var affectingLocations = []; var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: undefined, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: packageJsonInfoCache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: undefined, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false, /*cache*/ undefined, /*redirectedReference*/ undefined); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved, + /*isExternalLibraryImport*/ true, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -44849,7 +45572,7 @@ var ts; case 164 /* SyntaxKind.Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind, ", expected JSDocFunctionType"); }); + ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind), ", expected JSDocFunctionType"); }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -46033,8 +46756,6 @@ var ts; // - `BindingElement: BindingPattern Initializer?` // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization // - `BindingElement: BindingPattern Initializer?` - bindEach(node.decorators); - bindEach(node.modifiers); bind(node.dotDotDotToken); bind(node.propertyName); bind(node.initializer); @@ -46375,37 +47096,6 @@ var ts; typeLiteralSymbol.members.set(symbol.escapedName, symbol); } function bindObjectLiteralExpression(node) { - var ElementKind; - (function (ElementKind) { - ElementKind[ElementKind["Property"] = 1] = "Property"; - ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; - })(ElementKind || (ElementKind = {})); - if (inStrictMode && !ts.isAssignmentTarget(node)) { - var seen = new ts.Map(); - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 298 /* SyntaxKind.SpreadAssignment */ || prop.name.kind !== 79 /* SyntaxKind.Identifier */) { - continue; - } - var identifier = prop.name; - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 296 /* SyntaxKind.PropertyAssignment */ || prop.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || prop.kind === 169 /* SyntaxKind.MethodDeclaration */ - ? 1 /* ElementKind.Property */ - : 2 /* ElementKind.Accessor */; - var existingKind = seen.get(identifier.escapedText); - if (!existingKind) { - seen.set(identifier.escapedText, currentKind); - continue; - } - } - } return bindAnonymousDeclaration(node, 4096 /* SymbolFlags.ObjectLiteral */, "__object" /* InternalSymbolName.Object */); } function bindJsxAttributes(node) { @@ -47062,7 +47752,7 @@ var ts; } } function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { + if (ts.some(node.modifiers)) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level @@ -47099,12 +47789,14 @@ var ts; } } function setCommonJsModuleIndicator(node) { - if (file.externalModuleIndicator) { + if (file.externalModuleIndicator && file.externalModuleIndicator !== true) { return false; } if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } return true; } @@ -47518,7 +48210,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) && !ts.getJSDocTypeTag(node) && !(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */)) { + var possibleVariableDecl = node.kind === 254 /* SyntaxKind.VariableDeclaration */ ? node : node.parent.parent; + if (ts.isInJSFile(node) && + ts.isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && + !ts.getJSDocTypeTag(node) && + !(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* SymbolFlags.Alias */, 2097152 /* SymbolFlags.AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -47708,10 +48404,11 @@ var ts; } function isExportsOrModuleExportsOrAlias(sourceFile, node) { var i = 0; - var q = [node]; - while (q.length && i < 100) { + var q = ts.createQueue(); + q.enqueue(node); + while (!q.isEmpty() && i < 100) { i++; - node = q.shift(); + node = q.dequeue(); if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) { return true; } @@ -47719,10 +48416,10 @@ var ts; var symbol = lookupSymbolForName(sourceFile, node.escapedText); if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) { var init = symbol.valueDeclaration.initializer; - q.push(init); + q.enqueue(init); if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) { - q.push(init.left); - q.push(init.right); + q.enqueue(init.left); + q.enqueue(init.right); } } } @@ -47982,7 +48679,10 @@ var ts; TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; - TypeFacts[TypeFacts["All"] = 16777215] = "All"; + TypeFacts[TypeFacts["IsUndefined"] = 16777216] = "IsUndefined"; + TypeFacts[TypeFacts["IsNull"] = 33554432] = "IsNull"; + TypeFacts[TypeFacts["IsUndefinedOrNull"] = 50331648] = "IsUndefinedOrNull"; + TypeFacts[TypeFacts["All"] = 134217727] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. @@ -48024,25 +48724,17 @@ var ts; TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; - TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["VoidFacts"] = 9830144] = "VoidFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 26607360] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 42917664] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 83427327] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 83886079] = "EmptyObjectFacts"; + TypeFacts[TypeFacts["UnknownFacts"] = 83886079] = "UnknownFacts"; TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE"; - TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; // Masks TypeFacts[TypeFacts["OrFactsMask"] = 8256] = "OrFactsMask"; - TypeFacts[TypeFacts["AndFactsMask"] = 16768959] = "AndFactsMask"; - })(TypeFacts || (TypeFacts = {})); - var typeofEQFacts = new ts.Map(ts.getEntries({ - string: 1 /* TypeFacts.TypeofEQString */, - number: 2 /* TypeFacts.TypeofEQNumber */, - bigint: 4 /* TypeFacts.TypeofEQBigInt */, - boolean: 8 /* TypeFacts.TypeofEQBoolean */, - symbol: 16 /* TypeFacts.TypeofEQSymbol */, - undefined: 65536 /* TypeFacts.EQUndefined */, - object: 32 /* TypeFacts.TypeofEQObject */, - function: 64 /* TypeFacts.TypeofEQFunction */ - })); + TypeFacts[TypeFacts["AndFactsMask"] = 134209471] = "AndFactsMask"; + })(TypeFacts = ts.TypeFacts || (ts.TypeFacts = {})); var typeofNEFacts = new ts.Map(ts.getEntries({ string: 256 /* TypeFacts.TypeofNEString */, number: 512 /* TypeFacts.TypeofNENumber */, @@ -48077,7 +48769,7 @@ var ts; CheckMode[CheckMode["RestBindingElement"] = 64] = "RestBindingElement"; // e.g. in `const { a, ...rest } = foo`, when checking the type of `foo` to determine the type of `rest`, // we need to preserve generic types instead of substituting them for constraints - })(CheckMode || (CheckMode = {})); + })(CheckMode = ts.CheckMode || (ts.CheckMode = {})); var SignatureCheckMode; (function (SignatureCheckMode) { SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback"; @@ -48085,7 +48777,7 @@ var ts; SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes"; SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity"; SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback"; - })(SignatureCheckMode || (SignatureCheckMode = {})); + })(SignatureCheckMode = ts.SignatureCheckMode || (ts.SignatureCheckMode = {})); var IntersectionState; (function (IntersectionState) { IntersectionState[IntersectionState["None"] = 0] = "None"; @@ -48419,7 +49111,7 @@ var ts; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); - return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + return node ? getContextualTypeForObjectLiteralElement(node, /*contextFlags*/ undefined) : undefined; }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -48427,7 +49119,7 @@ var ts; }, getContextualTypeForJsxAttribute: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); - return node && getContextualTypeForJsxAttribute(node); + return node && getContextualTypeForJsxAttribute(node, /*contextFlags*/ undefined); }, isContextSensitive: isContextSensitive, getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, @@ -48541,9 +49233,9 @@ var ts; return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, - tryGetThisTypeAt: function (nodeIn, includeGlobalThis) { + tryGetThisTypeAt: function (nodeIn, includeGlobalThis, container) { var node = ts.getParseTreeNode(nodeIn); - return node && tryGetThisTypeAt(node, includeGlobalThis); + return node && tryGetThisTypeAt(node, includeGlobalThis, container); }, getTypeArgumentConstraint: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); @@ -48633,6 +49325,7 @@ var ts; var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); var subtypeReductionCache = new ts.Map(); + var cachedTypes = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var markerTypes = new ts.Set(); @@ -48641,11 +49334,10 @@ var ts; var unresolvedSymbols = new ts.Map(); var errorTypes = new ts.Map(); var anyType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); - var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); + var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 262144 /* ObjectFlags.NonInferrableType */); var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error"); var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved"); - var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); @@ -48674,8 +49366,7 @@ var ts; var esSymbolType = createIntrinsicType(4096 /* TypeFlags.ESSymbol */, "symbol"); var voidType = createIntrinsicType(16384 /* TypeFlags.Void */, "void"); var neverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); + var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* TypeFlags.NonPrimitive */, "object"); @@ -48685,16 +49376,30 @@ var ts; var numberOrBigIntType = getUnionType([numberType, bigintType]); var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]); var numericStringType = getTemplateLiteralType(["", ""], [numberType]); // The `${number}` type - var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }); - var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }); + var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }, function () { return "(restrictive mapper)"; }); + var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }, function () { return "(permissive mapper)"; }); var uniqueLiteralType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); // `uniqueLiteralType` is a special `never` flagged by union reduction to behave as a literal - var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }); // replace all type parameters with the unique literal type (disregarding constraints) + var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }, function () { return "(unique literal mapper)"; }); // replace all type parameters with the unique literal type (disregarding constraints) + var outofbandVarianceMarkerHandler; + var reportUnreliableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); + } + return t; + }, function () { return "(unmeasurable reporter)"; }); + var reportUnmeasurableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); + } + return t; + }, function () { return "(unreliable reporter)"; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyJsxObjectType.objectFlags |= 2048 /* ObjectFlags.JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* SymbolFlags.TypeLiteral */, "__type" /* InternalSymbolName.Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray)]) : unknownType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyGenericType.instantiations = new ts.Map(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); @@ -48708,6 +49413,9 @@ var ts; var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); + var markerSuperTypeForCheck = createTypeParameter(); + var markerSubTypeForCheck = createTypeParameter(); + markerSubTypeForCheck.constraint = markerSuperTypeForCheck; var noTypePredicate = createTypePredicate(1 /* TypePredicateKind.Identifier */, "<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); @@ -48837,21 +49545,13 @@ var ts; var potentialNewTargetCollisions = []; var potentialWeakMapSetCollisions = []; var potentialReflectCollisions = []; + var potentialUnusedRenamedBindingElementsInTypes = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); - var typeofTypesByName = new ts.Map(ts.getEntries({ - string: stringType, - number: numberType, - bigint: bigintType, - boolean: booleanType, - symbol: esSymbolType, - undefined: undefinedType - })); var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var outofbandVarianceMarkerHandler; var subtypeRelation = new ts.Map(); var strictSubtypeRelation = new ts.Map(); var assignableRelation = new ts.Map(); @@ -48877,6 +49577,14 @@ var ts; ]; initializeTypeChecker(); return checker; + function getCachedType(key) { + return key ? cachedTypes.get(key) : undefined; + } + function setCachedType(key, type) { + if (key) + cachedTypes.set(key, type); + return type; + } function getJsxNamespace(location) { if (location) { var file = ts.getSourceFileOfNode(location); @@ -49741,6 +50449,7 @@ var ts; if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 111551 /* SymbolFlags.Value */)) { // Remember the property node, it will be used later to report appropriate error + ts.Debug.assertNode(location, ts.isPropertyDeclaration); propertyWithInvalidInitializer = location; } } @@ -49930,11 +50639,27 @@ var ts; } } } + // The invalid initializer error is needed in two situation: + // 1. When result is undefined, after checking for a missing "this." + // 2. When result is defined + function checkAndReportErrorForInvalidInitializer() { + if (propertyWithInvalidInitializer && !(useDefineForClassFields && ts.getEmitScriptTarget(compilerOptions) >= 9 /* ScriptTarget.ES2022 */)) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed + // with ESNext+useDefineForClassFields because the scope semantics are different. + error(errorLocation, errorLocation && propertyWithInvalidInitializer.type && ts.textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) + ? ts.Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor + : ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg)); + return true; + } + return false; + } if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(function () { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForInvalidInitializer() && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && @@ -49942,7 +50667,16 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { + var suggestedLib = void 0; + // Report missing lib first + if (nameArg) { + suggestedLib = getSuggestedLibForNonExistentName(nameArg); + if (suggestedLib) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib); + } + } + // then spelling suggestions + if (!suggestedLib && getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -49961,16 +50695,9 @@ var ts; } } } - if (!suggestion) { - if (nameArg) { - var lib = getSuggestedLibForNonExistentName(nameArg); - if (lib) { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib); - } - else { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); - } - } + // And then fall back to unspecified "not found" + if (!suggestion && !suggestedLib && nameArg) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); } suggestionCount++; } @@ -49978,12 +50705,7 @@ var ts; } return undefined; } - if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ScriptTarget.ESNext */ && useDefineForClassFields)) { - // We have a match, but the reference occurred within a property initializer and the identifier also binds - // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed - // with ESNext+useDefineForClassFields because the scope semantics are different. - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + else if (checkAndReportErrorForInvalidInitializer()) { return undefined; } // Perform extra checks only if error reporting was requested @@ -50085,7 +50807,7 @@ var ts; if (decl.kind === 163 /* SyntaxKind.TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); } } } @@ -50194,7 +50916,12 @@ var ts; function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { if (isPrimitiveTypeName(name)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(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)); + } + else { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + } return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); @@ -50214,6 +50941,16 @@ var ts; } return false; } + function isExtendedByInterface(node) { + var grandparent = node.parent.parent; + var parentOfGrandparent = grandparent.parent; + if (grandparent && parentOfGrandparent) { + var isExtending = ts.isHeritageClause(grandparent) && grandparent.token === 94 /* SyntaxKind.ExtendsKeyword */; + var isInterface = ts.isInterfaceDeclaration(parentOfGrandparent); + return isExtending && isInterface; + } + return false; + } function maybeMappedType(node, symbol) { var container = ts.findAncestor(node.parent, function (n) { return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit"; @@ -50345,7 +51082,8 @@ var ts; && isAliasableOrJsExpression(node.parent.right) || node.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || node.kind === 296 /* SyntaxKind.PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node); + || node.kind === 254 /* SyntaxKind.VariableDeclaration */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) + || node.kind === 203 /* SyntaxKind.BindingElement */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -50438,7 +51176,7 @@ var ts; return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker - return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); + return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { var _a; @@ -50716,10 +51454,6 @@ var ts; checkExpressionCached(expression); return getNodeLinks(expression).resolvedSymbol; } - function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) { - var expression = node.initializer; - return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve); - } function getTargetOfAccessExpression(node, dontRecursivelyResolve) { if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */)) { return undefined; @@ -50751,7 +51485,7 @@ var ts; case 297 /* SyntaxKind.ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); case 296 /* SyntaxKind.PropertyAssignment */: - return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); + return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); case 207 /* SyntaxKind.ElementAccessExpression */: case 206 /* SyntaxKind.PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); @@ -51156,7 +51890,40 @@ var ts; // An override clause will take effect for type-only imports and import types, and allows importing the types across formats, regardless of // normal mode restrictions if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext && !ts.getResolutionModeOverrideForClause(overrideClause)) { - error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); + if (ts.findAncestor(location, ts.isImportEqualsDeclaration)) { + // ImportEquals in a ESM file resolving to another ESM file + error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); + } + else { + // CJS file resolving to an ESM file + var diagnosticDetails = void 0; + var ext = ts.tryGetExtensionFromPath(currentSourceFile.fileName); + if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) { + var scope = currentSourceFile.packageJsonScope; + var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined; + if (scope && !scope.packageJsonContent.type) { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json")); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, ts.combinePaths(scope.packageDirectory, "package.json")); + } + } + else { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, targetExt); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module); + } + } + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(diagnosticDetails, ts.Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, moduleReference))); + } } } // merged symbol is module declaration symbol combined with all augmentations @@ -51665,8 +52432,9 @@ var ts; function getExportSymbolOfValueSymbolIfExported(symbol) { return getMergedSymbol(symbol && (symbol.flags & 1048576 /* SymbolFlags.ExportValue */) !== 0 && symbol.exportSymbol || symbol); } - function symbolIsValue(symbol) { - return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && !getTypeOnlyAliasDeclaration(symbol)); + function symbolIsValue(symbol, includeTypeOnlyMembers) { + return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || + symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -51706,7 +52474,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getStringLiteralType)); + return getUnionType(ts.arrayFrom(typeofNEFacts.keys(), getStringLiteralType)); } function createTypeParameter(symbol) { var type = createType(262144 /* TypeFlags.TypeParameter */); @@ -52115,13 +52883,25 @@ var ts; && isDeclarationVisible(declaration.parent)) { return addVisibleAlias(declaration, declaration); } - else if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isBindingElement(declaration) && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement - && ts.isVariableDeclaration(declaration.parent.parent) - && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) - && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) - && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) - && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { - return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + else if (ts.isBindingElement(declaration)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement + && ts.isVariableDeclaration(declaration.parent.parent) + && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) + && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) + && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) + && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + } + else if (symbol.flags & 2 /* SymbolFlags.BlockScopedVariable */) { + var variableStatement = ts.findAncestor(declaration, ts.isVariableStatement); + if (ts.hasSyntacticModifier(variableStatement, 1 /* ModifierFlags.Export */)) { + return true; + } + if (!isDeclarationVisible(variableStatement.parent)) { + return false; + } + return addVisibleAlias(declaration, variableStatement); + } } // Declaration is not visible return false; @@ -52163,6 +52943,9 @@ var ts; if (symbol && symbol.flags & 262144 /* SymbolFlags.TypeParameter */ && meaning & 788968 /* SymbolFlags.Type */) { return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; } + if (!symbol && ts.isThisIdentifier(firstIdentifier) && isSymbolAccessible(getSymbolOfNode(ts.getThisContainer(firstIdentifier, /*includeArrowFunctions*/ false)), firstIdentifier, meaning, /*computeAliases*/ false).accessibility === 0 /* SymbolAccessibility.Accessible */) { + return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; + } // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* SymbolAccessibility.NotAccessible */, @@ -52251,7 +53034,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* TypeFormatFlags.None */; } - return flags & 814775659 /* TypeFormatFlags.NodeBuilderFlagsMask */; + return flags & 848330091 /* TypeFormatFlags.NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { return !!type.symbol && !!(type.symbol.flags & 32 /* SymbolFlags.Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* TypeFlags.Object */) && !!(ts.getObjectFlags(type) & 16777216 /* ObjectFlags.IsClassInstanceClone */))); @@ -52353,6 +53136,12 @@ var ts; return context.truncating = context.approximateLength > ((context.flags & 1 /* NodeBuilderFlags.NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { + var savedFlags = context.flags; + var typeNode = typeToTypeNodeWorker(type, context); + context.flags = savedFlags; + return typeNode; + } + function typeToTypeNodeWorker(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); } @@ -52492,6 +53281,9 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* SymbolFlags.Class */)) return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes); + if (ts.length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) { + return ts.factory.createArrayTypeNode(typeArgumentNodes[0]); + } return symbolToTypeNode(type.aliasSymbol, context, 788968 /* SymbolFlags.Type */, typeArgumentNodes); } var objectFlags = ts.getObjectFlags(type); @@ -52528,8 +53320,8 @@ var ts; if (type.symbol) { return symbolToTypeNode(type.symbol, context, 788968 /* SymbolFlags.Type */); } - var name = (type === markerSuperType || type === markerSubType) && varianceTypeParameter && varianceTypeParameter.symbol ? - (type === markerSubType ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; + var name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? + (type === markerSubTypeForCheck ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name), /*typeArguments*/ undefined); } if (type.flags & 1048576 /* TypeFlags.Union */ && type.origin) { @@ -52595,7 +53387,7 @@ var ts; var name = typeParameterToName(newParam, context); var newTypeVariable = ts.factory.createTypeReferenceNode(name); context.approximateLength += 37; // 15 each for two added conditionals, 7 for an added infer type - var newMapper = prependTypeMapping(type.root.checkType, newParam, type.combinedMapper || type.mapper); + var newMapper = prependTypeMapping(type.root.checkType, newParam, type.mapper); var saveInferTypeParameters_1 = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode_1 = typeToTypeNodeHelper(instantiateType(type.root.extendsType, newMapper), context); @@ -52636,6 +53428,10 @@ var ts; } return typeToTypeNodeHelper(type, context); } + function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) { + return isMappedTypeWithKeyofConstraintDeclaration(type) + && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */); + } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 524288 /* TypeFlags.Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -52645,7 +53441,7 @@ var ts; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` - if (!(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { var newParam = createTypeParameter(createSymbol(262144 /* SymbolFlags.TypeParameter */, "T")); var name = typeParameterToName(newParam, context); newTypeVariable = ts.factory.createTypeReferenceNode(name); @@ -52661,11 +53457,12 @@ var ts; var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; var result = ts.setEmitFlags(mappedTypeNode, 1 /* EmitFlags.SingleLine */); - if (isMappedTypeWithKeyofConstraintDeclaration(type) && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { // homomorphic mapped type with a non-homomorphic naive inlining // wrap it with a conditional like `SomeModifiersType extends infer U ? {..the mapped type...} : never` to ensure the resulting // type stays homomorphic - return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); + var originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type.declaration.typeParameter.constraint.type)) || unknownType, type.mapper); + return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* TypeFlags.Unknown */ ? undefined : typeToTypeNodeHelper(originalConstraint, context))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); } return result; } @@ -52682,7 +53479,7 @@ var ts; // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* SymbolFlags.Class */ && !getBaseTypeVariableOfClass(symbol) - && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 226 /* SyntaxKind.ClassExpression */ && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */) || + && !(symbol.valueDeclaration && ts.isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */ && (!ts.isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*computeAliases*/ false).accessibility !== 0 /* SymbolAccessibility.Accessible */)) || symbol.flags & (384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -52948,7 +53745,7 @@ var ts; var id = ids_1[_i]; qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id; } - return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf); + return ts.factory.updateImportTypeNode(root, root.argument, root.assertions, qualifier, typeArguments, root.isTypeOf); } else { // first shift type arguments @@ -53052,7 +53849,7 @@ var ts; anyType : getNonMissingTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* CheckFlags.Late */ && isLateBoundName(propertySymbol.escapedName)) { + if (context.tracker.trackSymbol && isLateBoundName(propertySymbol.escapedName)) { if (propertySymbol.declarations) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { @@ -53197,7 +53994,6 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, @@ -53209,8 +54005,7 @@ var ts; context.encounteredError = true; } context.approximateLength += (name.length + 4); - return ts.factory.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + return ts.factory.createIndexSignature(indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { var _a, _b, _c, _d; @@ -53229,7 +54024,7 @@ var ts; var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* CheckFlags.RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 171 /* SyntaxKind.Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); - var thisParameter = tryGetThisParameterDeclaration(signature, context); + var thisParameter = context.flags & 33554432 /* NodeBuilderFlags.OmitThisParameter */ ? undefined : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { parameters.unshift(thisParameter); } @@ -53262,15 +54057,15 @@ var ts; var node = kind === 174 /* SyntaxKind.CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 175 /* SyntaxKind.ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 168 /* SyntaxKind.MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(modifiers, parameters, /*body*/ undefined) : + kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 317 /* SyntaxKind.JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 179 /* SyntaxKind.FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : kind === 180 /* SyntaxKind.ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : kind === 213 /* SyntaxKind.FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : kind === 214 /* SyntaxKind.ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); @@ -53287,7 +54082,6 @@ var ts; var thisTag = ts.getJSDocThisTag(signature.declaration); if (thisTag && thisTag.typeExpression) { return ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); @@ -53319,7 +54113,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); - var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined; + var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && ts.canHaveModifiers(parameterDeclaration) ? ts.map(ts.getModifiers(parameterDeclaration), ts.factory.cloneNode) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* CheckFlags.RestParameter */; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -53330,21 +54124,27 @@ var ts; ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* CheckFlags.OptionalParameter */; var questionToken = isOptional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined; - var parameterNode = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + var parameterNode = ts.factory.createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { - return elideInitializerAndSetEmitFlags(node); - function elideInitializerAndSetEmitFlags(node) { + return elideInitializerAndPropertyRenamingAndSetEmitFlags(node); + function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) { if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { trackComputedName(node.expression, context.enclosingDeclaration, context); } - var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags); if (ts.isBindingElement(visited)) { - visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, - /*initializer*/ undefined); + if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, + /* propertyName*/ undefined, visited.propertyName, + /*initializer*/ undefined); + } + else { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, + /*initializer*/ undefined); + } } if (!ts.nodeIsSynthesized(visited)) { visited = ts.factory.cloneNode(visited); @@ -53553,6 +54353,7 @@ var ts; return symbol.parent ? ts.factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var _a, _b, _c, _d; var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module var isTypeOf = meaning === 111551 /* SymbolFlags.Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { @@ -53570,6 +54371,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral("import")) ]))); + (_b = (_a = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _b === void 0 ? void 0 : _b.call(_a); } } if (!specifier) { @@ -53589,6 +54391,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral(swappedMode === ts.ModuleKind.ESNext ? "import" : "require")) ]))); + (_d = (_c = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _d === void 0 ? void 0 : _d.call(_c); } } if (!assertion) { @@ -53990,9 +54793,7 @@ var ts; } if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdotToken*/ undefined, "x", /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); @@ -54000,14 +54801,13 @@ var ts; if (ts.isJSDocFunctionType(node)) { if (ts.isJSDocConstructSignature(node)) { var newTypeNode_1; - return ts.factory.createConstructorTypeNode(node.modifiers, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createConstructorTypeNode( + /*modifiers*/ undefined, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } else { return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } @@ -54026,7 +54826,7 @@ var ts; !(ts.length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) { return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); } - return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.assertions, node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { var _a = trackExistingEntityName(node, context, includePrivateSymbol), introducesError = _a.introducesError, result = _a.node; @@ -54078,7 +54878,7 @@ var ts; } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 169 /* SyntaxKind.MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -54139,8 +54939,7 @@ var ts; var name_3 = ns.name; var body = ns.body; if (ts.length(excessExports)) { - ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, + ns = ts.factory.updateModuleDeclaration(ns, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, /*alias*/ undefined, id); })), /*moduleSpecifier*/ undefined)], false)))); @@ -54166,7 +54965,6 @@ var ts; if (ts.length(exports) > 1) { var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; }); statements = __spreadArray(__spreadArray([], nonExports, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), /*moduleSpecifier*/ undefined)], false); @@ -54181,7 +54979,6 @@ var ts; // remove group members from statements and then merge group members and add back to statements statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), true), [ ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier) ], false); @@ -54221,7 +55018,7 @@ var ts; } else { // some items filtered, others not - update the export declaration - statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); + statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); } } return statements; @@ -54286,12 +55083,11 @@ var ts; if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) { var oldContext = context; context = cloneNodeBuilderContext(context); - var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); + serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); if (context.reportedDiagnostic) { oldcontext.reportedDiagnostic = context.reportedDiagnostic; // hoist diagnostic result into outer context } context = oldContext; - return result; } } // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias @@ -54372,7 +55168,6 @@ var ts; && ((_d = type.symbol) === null || _d === void 0 ? void 0 : _d.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, alias, localName)])), 0 /* ModifierFlags.None */); context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* SymbolFlags.Value */); @@ -54405,7 +55200,6 @@ var ts; // ``` // To create an export named `g` that does _not_ shadow the local `g` addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name, localName)])), 0 /* ModifierFlags.None */); needsExportDeclaration = false; @@ -54454,16 +55248,15 @@ var ts; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); if (!resolvedModule) continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); } } } if (needsPostExportDefault) { - addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportAssignment(/*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); } else if (needsExportDeclaration) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* ModifierFlags.None */); } @@ -54531,7 +55324,7 @@ var ts; && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); - addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); + addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; context.enclosingDeclaration = oldEnclosingDecl; } @@ -54547,7 +55340,6 @@ var ts; var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* SymbolFlags.Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), constructSignatures, true), callSignatures, true), members, true)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { @@ -54573,7 +55365,6 @@ var ts; var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* InternalSymbolName.ExportEquals */; }), function (s) { var _a, _b; @@ -54590,13 +55381,11 @@ var ts; return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name === targetName ? undefined : targetName, name); })))]); addResult(ts.factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* NodeFlags.Namespace */), 0 /* ModifierFlags.None */); } } function serializeEnum(symbol, symbolName, modifierFlags) { - addResult(ts.factory.createEnumDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { + addResult(ts.factory.createEnumDeclaration(ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { // TODO: Handle computed names // I hate that to get the initialized value we need to walk back to the declarations here; but there's no // other way to get the possible const value of an enum member that I'm aware of, as the value is cached @@ -54657,7 +55446,7 @@ var ts; // emit akin to the above would be needed. // Add a namespace // Create namespace as non-synthetic so it is usable as an enclosing declaration - var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace, enclosingDeclaration); fakespace.locals = ts.createSymbolTable(props); fakespace.symbol = props[0].parent; @@ -54676,11 +55465,10 @@ var ts; results = oldResults; // replace namespace with synthetic version var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, d.expression, ts.factory.createIdentifier("default" /* InternalSymbolName.Default */))])) : d; }); var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* ModifierFlags.Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced; - fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); + fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); addResult(fakespace, modifierFlags); // namespaces can never be default exported } } @@ -54736,7 +55524,7 @@ var ts; ? getBaseConstructorTypeOfClass(staticType) : anyType; var heritageClauses = __spreadArray(__spreadArray([], !ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], true), !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(117 /* SyntaxKind.ImplementsKeyword */, implementsExpressions)], true); - var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); + var symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties @@ -54754,7 +55542,6 @@ var ts; // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? [ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -54771,12 +55558,11 @@ var ts; ts.isInJSFile(symbol.valueDeclaration) && !ts.some(getSignaturesOfType(staticType, 1 /* SignatureKind.Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? - [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : + [ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : serializeSignatures(1 /* SignatureKind.Construct */, staticType, staticBaseType, 171 /* SyntaxKind.Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), staticMembers, true), constructors, true), publicProperties, true), privateProperties, true)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags); } function getSomeTargetNameFromDeclarations(declarations) { @@ -54828,7 +55614,6 @@ var ts; var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier( /*isTypeOnly*/ false, propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1), /*importClause*/ undefined), 0 /* ModifierFlags.None */); @@ -54852,12 +55637,10 @@ var ts; var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); // 'y' // import _x = require('y'); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* ModifierFlags.None */); // import x = _x.z addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); break; @@ -54874,7 +55657,6 @@ var ts; // an external `import localName = require("whatever")` var isLocalImport = !(target.flags & 512 /* SymbolFlags.ValueModule */) && !ts.isVariableDeclaration(node); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), isLocalImport ? symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false) @@ -54888,7 +55670,6 @@ var ts; break; case 267 /* SyntaxKind.ImportClause */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag @@ -54898,19 +55679,16 @@ var ts; break; case 268 /* SyntaxKind.NamespaceImport */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), /*assertClause*/ undefined), 0 /* ModifierFlags.None */); break; case 274 /* SyntaxKind.NamespaceExport */: addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* ModifierFlags.None */); break; case 270 /* SyntaxKind.ImportSpecifier */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamedImports([ @@ -54949,7 +55727,6 @@ var ts; } function serializeExportSpecifier(localName, targetName, specifier) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* ModifierFlags.None */); } @@ -54990,7 +55767,6 @@ var ts; context.tracker.trackSymbol = function () { return false; }; if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* SymbolFlags.All */))); } else { @@ -55005,7 +55781,6 @@ var ts; // serialize as `import _Ref = t.arg.et; export { _Ref as name }` var varName = getUnusedName(name, symbol); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false)), 0 /* ModifierFlags.None */); serializeExportSpecifier(name, varName); @@ -55036,7 +55811,6 @@ var ts; } if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName))); return true; } @@ -55086,9 +55860,7 @@ var ts; if (p.flags & 98304 /* SymbolFlags.Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SymbolFlags.SetAccessor */) { - result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], @@ -55096,8 +55868,7 @@ var ts; } if (p.flags & 32768 /* SymbolFlags.GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* ModifierFlags.Private */; - result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; @@ -55105,8 +55876,7 @@ var ts; // This is an else/if as accessors and properties can't merge in TS, but might in JS // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* SymbolFlags.Property */ | 3 /* SymbolFlags.Variable */ | 98304 /* SymbolFlags.Accessor */)) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); @@ -55115,8 +55885,7 @@ var ts; var type = getTypeOfSymbol(p); var signatures = getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (flag & 8 /* ModifierFlags.Private */) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, /*type*/ undefined, /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } @@ -55174,8 +55943,7 @@ var ts; } } if (privateProtected) { - return [ts.setTextRange(ts.factory.createConstructorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), + return [ts.setTextRange(ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(privateProtected), /*parameters*/ [], /*body*/ undefined), signatures[0].declaration)]; } @@ -55874,7 +56642,7 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 32768 /* TypeFlags.Undefined */) ? getNonUndefinedType(type) : type; + return strictNullChecks && !(getTypeFacts(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 16777216 /* TypeFacts.IsUndefined */) ? getNonUndefinedType(type) : type; } return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)], 2 /* UnionReduction.Subtype */)); } @@ -56275,7 +57043,7 @@ var ts; (resolvedSymbol || symbol).exports.forEach(function (s, name) { var _a; var exportedMember = members_4.get(name); - if (exportedMember && exportedMember !== s) { + if (exportedMember && exportedMember !== s && !(s.flags & 2097152 /* SymbolFlags.Alias */)) { if (s.flags & 111551 /* SymbolFlags.Value */ && exportedMember.flags & 111551 /* SymbolFlags.Value */) { // If the member has an additional value-like declaration, union the types from the two declarations, // but issue an error if they occurred in two different files. The purpose is to support a JS file with @@ -56309,6 +57077,17 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.indexInfos); + if (initialSize === members_4.size) { + if (type.aliasSymbol) { + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = type.aliasTypeArguments; + } + if (ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */) { + result.aliasSymbol = type.symbol; + var args = getTypeArguments(type); + result.aliasTypeArguments = ts.length(args) ? args : undefined; + } + } result.objectFlags |= (ts.getObjectFlags(type) & 4096 /* ObjectFlags.JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* SymbolFlags.Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { result.objectFlags |= 16777216 /* ObjectFlags.IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type @@ -56360,11 +57139,7 @@ var ts; if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAny(element, anyType); } - // When we're including the pattern in the type (an indication we're obtaining a contextual type), we - // use the non-inferrable any type. Inference will never directly infer this type, but it is possible - // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases, - // widening of the binding pattern type substitutes a regular any for the non-inferrable any. - return includePatternInType ? nonInferrableAnyType : anyType; + return anyType; } // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { @@ -57365,7 +58140,7 @@ var ts; error(declaration.typeExpression.type, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } else { - error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + error(ts.isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } } links.declaredType = type; @@ -58669,6 +59444,9 @@ var ts; else if (type.objectFlags & 32 /* ObjectFlags.Mapped */) { resolveMappedTypeMembers(type); } + else { + ts.Debug.fail("Unhandled object type " + ts.Debug.formatObjectFlags(type.objectFlags)); + } } else if (type.flags & 1048576 /* TypeFlags.Union */) { resolveUnionTypeMembers(type); @@ -58676,6 +59454,9 @@ var ts; else if (type.flags & 2097152 /* TypeFlags.Intersection */) { resolveIntersectionTypeMembers(type); } + else { + ts.Debug.fail("Unhandled type " + ts.Debug.formatTypeFlags(type.flags)); + } } return type; } @@ -58863,7 +59644,7 @@ var ts; } } } - else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { hasDisjointDomainType = true; } } @@ -58875,12 +59656,13 @@ var ts; // intersection operation to reduce the union constraints. for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { var t = types_6[_a]; - if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { constraints = ts.append(constraints, t); } } } - return getIntersectionType(constraints); + // The source types were normalized; ensure the result is normalized too. + return getNormalizedType(getIntersectionType(constraints), /*writing*/ false); } return undefined; } @@ -58991,7 +59773,7 @@ var ts; } if (t.flags & 268435456 /* TypeFlags.StringMapping */) { var constraint = getBaseConstraint(t.type); - return constraint ? getStringMappingType(t.symbol, constraint) : stringType; + return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType; } if (t.flags & 8388608 /* TypeFlags.IndexedAccess */) { if (isMappedTypeGenericIndexedAccess(t)) { @@ -59077,7 +59859,7 @@ var ts; var objectType; return !!(type.flags & 8388608 /* TypeFlags.IndexedAccess */ && ts.getObjectFlags(objectType = type.objectType) & 32 /* ObjectFlags.Mapped */ && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && - !objectType.declaration.questionToken && !objectType.declaration.nameType); + !(getMappedTypeModifiers(objectType) & 8 /* MappedTypeModifiers.ExcludeOptional */) && !objectType.declaration.nameType); } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, @@ -59356,12 +60138,12 @@ var ts; * @param type a type to look up property from * @param name a name of property to look up in a given type */ - function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment) { + function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) { type = getReducedApparentType(type); if (type.flags & 524288 /* TypeFlags.Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { + if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) { return symbol; } if (skipObjectFunctionPropertyAugment) @@ -59467,12 +60249,15 @@ var ts; // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(declaration) { + var _a; var result; - for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { - var node = _a[_i]; + for (var _i = 0, _b = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _b.length; _i++) { + var node = _b[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); } - return result; + return (result === null || result === void 0 ? void 0 : result.length) ? result + : ts.isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) === null || _a === void 0 ? void 0 : _a.typeParameters + : undefined; } function symbolsToArray(symbols) { var result = []; @@ -60023,8 +60808,7 @@ var ts; var _a; var inferences; if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { - for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; + var _loop_15 = function (declaration) { if (declaration.parent.kind === 190 /* SyntaxKind.InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the @@ -60032,12 +60816,12 @@ var ts; // present, we form an intersection of the inferred constraint types. var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; if (grandParent.kind === 178 /* SyntaxKind.TypeReference */ && !omitTypeReferences) { - var typeReference = grandParent; - var typeParameters = getTypeParametersForTypeReference(typeReference); - if (typeParameters) { - var index = typeReference.typeArguments.indexOf(childTypeParameter); - if (index < typeParameters.length) { - var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + var typeReference_1 = grandParent; + var typeParameters_1 = getTypeParametersForTypeReference(typeReference_1); + if (typeParameters_1) { + var index = typeReference_1.typeArguments.indexOf(childTypeParameter); + if (index < typeParameters_1.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters_1[index]); if (declaredConstraint) { // Type parameter constraints can reference other type parameters so // constraints need to be instantiated. If instantiation produces the @@ -60045,7 +60829,9 @@ var ts; // type Foo = [T, U]; // type Bar = T extends Foo ? Foo : T; // the instantiated constraint for U is X, so we discard that inference. - var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var mapper = makeDeferredTypeMapper(typeParameters_1, typeParameters_1.map(function (_, index) { return function () { + return getEffectiveTypeArgumentAtIndex(typeReference_1, typeParameters_1, index); + }; })); var constraint = instantiateType(declaredConstraint, mapper); if (constraint !== typeParameter) { inferences = ts.append(inferences, constraint); @@ -60083,6 +60869,10 @@ var ts; inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); } } + }; + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + _loop_15(declaration); } } return inferences && getIntersectionType(inferences); @@ -60145,13 +60935,13 @@ var ts; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type - // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // of an object literal or a non-inferrable type. This is because there are operations in the type checker // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type = types_8[_i]; - if (!(type.flags & excludeKinds)) { + if (excludeKinds === undefined || !(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } } @@ -60163,7 +60953,7 @@ var ts; if (!type) { type = createObjectType(4 /* ObjectFlags.Reference */, target.symbol); target.instantiations.set(id, type); - type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0; type.target = target; type.resolvedTypeArguments = typeArguments; } @@ -60971,7 +61761,7 @@ var ts; var lastRequiredIndex = -1; var firstRestIndex = -1; var lastOptionalOrRestIndex = -1; - var _loop_15 = function (i) { + var _loop_16 = function (i) { var type = elementTypes[i]; var flags = target.elementFlags[i]; if (flags & 8 /* ElementFlags.Variadic */) { @@ -61001,7 +61791,7 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - var state_4 = _loop_15(i); + var state_4 = _loop_16(i); if (typeof state_4 === "object") return state_4.value; } @@ -61197,7 +61987,7 @@ var ts; var templates = ts.filter(types, isPatternLiteralType); if (templates.length) { var i = types.length; - var _loop_16 = function () { + var _loop_17 = function () { i--; var t = types[i]; if (t.flags & 128 /* TypeFlags.StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { @@ -61205,7 +61995,7 @@ var ts; } }; while (i > 0) { - _loop_16(); + _loop_17(); } } } @@ -61282,14 +62072,14 @@ var ts; var namedUnions = []; addNamedUnions(namedUnions, types); var reducedTypes = []; - var _loop_17 = function (t) { + var _loop_18 = function (t) { if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) { reducedTypes.push(t); } }; for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) { var t = typeSet_1[_i]; - _loop_17(t); + _loop_18(t); } if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) { return namedUnions[0]; @@ -61424,7 +62214,7 @@ var ts; } return includes; } - function removeRedundantPrimitiveTypes(types, includes) { + function removeRedundantSupertypes(types, includes) { var i = types.length; while (i > 0) { i--; @@ -61432,7 +62222,9 @@ var ts; var remove = t.flags & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || t.flags & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || t.flags & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */; + t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + t.flags & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + isEmptyAnonymousObjectType(t) && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -61554,7 +62346,7 @@ var ts; // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types, aliasSymbol, aliasTypeArguments, noSupertypeReduction) { var typeMembershipMap = new ts.Map(); var includes = addTypesToIntersection(typeMembershipMap, 0, types); var typeSet = ts.arrayFrom(typeMembershipMap.values()); @@ -61591,11 +62383,11 @@ var ts; if (includes & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || includes & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || includes & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */) { - removeRedundantPrimitiveTypes(typeSet, includes); - } - if (includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 524288 /* TypeFlags.Object */) { - ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + includes & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */) { + if (!noSupertypeReduction) + removeRedundantSupertypes(typeSet, includes); } if (includes & 262144 /* TypeFlags.IncludesMissingType */) { typeSet[typeSet.indexOf(undefinedType)] = missingType; @@ -61634,8 +62426,9 @@ var ts; } var constituents = getCrossProductIntersections(typeSet); // We attach a denormalized origin type when at least one constituent of the cross-product union is an - // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions). - var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; + // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions) and + // the denormalized origin has fewer constituents than the union itself. + var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; result = getUnionType(constituents, 1 /* UnionReduction.Literal */, aliasSymbol, aliasTypeArguments, origin); } } @@ -61678,11 +62471,21 @@ var ts; } return intersections; } + function getConstituentCount(type) { + return !(type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) || type.aliasSymbol ? 1 : + type.flags & 1048576 /* TypeFlags.Union */ && type.origin ? getConstituentCount(type.origin) : + getConstituentCountOfTypes(type.types); + } + function getConstituentCountOfTypes(types) { + return ts.reduceLeft(types, function (n, t) { return n + getConstituentCount(t); }, 0); + } function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var aliasSymbol = getAliasSymbolForTypeNode(node); - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var types = ts.map(node.types, getTypeFromTypeNode); + var noSupertypeReduction = types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType; + links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); } return links.resolvedType; } @@ -61810,19 +62613,22 @@ var ts; * to reduce the resulting type if possible (since only intersections with conflicting literal-typed properties are reducible). */ function isPossiblyReducibleByInstantiation(type) { - return ts.some(type.types, function (t) { - var uniqueFilled = getUniqueLiteralFilledInstantiation(t); - return getReducedType(uniqueFilled) !== uniqueFilled; - }); + var uniqueFilled = getUniqueLiteralFilledInstantiation(type); + return getReducedType(uniqueFilled) !== uniqueFilled; + } + function shouldDeferIndexType(type) { + return !!(type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || + isGenericTupleType(type) || + isGenericMappedType(type) && !hasDistributiveNameType(type) || + type.flags & 1048576 /* TypeFlags.Union */ && ts.some(type.types, isPossiblyReducibleByInstantiation) || + type.flags & 2097152 /* TypeFlags.Intersection */ && maybeTypeOfKind(type, 465829888 /* TypeFlags.Instantiable */) && ts.some(type.types, isEmptyAnonymousObjectType)); } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } type = getReducedType(type); - return type.flags & 1048576 /* TypeFlags.Union */ ? isPossiblyReducibleByInstantiation(type) - ? getIndexTypeForGenericType(type, stringsOnly) - : getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + return shouldDeferIndexType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + type.flags & 1048576 /* TypeFlags.Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : + type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ ? getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) : type === wildcardType ? wildcardType : type.flags & 2 /* TypeFlags.Unknown */ ? neverType : @@ -61948,9 +62754,12 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type; + // 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; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -61961,6 +62770,15 @@ var ts; } return str; } + function applyTemplateStringMapping(symbol, texts, types) { + switch (intrinsicTypeKinds.get(symbol.escapedName)) { + case 0 /* IntrinsicTypeKind.Uppercase */: return [texts.map(function (t) { return t.toUpperCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 1 /* IntrinsicTypeKind.Lowercase */: return [texts.map(function (t) { return t.toLowerCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 2 /* IntrinsicTypeKind.Capitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toUpperCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + case 3 /* IntrinsicTypeKind.Uncapitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toLowerCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + } + return [texts, types]; + } function getStringMappingTypeForGenericType(symbol, type) { var id = "".concat(getSymbolId(symbol), ",").concat(getTypeId(type)); var result = stringMappingTypes.get(id); @@ -62062,21 +62880,28 @@ var ts; getFlowTypeOfReference(accessExpression, propType) : propType; } - if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName) && +propName >= 0) { + if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName)) { + var index = +propName; if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 16 /* AccessFlags.NoTupleBoundsCheck */)) { var indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { + if (index < 0) { + error(indexNode, ts.Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); + return undefinedType; + } error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); } else { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } } - errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, function (t) { - var restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; - }); + if (index >= 0) { + errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); + return mapType(objectType, function (t) { + var restType = getRestTypeOfTupleType(t) || undefinedType; + return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; + }); + } } } if (!(indexType.flags & 98304 /* TypeFlags.Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* TypeFlags.StringLike */ | 296 /* TypeFlags.NumberLike */ | 12288 /* TypeFlags.ESSymbolLike */)) { @@ -62202,7 +63027,7 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -62340,7 +63165,7 @@ var ts; function substituteIndexedMappedType(objectType, index) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]); var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return instantiateType(getTemplateTypeFromMappedType(objectType.target || objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) { if (accessFlags === void 0) { accessFlags = 0 /* AccessFlags.None */; } @@ -62488,7 +63313,7 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_18 = function () { + var _loop_19 = function () { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; @@ -62609,7 +63434,7 @@ var ts; // 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_5 = _loop_18(); + var state_5 = _loop_19(); if (typeof state_5 === "object") return state_5.value; if (state_5 === "break") @@ -62710,6 +63535,7 @@ var ts; } } function getTypeFromImportTypeNode(node) { + var _a; var links = getNodeLinks(node); if (!links.resolvedType) { if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments @@ -62729,6 +63555,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } + var isExportEquals = !!((_a = innerModuleSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* InternalSymbolName.ExportEquals */)); var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); @@ -62740,9 +63567,11 @@ var ts; // That, in turn, ultimately uses `getPropertyOfType` on the type of the symbol, which differs slightly from // the `exports` lookup process that only looks up namespace members which is used for most type references var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace)); - var next = node.isTypeOf - ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText) - : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var symbolFromVariable = node.isTypeOf || ts.isInJSFile(node) && isExportEquals + ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ true) + : undefined; + var symbolFromModule = node.isTypeOf ? undefined : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var next = symbolFromModule !== null && symbolFromModule !== void 0 ? symbolFromModule : symbolFromVariable; if (!next) { error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); return links.resolvedType = errorType; @@ -63239,7 +64068,7 @@ var ts; switch (mapper.kind) { case 0 /* TypeMapKind.Simple */: return type === mapper.source ? mapper.target : type; - case 1 /* TypeMapKind.Array */: + case 1 /* TypeMapKind.Array */: { var sources = mapper.sources; var targets = mapper.targets; for (var i = 0; i < sources.length; i++) { @@ -63248,25 +64077,39 @@ var ts; } } return type; - case 2 /* TypeMapKind.Function */: + } + case 2 /* TypeMapKind.Deferred */: { + var sources = mapper.sources; + var targets = mapper.targets; + for (var i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets[i](); + } + } + return type; + } + case 3 /* TypeMapKind.Function */: return mapper.func(type); - case 3 /* TypeMapKind.Composite */: - case 4 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: + case 5 /* TypeMapKind.Merged */: var t1 = getMappedType(type, mapper.mapper1); - return t1 !== type && mapper.kind === 3 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); + return t1 !== type && mapper.kind === 4 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); } } function makeUnaryTypeMapper(source, target) { - return { kind: 0 /* TypeMapKind.Simple */, source: source, target: target }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 0 /* TypeMapKind.Simple */, source: source, target: target }); } function makeArrayTypeMapper(sources, targets) { - return { kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }); } - function makeFunctionTypeMapper(func) { - return { kind: 2 /* TypeMapKind.Function */, func: func }; + function makeFunctionTypeMapper(func, debugInfo) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 3 /* TypeMapKind.Function */, func: func, debugInfo: ts.Debug.isDebugging ? debugInfo : undefined }); + } + function makeDeferredTypeMapper(sources, targets) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 2 /* TypeMapKind.Deferred */, sources: sources, targets: targets }); } function makeCompositeTypeMapper(kind, mapper1, mapper2) { - return { kind: kind, mapper1: mapper1, mapper2: mapper2 }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: kind, mapper1: mapper1, mapper2: mapper2 }); } function createTypeEraser(sources) { return createTypeMapper(sources, /*targets*/ undefined); @@ -63276,19 +64119,20 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(context, index) { - return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; }); + var forwardInferences = context.inferences.slice(index); + return createTypeMapper(ts.map(forwardInferences, function (i) { return i.typeParameter; }), ts.map(forwardInferences, function () { return unknownType; })); } function combineTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(3 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; } function mergeTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; } function prependTypeMapping(source, target, mapper) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); } function appendTypeMapping(mapper, source, target) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); } function getRestrictiveTypeParameter(tp) { return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), @@ -63554,6 +64398,7 @@ var ts; result.mapper = mapper; result.aliasSymbol = aliasSymbol || type.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + result.objectFlags |= result.aliasTypeArguments ? getPropagatingFlagsOfTypes(result.aliasTypeArguments) : 0; return result; } function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { @@ -64202,7 +65047,7 @@ var ts; }); } function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; if (isTupleLikeType(source)) { return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); @@ -64269,7 +65114,7 @@ var ts; }); } function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); } @@ -64356,7 +65201,7 @@ var ts; var sourceSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && - (getFalsyFlags(sourceType) & 98304 /* TypeFlags.Nullable */) === (getFalsyFlags(targetType) & 98304 /* TypeFlags.Nullable */); + (getTypeFacts(sourceType) & 50331648 /* TypeFacts.IsUndefinedOrNull */) === (getTypeFacts(targetType) & 50331648 /* TypeFacts.IsUndefinedOrNull */); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* SignatureCheckMode.StrictArity */) | (strictVariance ? 2 /* SignatureCheckMode.StrictCallback */ : 1 /* SignatureCheckMode.BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* SignatureCheckMode.Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); @@ -64468,6 +65313,20 @@ var ts; return !!(ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && (type.members && isEmptyResolvedType(type) || type.symbol && type.symbol.flags & 2048 /* SymbolFlags.TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0)); } + function isUnknownLikeUnionType(type) { + if (strictNullChecks && type.flags & 1048576 /* TypeFlags.Union */) { + if (!(type.objectFlags & 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */)) { + var types = type.types; + type.objectFlags |= 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */ | (types.length >= 3 && types[0].flags & 32768 /* TypeFlags.Undefined */ && + types[1].flags & 65536 /* TypeFlags.Null */ && ts.some(types, isEmptyAnonymousObjectType) ? 67108864 /* ObjectFlags.IsUnknownLikeUnion */ : 0); + } + return !!(type.objectFlags & 67108864 /* ObjectFlags.IsUnknownLikeUnion */); + } + return false; + } + function containsUndefinedType(type) { + return !!((type.flags & 1048576 /* TypeFlags.Union */ ? type.types[0] : type).flags & 32768 /* TypeFlags.Undefined */); + } function isStringIndexSignatureOnlyType(type) { return type.flags & 524288 /* TypeFlags.Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) || @@ -64547,7 +65406,7 @@ var ts; return true; if (s & 65536 /* TypeFlags.Null */ && (!strictNullChecks && !(t & 3145728 /* TypeFlags.UnionOrIntersection */) || t & 65536 /* TypeFlags.Null */)) return true; - if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */) + if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(ts.getObjectFlags(source) & 8192 /* ObjectFlags.FreshLiteral */))) return true; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* TypeFlags.Any */) @@ -64557,6 +65416,9 @@ var ts; // bit-flag enum types sometimes look like literal enum types with numeric literal values. if (s & (8 /* TypeFlags.Number */ | 256 /* TypeFlags.NumberLiteral */) && !(s & 1024 /* TypeFlags.EnumLiteral */) && (t & 32 /* TypeFlags.Enum */ || relation === assignableRelation && t & 256 /* TypeFlags.NumberLiteral */ && t & 1024 /* TypeFlags.EnumLiteral */)) return true; + // Anything is assignable to a union containing undefined, null, and {} + if (isUnknownLikeUnionType(target)) + return true; } return false; } @@ -64599,16 +65461,27 @@ var ts; function getNormalizedType(type, writing) { while (true) { var t = isFreshLiteralType(type) ? type.regularType : - ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getReducedType(type) : + ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : + type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* TypeFlags.Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* TypeFlags.Simplifiable */ ? getSimplifiedType(type, writing) : type; - t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) - break; + return t; type = t; } + } + function getNormalizedUnionOrIntersectionType(type, writing) { + var reduced = getReducedType(type); + if (reduced !== type) { + return reduced; + } + if (type.flags & 2097152 /* TypeFlags.Intersection */) { + var normalizedTypes = ts.sameMap(type.types, function (t) { return getNormalizedType(t, writing); }); + if (normalizedTypes !== type.types) { + return getIntersectionType(normalizedTypes); + } + } return type; } /** @@ -64840,7 +65713,7 @@ var ts; ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable"); generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); } - if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperType && target !== markerSubType) { + if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperTypeForCheck && target !== markerSubTypeForCheck) { var constraint = getBaseConstraintOfType(target); var needsOriginalSource = void 0; if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) { @@ -65055,6 +65928,7 @@ var ts; return 0 /* Ternary.False */; } function reportErrorResults(originalSource, originalTarget, source, target, headMessage) { + var _a, _b; var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; @@ -65095,6 +65969,14 @@ var ts; return; } reportRelationError(headMessage, source, target); + if (source.flags & 262144 /* TypeFlags.TypeParameter */ && ((_b = (_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) === null || _b === void 0 ? void 0 : _b[0]) && !getConstraintOfType(source)) { + var syntheticParam = cloneTypeParameter(source); + syntheticParam.constraint = instantiateType(target, makeUnaryTypeMapper(source, syntheticParam)); + if (hasNonCircularBaseConstraint(syntheticParam)) { + var targetConstraintString = typeToString(target, source.symbol.declarations[0]); + associateRelatedInfo(ts.createDiagnosticForNode(source.symbol.declarations[0], ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint, targetConstraintString)); + } + } } function traceUnionsOrIntersectionsTooLarge(source, target) { if (!ts.tracing) { @@ -65147,7 +66029,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_19 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -65210,7 +66092,7 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_6 = _loop_19(prop); + var state_6 = _loop_20(prop); if (typeof state_6 === "object") return state_6.value; } @@ -65232,7 +66114,7 @@ var ts; return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* TypeFlags.Primitive */) && !(target.flags & 131068 /* TypeFlags.Primitive */)); } if (target.flags & 2097152 /* TypeFlags.Intersection */) { - return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* IntersectionState.Target */); + return typeRelatedToEachType(source, target, reportErrors, 2 /* IntersectionState.Target */); } // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the // constraints of all non-primitive types in the source into a new intersection. We do this because the @@ -65442,10 +66324,10 @@ var ts; // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component var saved = entry & 24 /* RelationComparisonResult.ReportsMask */; if (saved & 8 /* RelationComparisonResult.ReportsUnmeasurable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers)); + instantiateType(source, reportUnmeasurableMapper); } if (saved & 16 /* RelationComparisonResult.ReportsUnreliable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } } return entry & 1 /* RelationComparisonResult.Succeeded */ ? -1 /* Ternary.True */ : 0 /* Ternary.False */; @@ -65545,13 +66427,40 @@ var ts; return result; } 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 */)) { + // 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 + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + // This also handles type parameters, as a type parameter with a union constraint compared against a union + // 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 && 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) { + resetErrorInfo(saveErrorInfo); + } + 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; - var saveErrorInfo = captureErrorCalculationState(); var sourceFlags = source.flags; var targetFlags = target.flags; if (relation === identityRelation) { @@ -65597,29 +66506,6 @@ var ts; if (result = unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState)) { return result; } - if (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */) { - // 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 - // when the target is a union type. Another is when the intersection contains types belonging - // to one of the disjoint domains. For example, given type variables T and U, each with the - // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and - // we need to check this constraint against a union on the target side. Also, given a type - // variable V constrained to 'string | number', 'V & number' has a combined constraint of - // 'string & number | number & number' which reduces to just 'number'. - // This also handles type parameters, as a type parameter with a union constraint compared against a union - // 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 && 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 - if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - } // The ordered decomposition above doesn't handle all cases. Specifically, we also need to handle: // Source is instantiable (e.g. source has union or intersection constraint). // Source is an object, target is a union (e.g. { a, b: boolean } <=> { a, b: true } | { a, b: false }). @@ -65663,6 +66549,20 @@ var ts; } } } + if (relation === comparableRelation && sourceFlags & 262144 /* TypeFlags.TypeParameter */) { + // This is a carve-out in comparability to essentially forbid comparing a type parameter + // 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 */) { + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { + return result; + } + constraint = getConstraintOfTypeParameter(constraint); + } + } + return 0 /* Ternary.False */; + } } else if (targetFlags & 4194304 /* TypeFlags.Index */) { var targetType_1 = target.type; @@ -65726,7 +66626,6 @@ var ts; result &= isRelatedTo(source.indexType, target.indexType, 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } if (reportErrors) { @@ -65829,7 +66728,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } var c = target; @@ -65844,7 +66742,6 @@ var ts; if (result = skipTrue ? -1 /* Ternary.True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false)) { result &= skipFalse ? -1 /* Ternary.True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false); if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65857,31 +66754,29 @@ var ts; } // Report unreliable variance for type variables referenced in template literal type placeholders. // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* Ternary.True */; } } + else if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + if (!(source.flags & 268435456 /* TypeFlags.StringMapping */)) { + if (isMemberOfStringMapping(source, target)) { + return -1 /* Ternary.True */; + } + } + } if (sourceFlags & 8650752 /* TypeFlags.TypeVariable */) { // IndexedAccess comparisons are handled above in the `targetFlags & TypeFlage.IndexedAccess` branch if (!(sourceFlags & 8388608 /* TypeFlags.IndexedAccess */ && targetFlags & 8388608 /* TypeFlags.IndexedAccess */)) { - var constraint = getConstraintOfType(source); - if (!constraint || (sourceFlags & 262144 /* TypeFlags.TypeParameter */ && constraint.flags & 1 /* TypeFlags.Any */)) { - // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* TypeFlags.NonPrimitive */), 3 /* RecursionFlags.Both */)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } + var constraint = getConstraintOfType(source) || unknownType; // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed - else if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && constraint !== unknownType && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { return result; } if (isMappedTypeGenericIndexedAccess(source)) { @@ -65890,7 +66785,6 @@ var ts; var indexConstraint = getConstraintOfType(source.indexType); if (indexConstraint) { if (result = isRelatedTo(getIndexedAccessType(source.objectType, indexConstraint), target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65899,7 +66793,6 @@ var ts; } else if (sourceFlags & 4194304 /* TypeFlags.Index */) { if (result = isRelatedTo(keyofConstraintType, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65907,22 +66800,22 @@ var ts; if (!(targetFlags & 134217728 /* TypeFlags.TemplateLiteral */)) { var constraint = getBaseConstraintOfType(source); if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } } else if (sourceFlags & 268435456 /* TypeFlags.StringMapping */) { - if (targetFlags & 268435456 /* TypeFlags.StringMapping */ && source.symbol === target.symbol) { + if (targetFlags & 268435456 /* TypeFlags.StringMapping */) { + if (source.symbol !== target.symbol) { + return 0 /* Ternary.False */; + } if (result = isRelatedTo(source.type, target.type, 3 /* RecursionFlags.Both */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } else { var constraint = getBaseConstraintOfType(source); if (constraint && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65931,7 +66824,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } if (targetFlags & 16777216 /* TypeFlags.Conditional */) { @@ -65954,7 +66846,6 @@ var ts; result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65965,7 +66856,6 @@ var ts; var distributiveConstraint = hasNonCircularBaseConstraint(source) ? getConstraintOfDistributiveConditionalType(source) : undefined; if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65975,7 +66865,6 @@ var ts; var defaultConstraint = getDefaultConstraintOfConditionalType(source); if (defaultConstraint) { if (result = isRelatedTo(defaultConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65988,7 +66877,6 @@ var ts; if (isGenericMappedType(target)) { if (isGenericMappedType(source)) { if (result = mappedTypeRelatedTo(source, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -66126,18 +67014,6 @@ var ts; } } } - function reportUnmeasurableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); - } - return p; - } - function reportUnreliableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); - } - return p; - } // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice // that S and T are contra-variant whereas X and Y are co-variant. @@ -66147,7 +67023,7 @@ var ts; if (modifiersRelated) { var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); - var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); + var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMapper : reportUnreliableMapper); if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* RecursionFlags.Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { @@ -66201,11 +67077,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_20 = 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_21 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -66221,7 +67097,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_8 = _loop_21(i); + var state_8 = _loop_22(i); switch (state_8) { case "continue-outer": continue outer; } @@ -66235,7 +67111,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_7 = _loop_20(combination); + var state_7 = _loop_21(combination); if (typeof state_7 === "object") return state_7.value; } @@ -66683,7 +67559,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, makeFunctionTypeMapper(reportUnreliableMarkers)); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, reportUnreliableMapper); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -66838,7 +67714,7 @@ var ts; return typeCouldHaveTopLevelSingletonTypes(constraint); } } - return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */); + return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */); } function getExactOptionalUnassignableProperties(source, target) { if (isTupleType(source) && isTupleType(target)) @@ -66942,7 +67818,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_22 = 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 */ : @@ -66978,12 +67854,12 @@ var ts; } variances.push(variance); }; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - _loop_22(tp); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var tp = typeParameters_2[_i]; + _loop_23(tp); } links.variances = variances; - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); } return links.variances; } @@ -67321,35 +68197,33 @@ var ts; var commonBaseType; for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { var t = types_13[_i]; - var baseType = getBaseTypeOfLiteralType(t); - if (!commonBaseType) { - commonBaseType = baseType; - } - if (baseType === t || baseType !== commonBaseType) { - return false; + if (!(t.flags & 131072 /* TypeFlags.Never */)) { + var baseType = getBaseTypeOfLiteralType(t); + commonBaseType !== null && commonBaseType !== void 0 ? commonBaseType : (commonBaseType = baseType); + if (baseType === t || baseType !== commonBaseType) { + return false; + } } } return true; } - // When the candidate types are all literal types with the same base type, return a union - // of those literal types. Otherwise, return the leftmost type for which no type to the - // right is a supertype. - function getSupertypeOrUnion(types) { - if (types.length === 1) { - return types[0]; - } - return literalTypesWithSameBaseType(types) ? - getUnionType(types) : - ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + function getCombinedTypeFlags(types) { + return ts.reduceLeft(types, function (flags, t) { return flags | (t.flags & 1048576 /* TypeFlags.Union */ ? getCombinedTypeFlags(t.types) : t.flags); }, 0); } function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); + if (types.length === 1) { + return types[0]; } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* TypeFlags.Nullable */); }); - return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* TypeFlags.Nullable */) : - getUnionType(types, 2 /* UnionReduction.Subtype */); + // Remove nullable types from each of the candidates. + var primaryTypes = strictNullChecks ? ts.sameMap(types, function (t) { return filterType(t, function (u) { return !(u.flags & 98304 /* TypeFlags.Nullable */); }); }) : types; + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + var superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? + getUnionType(primaryTypes) : + ts.reduceLeft(primaryTypes, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + // Add any nullable types that occurred in the candidates back to the result. + return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & 98304 /* TypeFlags.Nullable */); } // Return the leftmost type for which no type to the right is a subtype. function getCommonSubtype(types) { @@ -67453,9 +68327,14 @@ var ts; type.flags & 256 /* TypeFlags.NumberLiteral */ ? numberType : type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? bigintType : type.flags & 512 /* TypeFlags.BooleanLiteral */ ? booleanType : - type.flags & 1048576 /* TypeFlags.Union */ ? mapType(type, getBaseTypeOfLiteralType) : + type.flags & 1048576 /* TypeFlags.Union */ ? getBaseTypeOfLiteralTypeUnion(type) : type; } + function getBaseTypeOfLiteralTypeUnion(type) { + var _a; + var key = "B".concat(getTypeId(type)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); + } function getWidenedLiteralType(type) { return type.flags & 1024 /* TypeFlags.EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : type.flags & 128 /* TypeFlags.StringLiteral */ && isFreshLiteralType(type) ? stringType : @@ -67536,29 +68415,8 @@ var ts; var value = _a.value; return value.base10Value === "0"; } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - result |= getFalsyFlags(t); - } - return result; - } - // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null - // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns - // no flags for all other types (including non-falsy literal types). - function getFalsyFlags(type) { - return type.flags & 1048576 /* TypeFlags.Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? type.value === "" ? 128 /* TypeFlags.StringLiteral */ : 0 : - type.flags & 256 /* TypeFlags.NumberLiteral */ ? type.value === 0 ? 256 /* TypeFlags.NumberLiteral */ : 0 : - type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* TypeFlags.BigIntLiteral */ : 0 : - type.flags & 512 /* TypeFlags.BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* TypeFlags.BooleanLiteral */ : 0 : - type.flags & 117724 /* TypeFlags.PossiblyFalsy */; - } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 117632 /* TypeFlags.DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* TypeFlags.DefinitelyFalsy */); }) : - type; + return filterType(type, function (t) { return !!(getTypeFacts(t) & 4194304 /* TypeFacts.Truthy */); }); } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); @@ -67593,20 +68451,15 @@ var ts; return type.flags & 32768 /* TypeFlags.Undefined */ ? type : getUnionType([type, isProperty ? missingType : undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { - // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates - // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' - // that isn't eliminated by a NonNullable instantiation. - var reducedType = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* SymbolFlags.TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? - getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : - reducedType; + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : + getIntersectionType([type, emptyObjectType]); } function getNonNullableType(type) { - return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + return strictNullChecks ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; @@ -67660,12 +68513,13 @@ var ts; * with no call or construct signatures. */ function isObjectTypeWithInferableIndex(type) { + var objectFlags = ts.getObjectFlags(type); return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* SymbolFlags.ObjectLiteral */ | 2048 /* SymbolFlags.TypeLiteral */ | 384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */)) !== 0 && !(type.symbol.flags & 32 /* SymbolFlags.Class */) - && !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & 4194304 /* ObjectFlags.ObjectRestType */) || !!(objectFlags & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* CheckFlags.Readonly */); @@ -67998,27 +68852,29 @@ var ts; signature: signature, flags: flags, compareTypes: compareTypes, - mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }), - nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }), + mapper: reportUnmeasurableMapper, + nonFixingMapper: reportUnmeasurableMapper, }; + context.mapper = makeFixingMapperForContext(context); + context.nonFixingMapper = makeNonFixingMapperForContext(context); return context; } - function mapToInferredType(context, t, fix) { - var inferences = context.inferences; - for (var i = 0; i < inferences.length; i++) { - var inference = inferences[i]; - if (t === inference.typeParameter) { - if (fix && !inference.isFixed) { - // Before we commit to a particular inference (and thus lock out any further inferences), - // we infer from any intra-expression inference sites we have collected. - inferFromIntraExpressionSites(context); - clearCachedInferences(inferences); - inference.isFixed = true; - } - return getInferredType(context, i); + function makeFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (inference, i) { return function () { + if (!inference.isFixed) { + // Before we commit to a particular inference (and thus lock out any further inferences), + // we infer from any intra-expression inference sites we have collected. + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; } - } - return t; + return getInferredType(context, i); + }; })); + } + function makeNonFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (_, i) { return function () { + return getInferredType(context, i); + }; })); } function clearCachedInferences(inferences) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { @@ -68287,13 +69143,40 @@ var ts; return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen); } - function isValidBigIntString(s) { + /** + * Tests whether the provided string can be parsed as a number. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting number matches the input when converted back to a string. + */ + function isValidNumberString(s, roundTripOnly) { + if (s === "") + return false; + var n = +s; + return isFinite(n) && (!roundTripOnly || "" + n === s); + } + /** + * @param text a valid bigint string excluding a trailing `n`, but including a possible prefix `-`. Use `isValidBigIntString(text, roundTripOnly)` before calling this function. + */ + function parseBigIntLiteralType(text) { + var negative = text.startsWith("-"); + var base10Value = ts.parsePseudoBigInt("".concat(negative ? text.slice(1) : text, "n")); + return getBigIntLiteralType({ negative: negative, base10Value: base10Value }); + } + /** + * Tests whether the provided string can be parsed as a bigint. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting bigint matches the input when converted back to a string. + */ + function isValidBigIntString(s, roundTripOnly) { + if (s === "") + return false; var scanner = ts.createScanner(99 /* ScriptTarget.ESNext */, /*skipTrivia*/ false); var success = true; scanner.setOnError(function () { return success = false; }); scanner.setText(s + "n"); var result = scanner.scan(); - if (result === 40 /* SyntaxKind.MinusToken */) { + var negative = result === 40 /* SyntaxKind.MinusToken */; + if (negative) { result = scanner.scan(); } var flags = scanner.getTokenFlags(); @@ -68302,7 +69185,33 @@ var ts; // * a bigint can be scanned, and that when it is scanned, it is // * the full length of the input string (so the scanner is one character beyond the augmented input length) // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) - return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */); + return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */) + && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); + } + function isMemberOfStringMapping(source, target) { + if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + return true; + } + if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { + return isTypeAssignableTo(source, target); + } + if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + // We need to see whether applying the same mappings of the target + // onto the source would produce an identical type *and* that + // it's compatible with the inner-most non-string-mapped type. + // + // The intuition here is that if same mappings don't affect the source at all, + // and the source is compatible with the unmapped target, then they must + // still reside in the same domain. + var mappingStack = []; + while (target.flags & 268435456 /* TypeFlags.StringMapping */) { + mappingStack.unshift(target.symbol); + target = target.type; + } + var mappedSource = ts.reduceLeft(mappingStack, function (memo, value) { return getStringMappingType(value, memo); }, source); + return mappedSource === source && isMemberOfStringMapping(source, target); + } + return false; } function isValidTypeForTemplateLiteralPlaceholder(source, target) { if (source === target || target.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */)) { @@ -68310,9 +69219,10 @@ var ts; } if (source.flags & 128 /* TypeFlags.StringLiteral */) { var value = source.value; - return !!(target.flags & 8 /* TypeFlags.Number */ && value !== "" && isFinite(+value) || - target.flags & 64 /* TypeFlags.BigInt */ && value !== "" && isValidBigIntString(value) || - target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName); + return !!(target.flags & 8 /* TypeFlags.Number */ && isValidNumberString(value, /*roundTripOnly*/ false) || + target.flags & 64 /* TypeFlags.BigInt */ && isValidBigIntString(value, /*roundTripOnly*/ false) || + target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName || + target.flags & 268435456 /* TypeFlags.StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target)); } if (source.flags & 134217728 /* TypeFlags.TemplateLiteral */) { var texts = source.texts; @@ -68435,10 +69345,13 @@ var ts; propagationType = savePropagationType; return; } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - // Source and target are types originating in the same generic type alias declaration. - // Simply infer from source type arguments to target type arguments. - inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + if (source.aliasSymbol && source.aliasSymbol === target.aliasSymbol) { + if (source.aliasTypeArguments) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + } + // And if there weren't any type arguments, there's no reason to run inference as the types must be the same. return; } if (source === target && source.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { @@ -68494,18 +69407,26 @@ var ts; target = getActualTypeVariable(target); } if (target.flags & 8650752 /* TypeFlags.TypeVariable */) { - // If target is a type parameter, make an inference, unless the source type contains - // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). - // Because the anyFunctionType is internal, it should not be exposed to the user by adding - // it as an inference candidate. Hopefully, a better candidate will come along that does - // not contain anyFunctionType when we come back to this argument for its second round - // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard - // when constructing types from type parameters that had no inference candidates). - if (source === nonInferrableAnyType || source === silentNeverType || (priority & 128 /* InferencePriority.ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + // Skip inference if the source is "blocked", which is used by the language service to + // prevent inference on nodes currently being edited. + if (isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); if (inference) { + // If target is a type parameter, make an inference, unless the source type contains + // a "non-inferrable" type. Types with this flag set are markers used to prevent inference. + // + // For example: + // - anyFunctionType is a wildcard type that's used to avoid contextually typing functions; + // it's internal, so should not be exposed to the user by adding it as a candidate. + // - autoType (and autoArrayType) is a special "any" used in control flow; like anyFunctionType, + // it's internal and should not be observable. + // - silentNeverType is returned by getInferredType when instantiating a generic function for + // inference (and a type variable has no mapping). + // + // This flag is infectious; if we produce Box (where never is silentNeverType), Box is + // also non-inferrable. if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) { return; } @@ -68562,15 +69483,11 @@ var ts; inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target)); } else if (source.flags & 4194304 /* TypeFlags.Index */ && target.flags & 4194304 /* TypeFlags.Index */) { - contravariant = !contravariant; - inferFromTypes(source.type, target.type); - contravariant = !contravariant; + inferFromContravariantTypes(source.type, target.type); } else if ((isLiteralType(source) || source.flags & 4 /* TypeFlags.String */) && target.flags & 4194304 /* TypeFlags.Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - contravariant = !contravariant; - inferWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); - contravariant = !contravariant; + inferFromContravariantTypesWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); } else if (source.flags & 8388608 /* TypeFlags.IndexedAccess */ && target.flags & 8388608 /* TypeFlags.IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -68583,10 +69500,7 @@ var ts; } else if (source.flags & 33554432 /* TypeFlags.Substitution */) { inferFromTypes(source.baseType, target); - var oldPriority = priority; - priority |= 4 /* InferencePriority.SubstituteSource */; - inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority - priority = oldPriority; + inferWithPriority(source.substitute, target, 4 /* InferencePriority.SubstituteSource */); // Make substitute inference at a lower priority } else if (target.flags & 16777216 /* TypeFlags.Conditional */) { invokeOnce(source, target, inferToConditionalType); @@ -68636,6 +69550,18 @@ var ts; inferFromTypes(source, target); priority = savePriority; } + function inferFromContravariantTypesWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromContravariantTypes(source, target); + priority = savePriority; + } + function inferToMultipleTypesWithPriority(source, targets, targetFlags, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferToMultipleTypes(source, targets, targetFlags); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -68700,10 +69626,13 @@ var ts; } } function inferFromContravariantTypes(source, target) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + function inferFromContravariantTypesIfStrictFunctionTypes(source, target) { if (strictFunctionTypes || priority & 1024 /* InferencePriority.AlwaysStrict */) { - contravariant = !contravariant; - inferFromTypes(source, target); - contravariant = !contravariant; + inferFromContravariantTypes(source, target); } else { inferFromTypes(source, target); @@ -68722,8 +69651,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var type = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* TypeFlags.Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -68867,11 +69796,8 @@ var ts; inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else { - var savePriority = priority; - priority |= contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; - inferToMultipleTypes(source, targetTypes, target.flags); - priority = savePriority; + inferToMultipleTypesWithPriority(source, targetTypes, target.flags, contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0); } } function inferToTemplateLiteralType(source, target) { @@ -68884,8 +69810,57 @@ 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_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 + // allowed template literal placeholder types, infer from a literal type corresponding to the constraint. + if (source_1.flags & 128 /* TypeFlags.StringLiteral */ && target_3.flags & 8650752 /* TypeFlags.TypeVariable */) { + var inferenceContext = getInferenceInfoForType(target_3); + var constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : undefined; + if (constraint && !isTypeAny(constraint)) { + var constraintTypes = constraint.flags & 1048576 /* TypeFlags.Union */ ? constraint.types : [constraint]; + var allTypeFlags_1 = ts.reduceLeft(constraintTypes, function (flags, t) { return flags | t.flags; }, 0); + // If the constraint contains `string`, we don't need to look for a more preferred type + if (!(allTypeFlags_1 & 4 /* TypeFlags.String */)) { + var str_1 = source_1.value; + // If the type contains `number` or a number literal and the string isn't a valid number, exclude numbers + if (allTypeFlags_1 & 296 /* TypeFlags.NumberLike */ && !isValidNumberString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~296 /* TypeFlags.NumberLike */; + } + // If the type contains `bigint` or a bigint literal and the string isn't a valid bigint, exclude bigints + if (allTypeFlags_1 & 2112 /* TypeFlags.BigIntLike */ && !isValidBigIntString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~2112 /* TypeFlags.BigIntLike */; + } + // for each type in the constraint, find the highest priority matching type + var matchingType = ts.reduceLeft(constraintTypes, function (left, right) { + return !(right.flags & allTypeFlags_1) ? left : + left.flags & 4 /* TypeFlags.String */ ? left : right.flags & 4 /* TypeFlags.String */ ? source_1 : + left.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? left : right.flags & 134217728 /* TypeFlags.TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source_1, right) ? source_1 : + left.flags & 268435456 /* TypeFlags.StringMapping */ ? left : right.flags & 268435456 /* TypeFlags.StringMapping */ && str_1 === applyStringMapping(right.symbol, str_1) ? source_1 : + left.flags & 128 /* TypeFlags.StringLiteral */ ? left : right.flags & 128 /* TypeFlags.StringLiteral */ && right.value === str_1 ? right : + left.flags & 8 /* TypeFlags.Number */ ? left : right.flags & 8 /* TypeFlags.Number */ ? getNumberLiteralType(+str_1) : + left.flags & 32 /* TypeFlags.Enum */ ? left : right.flags & 32 /* TypeFlags.Enum */ ? getNumberLiteralType(+str_1) : + left.flags & 256 /* TypeFlags.NumberLiteral */ ? left : right.flags & 256 /* TypeFlags.NumberLiteral */ && right.value === +str_1 ? right : + left.flags & 64 /* TypeFlags.BigInt */ ? left : right.flags & 64 /* TypeFlags.BigInt */ ? parseBigIntLiteralType(str_1) : + left.flags & 2048 /* TypeFlags.BigIntLiteral */ ? left : right.flags & 2048 /* TypeFlags.BigIntLiteral */ && ts.pseudoBigIntToString(right.value) === str_1 ? right : + left.flags & 16 /* TypeFlags.Boolean */ ? left : right.flags & 16 /* TypeFlags.Boolean */ ? str_1 === "true" ? trueType : str_1 === "false" ? falseType : booleanType : + left.flags & 512 /* TypeFlags.BooleanLiteral */ ? left : right.flags & 512 /* TypeFlags.BooleanLiteral */ && right.intrinsicName === str_1 ? right : + left.flags & 32768 /* TypeFlags.Undefined */ ? left : right.flags & 32768 /* TypeFlags.Undefined */ && right.intrinsicName === str_1 ? right : + left.flags & 65536 /* TypeFlags.Null */ ? left : right.flags & 65536 /* TypeFlags.Null */ && right.intrinsicName === str_1 ? right : + left; + }, neverType); + if (!(matchingType.flags & 131072 /* TypeFlags.Never */)) { + inferFromTypes(matchingType, target_3); + return "continue"; + } + } + } + } + inferFromTypes(source_1, target_3); + }; for (var i = 0; i < types.length; i++) { - inferFromTypes(matches ? matches[i] : neverType, types[i]); + _loop_24(i); } } } @@ -68999,20 +69974,17 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } - function inferFromSignature(source, target, skipParameters) { - if (!skipParameters) { - var saveBivariant = bivariant; - var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; - // Once we descend into a bivariant signature we remain bivariant for all nested inferences - bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; - applyToParameterTypes(source, target, inferFromContravariantTypes); - bivariant = saveBivariant; - } + function inferFromSignature(source, target) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; + applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); + bivariant = saveBivariant; applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { @@ -69259,6 +70231,15 @@ var ts; var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); return key && key + "." + propName; } + break; + case 201 /* SyntaxKind.ObjectBindingPattern */: + case 202 /* SyntaxKind.ArrayBindingPattern */: + case 256 /* SyntaxKind.FunctionDeclaration */: + case 213 /* SyntaxKind.FunctionExpression */: + case 214 /* SyntaxKind.ArrowFunction */: + case 169 /* SyntaxKind.MethodDeclaration */: + // Handle pseudo-references originating in getNarrowedTypeOfSymbol. + return "".concat(getNodeId(node), "#").concat(getTypeId(declaredType)); } return undefined; } @@ -69403,7 +70384,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_23 = 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) { @@ -69427,9 +70408,9 @@ var ts; } } }; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - var state_9 = _loop_23(type); + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var type = types_15[_i]; + var state_9 = _loop_25(type); if (typeof state_9 === "object") return state_9.value; } @@ -69518,23 +70499,25 @@ var ts; // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 131072 /* TypeFlags.Never */) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType)) { - reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types - } - // Our crude heuristic produces an invalid result in some cases: see GH#26130. - // For now, when that happens, we give up and don't narrow at all. (This also - // means we'll never narrow for erroneous assignments where the assigned type - // is not assignable to the declared type.) - if (isTypeAssignableTo(assignedType, reducedType)) { - return reducedType; - } + var _a; + if (declaredType === assignedType) { + return declaredType; } - return declaredType; + if (assignedType.flags & 131072 /* TypeFlags.Never */) { + return assignedType; + } + var key = "A".concat(getTypeId(declaredType), ",").concat(getTypeId(assignedType)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); + } + function getAssignmentReducedTypeWorker(declaredType, assignedType) { + var filteredType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + // Ensure that we narrow to fresh types if the assignment is a fresh boolean literal type. + var reducedType = assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType; + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType; } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype @@ -69543,14 +70526,16 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type, ignoreObjects) { - if (ignoreObjects === void 0) { ignoreObjects = false; } + function getTypeFacts(type) { + if (type.flags & (2097152 /* TypeFlags.Intersection */ | 465829888 /* TypeFlags.Instantiable */)) { + type = getBaseConstraintOfType(type) || unknownType; + } var flags = type.flags; - if (flags & 4 /* TypeFlags.String */) { + if (flags & (4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */)) { return strictNullChecks ? 16317953 /* TypeFacts.StringStrictFacts */ : 16776705 /* TypeFacts.StringFacts */; } - if (flags & 128 /* TypeFlags.StringLiteral */) { - var isEmpty = type.value === ""; + if (flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */)) { + var isEmpty = flags & 128 /* TypeFlags.StringLiteral */ && type.value === ""; return strictNullChecks ? isEmpty ? 12123649 /* TypeFacts.EmptyStringStrictFacts */ : 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* TypeFacts.EmptyStringFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; @@ -69582,20 +70567,20 @@ var ts; (type === falseType || type === regularFalseType) ? 12580616 /* TypeFacts.FalseFacts */ : 16774920 /* TypeFacts.TrueFacts */; } if (flags & 524288 /* TypeFlags.Object */) { - if (ignoreObjects) { - return 16768959 /* TypeFacts.AndFactsMask */; // This is the identity element for computing type facts of intersection. - } return ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && isEmptyObjectType(type) ? - strictNullChecks ? 16318463 /* TypeFacts.EmptyObjectStrictFacts */ : 16777215 /* TypeFacts.EmptyObjectFacts */ : + strictNullChecks ? 83427327 /* TypeFacts.EmptyObjectStrictFacts */ : 83886079 /* TypeFacts.EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* TypeFacts.FunctionStrictFacts */ : 16728000 /* TypeFacts.FunctionFacts */ : strictNullChecks ? 7888800 /* TypeFacts.ObjectStrictFacts */ : 16736160 /* TypeFacts.ObjectFacts */; } - if (flags & (16384 /* TypeFlags.Void */ | 32768 /* TypeFlags.Undefined */)) { - return 9830144 /* TypeFacts.UndefinedFacts */; + if (flags & 16384 /* TypeFlags.Void */) { + return 9830144 /* TypeFacts.VoidFacts */; + } + if (flags & 32768 /* TypeFlags.Undefined */) { + return 26607360 /* TypeFacts.UndefinedFacts */; } if (flags & 65536 /* TypeFlags.Null */) { - return 9363232 /* TypeFacts.NullFacts */; + return 42917664 /* TypeFacts.NullFacts */; } if (flags & 12288 /* TypeFlags.ESSymbolLike */) { return strictNullChecks ? 7925520 /* TypeFacts.SymbolStrictFacts */ : 16772880 /* TypeFacts.SymbolFacts */; @@ -69606,37 +70591,56 @@ var ts; if (flags & 131072 /* TypeFlags.Never */) { return 0 /* TypeFacts.None */; } - if (flags & 465829888 /* TypeFlags.Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : - strictNullChecks ? 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; - } if (flags & 1048576 /* TypeFlags.Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* TypeFacts.None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* TypeFacts.None */); } if (flags & 2097152 /* TypeFlags.Intersection */) { - // When an intersection contains a primitive type we ignore object type constituents as they are - // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. - ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */)); - return getIntersectionTypeFacts(type, ignoreObjects); + return getIntersectionTypeFacts(type); } - return 16777215 /* TypeFacts.All */; + return 83886079 /* TypeFacts.UnknownFacts */; } - function getIntersectionTypeFacts(type, ignoreObjects) { + function getIntersectionTypeFacts(type) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + var ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */); // When computing the type facts of an intersection type, certain type facts are computed as `and` // and others are computed as `or`. var oredFacts = 0 /* TypeFacts.None */; - var andedFacts = 16777215 /* TypeFacts.All */; + var andedFacts = 134217727 /* TypeFacts.All */; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - var f = getTypeFacts(t, ignoreObjects); - oredFacts |= f; - andedFacts &= f; + if (!(ignoreObjects && t.flags & 524288 /* TypeFlags.Object */)) { + var f = getTypeFacts(t); + oredFacts |= f; + andedFacts &= f; + } } - return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 16768959 /* TypeFacts.AndFactsMask */; + return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 134209471 /* TypeFacts.AndFactsMask */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } + // This function is similar to getTypeWithFacts, except that in strictNullChecks mode it replaces type + // unknown with the union {} | null | undefined (and reduces that accordingly), and it intersects remaining + // instantiable types with {}, {} | null, or {} | undefined in order to remove null and/or undefined. + function getAdjustedTypeWithFacts(type, facts) { + var reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 /* TypeFlags.Unknown */ ? unknownUnionType : type, facts)); + if (strictNullChecks) { + switch (facts) { + case 524288 /* TypeFacts.NEUndefined */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ ? getIntersectionType([t, getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ && !maybeTypeOfKind(reduced, 65536 /* TypeFlags.Null */) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t; }); + case 1048576 /* TypeFacts.NENull */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ ? getIntersectionType([t, getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ && !maybeTypeOfKind(reduced, 32768 /* TypeFlags.Undefined */) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t; }); + case 2097152 /* TypeFacts.NEUndefinedOrNull */: + case 4194304 /* TypeFacts.Truthy */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 262144 /* TypeFacts.EQUndefinedOrNull */ ? getGlobalNonNullableTypeInstantiation(t) : t; }); + } + } + return reduced; + } + function recombineUnknownType(type) { + return type === unknownUnionType ? unknownType : type; + } function getTypeWithDefault(type, defaultExpression) { return defaultExpression ? getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : @@ -69791,19 +70795,17 @@ var ts; } return links.switchTypes; } - function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) { + // Get the type names from all cases in a switch on `typeof`. The default clause and/or duplicate type names are + // represented as undefined. Return undefined if one or more case clause expressions are not string literals. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + if (ts.some(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 289 /* SyntaxKind.CaseClause */ && !ts.isStringLiteralLike(clause.expression); })) { + return undefined; + } var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 289 /* SyntaxKind.CaseClause */) { - if (ts.isStringLiteralLike(clause.expression)) { - witnesses.push(clause.expression.text); - continue; - } - return ts.emptyArray; - } - if (retainDefault) - witnesses.push(/*explicitDefaultStatement*/ undefined); + var text = clause.kind === 289 /* SyntaxKind.CaseClause */ ? clause.expression.text : undefined; + witnesses.push(text && !ts.contains(witnesses, text) ? text : undefined); } return witnesses; } @@ -69885,8 +70887,8 @@ var ts; var types = origin && origin.flags & 1048576 /* TypeFlags.Union */ ? origin.types : type.types; var mappedTypes; var changed = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; var mapped = t.flags & 1048576 /* TypeFlags.Union */ ? mapType(t, mapper, noReductions) : mapper(t); changed || (changed = t !== mapped); if (mapped) { @@ -69972,8 +70974,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (!(t.flags & 131072 /* TypeFlags.Never */)) { if (!(ts.getObjectFlags(t) & 256 /* ObjectFlags.EvolvingArray */)) { return false; @@ -70434,7 +71436,7 @@ var ts; } // for (const _ in ref) acts as a nonnull on ref if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 243 /* SyntaxKind.ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { - return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); } // Assignment doesn't affect reference return undefined; @@ -70694,7 +71696,7 @@ var ts; if (isEvolvingArrayTypeList(types)) { return getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))); } - var result = getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + var result = recombineUnknownType(getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction)); if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* TypeFlags.Union */ && ts.arraysEqual(result.types, declaredType.types)) { return declaredType; } @@ -70796,11 +71798,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return type.flags & 2 /* TypeFlags.Unknown */ && assumeTrue ? nonNullUnknownType : - getTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); + return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -70922,7 +71923,7 @@ var ts; var targetType = ts.hasStaticModifier(ts.Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows: @@ -70940,7 +71941,7 @@ var ts; // Note that we include any and unknown in the exclusion test because their domain includes null and undefined. var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) || equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* TypeFlags.AnyOrUnknown */ | nullableFlags)); }); - return removeNullable ? getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; + return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* TypeFlags.Any */) { @@ -70950,9 +71951,6 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (assumeTrue && (type.flags & 2 /* TypeFlags.Unknown */) && (operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 35 /* SyntaxKind.ExclamationEqualsToken */) && (valueType.flags & 65536 /* TypeFlags.Null */)) { - return getUnionType([nullType, undefinedType]); - } if ((type.flags & 2 /* TypeFlags.Unknown */) && assumeTrue && (operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */ || operator === 37 /* SyntaxKind.ExclamationEqualsEqualsToken */)) { if (valueType.flags & (131068 /* TypeFlags.Primitive */ | 67108864 /* TypeFlags.NonPrimitive */)) { return valueType; @@ -70972,7 +71970,7 @@ var ts; valueType.flags & 65536 /* TypeFlags.Null */ ? assumeTrue ? 131072 /* TypeFacts.EQNull */ : 1048576 /* TypeFacts.NENull */ : assumeTrue ? 65536 /* TypeFacts.EQUndefined */ : 524288 /* TypeFacts.NEUndefined */; - return type.flags & 2 /* TypeFlags.Unknown */ && facts & (1048576 /* TypeFacts.NENull */ | 2097152 /* TypeFacts.NEUndefinedOrNull */) ? nonNullUnknownType : getTypeWithFacts(type, facts); + return getAdjustedTypeWithFacts(type, facts); } if (assumeTrue) { var filterFn = operator === 34 /* SyntaxKind.EqualsEqualsToken */ ? @@ -70993,24 +71991,13 @@ var ts; var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } - if (type.flags & 1 /* TypeFlags.Any */ && literal.text === "function") { - return type; - } - if (assumeTrue && type.flags & 2 /* TypeFlags.Unknown */ && literal.text === "object") { - // The non-null unknown type is used to track whether a previous narrowing operation has removed the null type - // from the unknown type. For example, the expression `x && typeof x === 'object'` first narrows x to the non-null - // unknown type, and then narrows that to the non-primitive type. - return type === nonNullUnknownType ? nonPrimitiveType : getUnionType([nonPrimitiveType, nullType]); - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 128 /* TypeFacts.TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */; - var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text); - return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts); + return assumeTrue ? + narrowTypeByTypeName(type, literal.text) : + getTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */); } function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); @@ -71057,97 +72044,52 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* TypeFlags.Never */ ? defaultType : getUnionType([caseType, defaultType]); } - function getImpliedTypeFromTypeofGuard(type, text) { - switch (text) { - case "function": - return type.flags & 1 /* TypeFlags.Any */ ? type : globalFunctionType; - case "object": - return type.flags & 2 /* TypeFlags.Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; - default: - return typeofTypesByName.get(text); - } - } - // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are - // super-types of the implied guard will be retained in the final type: this is because type-facts only - // filter. Instead, we would like to replace those union constituents with the more precise type implied by - // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not - // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to - // filtering by type-facts. - function narrowUnionMemberByTypeof(candidate) { - return function (type) { - if (isTypeSubtypeOf(type, candidate)) { - return type; - } - if (isTypeSubtypeOf(candidate, type)) { - return candidate; - } - if (type.flags & 465829888 /* TypeFlags.Instantiable */) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(candidate, constraint)) { - return getIntersectionType([type, candidate]); - } - } - return type; - }; + function narrowTypeByTypeName(type, typeName) { + switch (typeName) { + case "string": return narrowTypeByTypeFacts(type, stringType, 1 /* TypeFacts.TypeofEQString */); + case "number": return narrowTypeByTypeFacts(type, numberType, 2 /* TypeFacts.TypeofEQNumber */); + case "bigint": return narrowTypeByTypeFacts(type, bigintType, 4 /* TypeFacts.TypeofEQBigInt */); + case "boolean": return narrowTypeByTypeFacts(type, booleanType, 8 /* TypeFacts.TypeofEQBoolean */); + case "symbol": return narrowTypeByTypeFacts(type, esSymbolType, 16 /* TypeFacts.TypeofEQSymbol */); + case "object": return type.flags & 1 /* TypeFlags.Any */ ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32 /* TypeFacts.TypeofEQObject */), narrowTypeByTypeFacts(type, nullType, 131072 /* TypeFacts.EQNull */)]); + case "function": return type.flags & 1 /* TypeFlags.Any */ ? type : narrowTypeByTypeFacts(type, globalFunctionType, 64 /* TypeFacts.TypeofEQFunction */); + case "undefined": return narrowTypeByTypeFacts(type, undefinedType, 65536 /* TypeFacts.EQUndefined */); + } + return narrowTypeByTypeFacts(type, nonPrimitiveType, 128 /* TypeFacts.TypeofEQHostObject */); + } + function narrowTypeByTypeFacts(type, impliedType, facts) { + return mapType(type, function (t) { + // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate + // the constituent based on its type facts. We use the strict subtype relation because it treats `object` + // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, + // but are classified as "function" according to `typeof`. + return isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? getTypeFacts(t) & facts ? t : neverType : + // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied + // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. + isTypeSubtypeOf(impliedType, t) ? impliedType : + // Neither the constituent nor the implied type is a subtype of the other, however their domains may still + // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate + // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. + getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : + neverType; + }); } function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { - var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true); - if (!switchWitnesses.length) { + var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!witnesses) { return type; } - // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause - var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); - var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); - var clauseWitnesses; - var switchFacts; - if (defaultCaseLocation > -1) { - // We no longer need the undefined denoting an explicit default case. Remove the undefined and - // fix-up clauseStart and clauseEnd. This means that we don't have to worry about undefined in the - // witness array. - var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); - // The adjusted clause start and end after removing the `default` statement. - var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; - var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; - clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); - switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); - } - else { - clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); - switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); - } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause. + var defaultIndex = ts.findIndex(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 290 /* SyntaxKind.DefaultClause */; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultIndex >= clauseStart && defaultIndex < clauseEnd); if (hasDefaultClause) { - return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + // In the default clause we filter constituents down to those that are not-equal to all handled cases. + var notEqualFacts_1 = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); + return filterType(type, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }); } - /* - The implied type is the raw type suggested by a - value being caught in this clause. - - When the clause contains a default case we ignore - the implied type and try to narrow using any facts - we can learn: see `switchFacts`. - - Example: - switch (typeof x) { - case 'number': - case 'string': break; - default: break; - case 'number': - case 'boolean': break - } - - In the first clause (case `number` and `string`) the - implied type is number | string. - - In the default clause we de not compute an implied type. - - In the third clause (case `number` and `boolean`) - the naive implied type is number | boolean, however - we use the type facts to narrow the implied type to - boolean. We know that number cannot be selected - because it is caught in the first clause. - */ - var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts); - return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts); + // In the non-default cause we create a union of the type narrowed by each of the listed cases. + var clauseWitnesses = witnesses.slice(clauseStart, clauseEnd); + return getUnionType(ts.map(clauseWitnesses, function (text) { return text ? narrowTypeByTypeName(type, text) : neverType; })); } function isMatchingConstructorReference(expr) { return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || @@ -71198,7 +72140,7 @@ var ts; var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } @@ -71232,29 +72174,48 @@ var ts; if (!nonConstructorTypeInUnion) return type; } - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { + function getNarrowedType(type, candidate, assumeTrue, checkDerived) { + var _a; + var key = type.flags & 1048576 /* TypeFlags.Union */ ? "N".concat(getTypeId(type), ",").concat(getTypeId(candidate), ",").concat((assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)) : undefined; + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); + } + function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) { + var isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf; if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - // If the current type is a union type, remove all constituents that couldn't be instances of - // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 1048576 /* TypeFlags.Union */) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 131072 /* TypeFlags.Never */)) { - return assignableType; - } + if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { + return candidate; } - // If the candidate type is a subtype of the target type, narrow to the candidate type. - // Otherwise, if the target type is assignable to the candidate type, keep the target type. - // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate - // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the - // two types. - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); + // We first attempt to filter the current type, narrowing constituents as appropriate and removing + // constituents that are unrelated to the candidate. + var keyPropertyName = type.flags & 1048576 /* TypeFlags.Union */ ? getKeyPropertyName(type) : undefined; + var narrowedType = mapType(candidate, function (c) { + // If a discriminant property is available, use that to reduce the type. + var discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName); + var matching = discriminant && getConstituentTypeForKeyType(type, discriminant); + // For each constituent t in the current type, if t and and c are directly related, pick the most + // specific of the two. When t and c are related in both directions, we prefer c for type predicates + // because that is the asserted type, but t for `instanceof` because generics aren't reflected in + // prototype object types. + var directlyRelated = mapType(matching || type, checkDerived ? + function (t) { return isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType; } : + function (t) { return isTypeSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : neverType; }); + // If no constituents are directly related, create intersections for any generic constituents that + // are related by constraint. + return directlyRelated.flags & 131072 /* TypeFlags.Never */ ? + mapType(type, function (t) { return maybeTypeOfKind(t, 465829888 /* TypeFlags.Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType; }) : + directlyRelated; + }); + // If filtering produced a non-empty type, return that. Otherwise, pick the most specific of the two + // based on assignability, or as a last resort produce an intersection. + return !(narrowedType.flags & 131072 /* TypeFlags.Never */) ? narrowedType : + isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -71282,15 +72243,15 @@ var ts; var predicateArgument = getTypePredicateArgument(predicate, callExpression); if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + return getNarrowedType(type, predicate.type, assumeTrue, /*checkDerived*/ false); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && !(getTypeFacts(predicate.type) & 65536 /* TypeFacts.EQUndefined */)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(predicateArgument, type); if (access) { - return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); + return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, /*checkDerived*/ false); }); } } } @@ -71343,7 +72304,7 @@ var ts; } function narrowTypeByOptionality(type, expr, assumePresent) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -71429,8 +72390,8 @@ var ts; var annotationIncludesUndefined = strictNullChecks && declaration.kind === 164 /* SyntaxKind.Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 32768 /* TypeFlags.Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* TypeFlags.Undefined */); + getTypeFacts(declaredType) & 16777216 /* TypeFacts.IsUndefined */ && + !(getTypeFacts(checkExpression(declaration.initializer)) & 16777216 /* TypeFacts.IsUndefined */); popTypeResolution(); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* TypeFacts.NEUndefined */) : declaredType; } @@ -71451,7 +72412,9 @@ var ts; !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { - return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); + return type.flags & 2097152 /* TypeFlags.Intersection */ ? + ts.some(type.types, isGenericTypeWithUnionConstraint) : + !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); } function isGenericTypeWithoutNullableConstraint(type) { return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* TypeFlags.Nullable */)); @@ -71465,7 +72428,7 @@ var ts; !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 64 /* CheckMode.RestBindingElement */ ? getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) - : getContextualType(node)); + : getContextualType(node, /*contextFlags*/ undefined)); return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { @@ -71479,7 +72442,7 @@ var ts; var substituteConstraints = !(checkMode && checkMode & 2 /* CheckMode.Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); - return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* TypeFlags.Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (n) { @@ -71627,9 +72590,7 @@ var ts; getNodeLinks(container).flags |= 8192 /* NodeCheckFlags.CaptureArguments */; return getTypeOfSymbol(symbol); } - // We should only mark aliases as referenced if there isn't a local value declaration - // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that - if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + if (shouldMarkIdentifierAliasReferenced(node)) { markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); @@ -71756,13 +72717,32 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function shouldMarkIdentifierAliasReferenced(node) { + var _a; + var parent = node.parent; + if (parent) { + // A property access expression LHS? checkPropertyAccessExpression will handle that. + if (ts.isPropertyAccessExpression(parent) && parent.expression === node) { + return false; + } + // Next two check for an identifier inside a type only export. + if (ts.isExportSpecifier(parent) && parent.isTypeOnly) { + return false; + } + var greatGrandparent = (_a = parent.parent) === null || _a === void 0 ? void 0 : _a.parent; + if (greatGrandparent && ts.isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) { + return false; + } + } + return true; + } function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } @@ -71890,7 +72870,7 @@ var ts; } function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) { if (ts.isPropertyDeclaration(container) && ts.hasStaticModifier(container) && - container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.length(container.parent.decorators)) { + container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.hasDecorators(container.parent)) { error(thisExpression, ts.Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); } } @@ -72312,7 +73292,7 @@ var ts; // We have an object literal method. Check if the containing object literal has a contextual type // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in // any directly enclosing object literals. - var contextualType = getApparentTypeOfContextualType(containingLiteral); + var contextualType = getApparentTypeOfContextualType(containingLiteral, /*contextFlags*/ undefined); var literal = containingLiteral; var type = contextualType; while (type) { @@ -72324,7 +73304,7 @@ var ts; break; } literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); + type = getApparentTypeOfContextualType(literal, /*contextFlags*/ undefined); } // There was no contextual ThisType for the containing object literal, so the contextual type // for 'this' is the non-null form of the contextual type for the containing object literal or @@ -72381,7 +73361,7 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } - function getContextualTypeForVariableLikeDeclaration(declaration) { + function getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -72390,18 +73370,18 @@ var ts; case 164 /* SyntaxKind.Parameter */: return getContextuallyTypedParameterType(declaration); case 203 /* SyntaxKind.BindingElement */: - return getContextualTypeForBindingElement(declaration); + return getContextualTypeForBindingElement(declaration, contextFlags); case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isStatic(declaration)) { - return getContextualTypeForStaticPropertyDeclaration(declaration); + return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); } // By default, do nothing and return undefined - only the above cases have context implied by a parent } } - function getContextualTypeForBindingElement(declaration) { + function getContextualTypeForBindingElement(declaration, contextFlags) { var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - var parentType = getContextualTypeForVariableLikeDeclaration(parent) || + var parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== 203 /* SyntaxKind.BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 64 /* CheckMode.RestBindingElement */ : 0 /* CheckMode.Normal */); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; @@ -72417,8 +73397,8 @@ var ts; return getTypeOfPropertyOfType(parentType, text); } } - function getContextualTypeForStaticPropertyDeclaration(declaration) { - var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent); + function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) { + var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags); if (!parentType) return undefined; return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName); @@ -72434,29 +73414,32 @@ var ts; function getContextualTypeForInitializerExpression(node, contextFlags) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var result = getContextualTypeForVariableLikeDeclaration(declaration); + var result = getContextualTypeForVariableLikeDeclaration(declaration, contextFlags); if (result) { return result; } - if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable + if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name) && declaration.name.elements.length > 0) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } } return undefined; } - function getContextualTypeForReturnExpression(node) { + function getContextualTypeForReturnExpression(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { var functionFlags = ts.getFunctionFlags(func); if (functionFlags & 1 /* FunctionFlags.Generator */) { // Generator or AsyncGenerator function - var use = functionFlags & 2 /* FunctionFlags.Async */ ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; - var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined); - if (!iterationTypes) { + var isAsyncGenerator_1 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_1); }); + } + var iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + if (!iterationReturnType) { return undefined; } - contextualReturnType = iterationTypes.returnType; + contextualReturnType = iterationReturnType; // falls through to unwrap Promise for AsyncGenerators } if (functionFlags & 2 /* FunctionFlags.Async */) { // Async function or AsyncGenerator function @@ -72477,15 +73460,19 @@ var ts; } return undefined; } - function getContextualTypeForYieldOperand(node) { + function getContextualTypeForYieldOperand(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { + var isAsyncGenerator_2 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_2); }); + } return node.asteriskToken ? contextualReturnType - : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, isAsyncGenerator_2); } } return undefined; @@ -72505,14 +73492,14 @@ var ts; } function getContextualIterationType(kind, functionDecl) { var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* FunctionFlags.Async */); - var contextualReturnType = getContextualReturnType(functionDecl); + var contextualReturnType = getContextualReturnType(functionDecl, /*contextFlags*/ undefined); if (contextualReturnType) { return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || undefined; } return undefined; } - function getContextualReturnType(functionDecl) { + function getContextualReturnType(functionDecl, contextFlags) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed var returnType = getReturnTypeFromAnnotation(functionDecl); @@ -72527,7 +73514,7 @@ var ts; } var iife = ts.getImmediatelyInvokedFunctionExpression(functionDecl); if (iife) { - return getContextualType(iife); + return getContextualType(iife, contextFlags); } return undefined; } @@ -72601,6 +73588,14 @@ var ts; var lhsType = getTypeOfExpression(e.expression); return ts.isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText); } + if (ts.isElementAccessExpression(e)) { + var propType = checkExpressionCached(e.argumentExpression); + if (!isTypeUsableAsPropertyName(propType)) { + return undefined; + } + var lhsType = getTypeOfExpression(e.expression); + return getPropertyOfType(lhsType, getPropertyNameFromType(propType)); + } return undefined; function tryGetPrivateIdentifierPropertyOfType(type, id) { var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id); @@ -72622,7 +73617,7 @@ var ts; if (decl && (ts.isPropertyDeclaration(decl) || ts.isPropertySignature(decl))) { var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); return (overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper)) || - (decl.initializer && getTypeOfExpression(binaryExpression.left)); + (ts.isPropertyDeclaration(decl) ? decl.initializer && getTypeOfExpression(binaryExpression.left) : undefined); } if (kind === 0 /* AssignmentDeclarationKind.None */) { return getTypeOfExpression(binaryExpression.left); @@ -72755,7 +73750,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; - var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element, contextFlags); if (propertyAssignmentType) { return propertyAssignmentType; } @@ -72790,8 +73785,8 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined; } - function getContextualTypeForChildJsxExpression(node, child) { - var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + function getContextualTypeForChildJsxExpression(node, child, contextFlags) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); // JSX expression is in children of JSX Element, we will look for an "children" attribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { @@ -72809,27 +73804,27 @@ var ts; } }, /*noReductions*/ true)); } - function getContextualTypeForJsxExpression(node) { + function getContextualTypeForJsxExpression(node, contextFlags) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) - ? getContextualType(node) + ? getContextualType(node, contextFlags) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent, node) + ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) : undefined; } - function getContextualTypeForJsxAttribute(attribute) { + function getContextualTypeForJsxAttribute(attribute, contextFlags) { // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName if (ts.isJsxAttribute(attribute)) { - var attributesType = getApparentTypeOfContextualType(attribute.parent); + var attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return getContextualType(attribute.parent); + return getContextualType(attribute.parent, contextFlags); } } // Return true if the given expression is possibly a discriminant value. We limit the kinds of @@ -72882,22 +73877,20 @@ var ts; 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 && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { // 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. - if (contextFlags && contextFlags & 1 /* ContextFlags.Signature */) { - return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); - } + return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); + } + if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.returnMapper) { // For other purposes (e.g. determining whether to produce literal types) we only // incorporate inferences made from the return type in a function call. We remove // the 'boolean' type from the contextual type such that contextually typed boolean // literals actually end up widening to 'boolean' (see #48363). - if (inferenceContext.returnMapper) { - var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); - return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? - filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : - type; - } + var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); + return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? + filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : + type; } } return contextualType; @@ -72952,9 +73945,9 @@ var ts; return getContextualTypeForInitializerExpression(node, contextFlags); case 214 /* SyntaxKind.ArrowFunction */: case 247 /* SyntaxKind.ReturnStatement */: - return getContextualTypeForReturnExpression(node); + return getContextualTypeForReturnExpression(node, contextFlags); case 224 /* SyntaxKind.YieldExpression */: - return getContextualTypeForYieldOperand(parent); + return getContextualTypeForYieldOperand(parent, contextFlags); case 218 /* SyntaxKind.AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); case 208 /* SyntaxKind.CallExpression */: @@ -72992,17 +73985,17 @@ var ts; case 271 /* SyntaxKind.ExportAssignment */: return tryGetTypeFromEffectiveTypeNode(parent); case 288 /* SyntaxKind.JsxExpression */: - return getContextualTypeForJsxExpression(parent); + return getContextualTypeForJsxExpression(parent, contextFlags); case 285 /* SyntaxKind.JsxAttribute */: case 287 /* SyntaxKind.JsxSpreadAttribute */: - return getContextualTypeForJsxAttribute(parent); + return getContextualTypeForJsxAttribute(parent, contextFlags); case 280 /* SyntaxKind.JsxOpeningElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; function tryFindWhenConstTypeReference(node) { - return getContextualType(node); + return getContextualType(node, contextFlags); } } function getInferenceContext(node) { @@ -73262,8 +74255,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var current = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var current = types_18[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -73304,7 +74297,7 @@ var ts; var elementCount = elements.length; var elementTypes = []; var elementFlags = []; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var inDestructuringPattern = ts.isAssignmentTarget(node); var inConstContext = isConstContext(node); var hasOmittedExpression = false; @@ -73475,7 +74468,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 201 /* SyntaxKind.ObjectBindingPattern */ || contextualType.pattern.kind === 205 /* SyntaxKind.ObjectLiteralExpression */); var inConstContext = isConstContext(node); @@ -73814,7 +74807,7 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes, /*contextFlags*/ undefined); var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* SymbolFlags.Property */, jsxChildrenPropertyName); @@ -74425,19 +75418,19 @@ var ts; return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { - return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */); + return !!(getTypeFacts(type) & 50331648 /* TypeFacts.IsUndefinedOrNull */); } function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function reportObjectPossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportObjectPossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); } - function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); @@ -74447,9 +75440,9 @@ var ts; error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */; - if (kind) { - reportError(node, kind); + var facts = getTypeFacts(type); + if (facts & 50331648 /* TypeFacts.IsUndefinedOrNull */) { + reportError(node, facts); var t = getNonNullableType(type); return t.flags & (98304 /* TypeFlags.Nullable */ | 131072 /* TypeFlags.Never */) ? errorType : t; } @@ -74618,9 +75611,8 @@ var ts; markAliasReferenced(parentSymbol, node); } return isErrorType(apparentType) ? errorType : apparentType; - ; } - prop = getPropertyOfType(apparentType, right.escapedText); + prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ node.kind === 161 /* SyntaxKind.QualifiedName */); } // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. // `Foo` is also not referenced in `enum FooCopy { Bar = Foo.Bar }`, because the enum member value gets inlined @@ -74745,7 +75737,7 @@ var ts; assumeUninitialized = true; } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) { error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -74928,9 +75920,9 @@ var ts; function getSuggestedSymbolForNonexistentProperty(name, containingType) { var props = getPropertiesOfType(containingType); if (typeof name !== "string") { - var parent_2 = name.parent; - if (ts.isPropertyAccessExpression(parent_2)) { - props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + var parent_3 = name.parent; + if (ts.isPropertyAccessExpression(parent_3)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_3, containingType, prop); }); } name = ts.idText(name); } @@ -75432,29 +76424,43 @@ var ts; // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. if (node.kind !== 165 /* SyntaxKind.Decorator */) { - var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); + var skipBindingPatterns = ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }); + var contextualType = getContextualType(node, skipBindingPatterns ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); if (contextualType) { var inferenceTargetType = getReturnTypeOfSignature(signature); if (couldContainTypeVariables(inferenceTargetType)) { - // We clone the inference context to avoid disturbing a resolution in progress for an - // outer call expression. Effectively we just want a snapshot of whatever has been - // inferred for any outer call expression so far. var outerContext = getInferenceContext(node); - var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); - var instantiatedType = instantiateType(contextualType, outerMapper); - // If the contextual type is a generic function type with a single call signature, we - // instantiate the type with its own type parameters and type arguments. This ensures that - // the type parameters are not erased to type any during type inference such that they can - // be inferred as actual types from the contextual type. For example: - // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; - // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); - // Above, the type of the 'value' parameter is inferred to be 'A'. - var contextualSignature = getSingleCallSignature(instantiatedType); - var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : - instantiatedType; - // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + var isFromBindingPattern = !skipBindingPatterns && getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) !== contextualType; + // A return type inference from a binding pattern can be used in instantiating the contextual + // type of an argument later in inference, but cannot stand on its own as the final return type. + // It is incorporated into `context.returnMapper` which is used in `instantiateContextualType`, + // but doesn't need to go into `context.inferences`. This allows a an array binding pattern to + // produce a tuple for `T` in + // declare function f(cb: () => T): T; + // const [e1, e2, e3] = f(() => [1, "hi", true]); + // but does not produce any inference for `T` in + // declare function f(): T; + // const [e1, e2, e3] = f(); + if (!isFromBindingPattern) { + // We clone the inference context to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); + var instantiatedType = instantiateType(contextualType, outerMapper); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + } // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -75781,7 +76787,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_24 = 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 === 225 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -75798,7 +76804,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_24(i); + _loop_26(i); } return effectiveArgs_1; } @@ -76005,7 +77011,7 @@ var ts; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray; var typeArguments; - if (!isDecorator) { + if (!isDecorator && !ts.isSuperCall(node)) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 106 /* SyntaxKind.SuperKeyword */) { @@ -76084,6 +77090,15 @@ var ts; if (result) { return result; } + result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + // Preemptively cache the result; getResolvedSignature will do this after we return, but + // we need to ensure that the result is present for the error checks below so that if + // this signature is encountered again, we handle the circularity (rather than producing a + // different result which may produce no errors and assert). Callers of getResolvedSignature + // don't hit this issue because they only observe this result after it's had a chance to + // be cached, but the error reporting code below executes before getResolvedSignature sets + // resolvedSignature. + getNodeLinks(node).resolvedSignature = result; // No signatures were applicable. Now report errors based on the last applicable signature with // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, @@ -76118,7 +77133,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_25 = 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) { @@ -76136,7 +77151,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_25(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"); @@ -76175,7 +77190,7 @@ var ts; } } } - return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + return result; function addImplementationSuccessElaboration(failed, diagnostic) { var _a, _b; var oldCandidatesForArgumentError = candidatesForArgumentError; @@ -76255,7 +77270,7 @@ var ts; argCheckMode = checkMode & 32 /* CheckMode.IsForStringLiteralArgumentCompletions */; if (inferenceContext) { var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -76294,7 +77309,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_26 = 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; }); @@ -76302,7 +77317,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_26(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -76470,7 +77485,7 @@ var ts; // returns a function type, we choose to defer processing. This narrowly permits function composition // operators to flow inferences through return types, but otherwise processes calls right away. We // use the resolvingSignature singleton to indicate that we deferred processing. This result will be - // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and + // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and // from which we never make inferences). if (checkMode & 8 /* CheckMode.SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) { skippedGenericFunction(node, checkMode); @@ -76647,8 +77662,8 @@ var ts; if (apparentType.flags & 1048576 /* TypeFlags.Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var constituent = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var constituent = types_19[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -76814,7 +77829,7 @@ var ts; // file would probably be preferable. var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* SymbolFlags.Type */); var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* SymbolFlags.Type */, node); - var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); var parameterSymbol = createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, "props"); parameterSymbol.type = result; return createSignature(declaration, @@ -77023,8 +78038,8 @@ var ts; var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode); if (signature === resolvingSignature) { // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that - // returns a function type. We defer checking and return nonInferrableType. - return nonInferrableType; + // returns a function type. We defer checking and return silentNeverType. + return silentNeverType; } checkDeprecatedSignature(signature, node); if (node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { @@ -77632,17 +78647,6 @@ var ts; } } } - var restType = getEffectiveRestType(context); - if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { - // The contextual signature has a generic rest parameter. We first instantiate the contextual - // signature (without fixing type parameters) and assign types to contextually typed parameters. - var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper); - assignContextualParameterTypes(signature, instantiatedContext); - // We then infer from a tuple type representing the parameters that correspond to the contextual - // rest parameter. - var restPos = getParameterCount(context) - 1; - inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType); - } } function assignContextualParameterTypes(signature, context) { if (context.typeParameters) { @@ -77835,7 +78839,7 @@ var ts; var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : - instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); + instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func, /*contextFlags*/ undefined); if (isGenerator) { yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* IterationTypeKind.Yield */, isAsync); returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* IterationTypeKind.Return */, isAsync); @@ -77906,7 +78910,7 @@ var ts; nextType = iterationTypes && iterationTypes.nextType; } else { - nextType = getContextualType(yieldExpression); + nextType = getContextualType(yieldExpression, /*contextFlags*/ undefined); } if (nextType) ts.pushIfUnique(nextTypes, nextType); @@ -77921,45 +78925,12 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - /** - * Collect the TypeFacts learned from a typeof switch with - * total clauses `witnesses`, and the active clause ranging - * from `start` to `end`. Parameter `hasDefault` denotes - * whether the active clause contains a default clause. - */ - function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + // Return the combined not-equal type facts for all cases except those between the start and end indices. + function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) { var facts = 0 /* TypeFacts.None */; - // When in the default we only collect inequality facts - // because default is 'in theory' a set of infinite - // equalities. - if (hasDefault) { - // Value is not equal to any types after the active clause. - for (var i = end; i < witnesses.length; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - // Remove inequalities for types that appear in the - // active clause because they appear before other - // types collected so far. - for (var i = start; i < end; i++) { - facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); - } - // Add inequalities for types before the active clause unconditionally. - for (var i = 0; i < start; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - } - // When in an active clause without default the set of - // equalities is finite. - else { - // Add equalities for all types in the active clause. - for (var i = start; i < end; i++) { - facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeFacts.TypeofEQHostObject */; - } - // Remove equalities for types that appear before the - // active clause. - for (var i = 0; i < start; i++) { - facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); - } + for (var i = 0; i < witnesses.length; i++) { + var witness = i < start || i >= end ? witnesses[i] : undefined; + facts |= witness !== undefined ? typeofNEFacts.get(witness) || 32768 /* TypeFacts.TypeofNEHostObject */ : 0; } return facts; } @@ -77969,16 +78940,19 @@ var ts; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 216 /* SyntaxKind.TypeOfExpression */) { - var operandType = getTypeOfExpression(node.expression.expression); - var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); - // notEqualFacts states that the type of the switched value is not equal to every type in the switch. - var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_6 = getBaseConstraintOfType(operandType) || operandType; - // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_6.flags & 3 /* TypeFlags.AnyOrUnknown */) { - return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_1) === 556800 /* TypeFacts.AllTypeofNE */; + var witnesses = getSwitchClauseTypeOfWitnesses(node); + if (!witnesses) { + return false; } - return !!(filterType(type_6, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* TypeFlags.Never */); + var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(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 */) { + // We special case the top types to be exhaustive when all cases are handled. + return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_2) === 556800 /* TypeFacts.AllTypeofNE */; + } + // 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); if (!isLiteralType(type)) { @@ -78145,11 +79119,16 @@ var ts; if (isContextSensitive(node)) { if (contextualSignature) { var inferenceContext = getInferenceContext(node); + var instantiatedContextualSignature = void 0; if (checkMode && checkMode & 2 /* CheckMode.Inferential */) { inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); + var restType = getEffectiveRestType(contextualSignature); + if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { + instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper); + } } - var instantiatedContextualSignature = inferenceContext ? - instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature; + instantiatedContextualSignature || (instantiatedContextualSignature = inferenceContext ? + instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature); assignContextualParameterTypes(signature, instantiatedContextualSignature); } else { @@ -78339,7 +79318,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks && !(type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 131072 /* TypeFlags.Never */)) && - !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getTypeFacts(type) & 16777216 /* TypeFacts.IsUndefined */)) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); } } @@ -78448,7 +79427,7 @@ var ts; error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } if (node.operator === 39 /* SyntaxKind.PlusToken */) { - if (maybeTypeOfKind(operandType, 2112 /* TypeFlags.BigIntLike */)) { + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* TypeFlags.BigIntLike */)) { error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType))); } return numberType; @@ -78507,8 +79486,8 @@ var ts; } if (type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { - var t = types_21[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var t = types_20[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -78735,7 +79714,7 @@ var ts; // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* TypeFlags.Undefined */)) { + !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & 16777216 /* TypeFacts.IsUndefined */)) { sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -78748,6 +79727,10 @@ var ts; if (target.kind === 221 /* SyntaxKind.BinaryExpression */ && target.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; + // A default value is specified, so remove undefined from the final type. + if (strictNullChecks) { + sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); + } } if (target.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); @@ -78888,7 +79871,11 @@ var ts; var operator = operatorToken.kind; if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */ || operator === 56 /* SyntaxKind.BarBarToken */ || operator === 60 /* SyntaxKind.QuestionQuestionToken */) { if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); + var parent = node.parent; + while (parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */ + || ts.isBinaryExpression(parent) && (parent.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ || parent.operatorToken.kind === 56 /* SyntaxKind.BarBarToken */)) { + parent = parent.parent; + } checkTestingKnownTruthyCallableOrAwaitableType(node.left, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } checkTruthinessOfType(leftType, node.left); @@ -79112,6 +80099,10 @@ var ts; case 35 /* SyntaxKind.ExclamationEqualsToken */: case 36 /* SyntaxKind.EqualsEqualsEqualsToken */: case 37 /* SyntaxKind.ExclamationEqualsEqualsToken */: + if (ts.isLiteralExpressionOfObject(left) || ts.isLiteralExpressionOfObject(right)) { + var eqType = operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */; + error(errorNode, ts.Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); + } reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); }); return booleanType; case 102 /* SyntaxKind.InstanceOfKeyword */: @@ -79131,7 +80122,7 @@ var ts; case 56 /* SyntaxKind.BarBarToken */: case 75 /* SyntaxKind.BarBarEqualsToken */: { var resultType_3 = getTypeFacts(leftType) & 8388608 /* TypeFacts.Falsy */ ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* UnionReduction.Subtype */) : + getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* UnionReduction.Subtype */) : leftType; if (operator === 75 /* SyntaxKind.BarBarEqualsToken */) { checkAssignmentOperator(rightType); @@ -79383,7 +80374,7 @@ var ts; type = anyType; addLazyDiagnostic(function () { if (noImplicitAny && !ts.expressionResultIsUnused(node)) { - var contextualType = getContextualType(node); + var contextualType = getContextualType(node, /*contextFlags*/ undefined); if (!contextualType || isTypeAny(contextualType)) { error(node, ts.Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); } @@ -79424,7 +80415,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node, /*contextFlags*/ undefined) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; } function isTemplateLiteralContextualType(type) { return !!(type.flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */) || @@ -79452,7 +80443,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node, /*contextFlags*/ undefined)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -79567,7 +80558,7 @@ var ts; var type = checkExpression(node, checkMode, forceTuple); return isConstContext(node) || ts.isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : - getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node)); + getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node, /*contextFlags*/ undefined) : contextualType, node, /*contextFlags*/ undefined)); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. @@ -79677,8 +80668,8 @@ var ts; var result = []; var oldTypeParameters; var newTypeParameters; - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var tp = typeParameters_2[_i]; + for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { + var tp = typeParameters_3[_i]; var name = tp.symbol.escapedName; if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) { var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name); @@ -80000,12 +80991,14 @@ var ts; error(node, ts.Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); } else if (modifiers === 32768 /* ModifierFlags.In */ || modifiers === 65536 /* ModifierFlags.Out */) { - var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubType : markerSuperType); - var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperType : markerSubType); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); + var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck); + var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck); var saveVarianceTypeParameter = typeParameter; varianceTypeParameter = typeParameter; checkTypeAssignableTo(source, target, node, ts.Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation); varianceTypeParameter = saveVarianceTypeParameter; + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } } @@ -80026,7 +81019,7 @@ var ts; error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + if ((node.questionToken || isJSDocOptionalParameter(node)) && ts.isBindingPattern(node.name) && func.body) { error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { @@ -80355,7 +81348,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_27 = 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)); @@ -80370,7 +81363,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_27(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -80403,6 +81396,9 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); + if (ts.isMethodDeclaration(node) && node.asteriskToken && ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_a_generator); + } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // method signatures already report "implementation not allowed in ambient context" elsewhere @@ -80530,6 +81526,9 @@ var ts; return !!ts.forEachChild(node, nodeImmediatelyReferencesSuperOrThis); } function checkAccessorDeclaration(node) { + if (ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_an_accessor); + } addLazyDiagnostic(checkAccessorDeclarationDiagnostics); checkSourceElement(node.body); setNodeLinksForPrivateIdentifierScope(node); @@ -80587,6 +81586,12 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) { + if (index < typeParameters.length) { + return getTypeFromTypeNode(node.typeArguments[index]); + } + return getEffectiveTypeArguments(node, typeParameters)[index]; + } function getEffectiveTypeArguments(node, typeParameters) { return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } @@ -80828,8 +81833,11 @@ var ts; if (node.assertions) { var override = ts.getResolutionModeOverrideForClause(node.assertions.assertClause, grammarErrorOnNode); if (override) { + if (!ts.isNightly()) { + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } } } @@ -81214,7 +82222,7 @@ var ts; * @param type The type of the promise. * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. */ - function getPromisedTypeOfPromise(type, errorNode) { + function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) { // // { // type // then( // thenFunction @@ -81249,7 +82257,29 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); + var thisTypeForError; + var candidates; + for (var _i = 0, thenSignatures_1 = thenSignatures; _i < thenSignatures_1.length; _i++) { + var thenSignature = thenSignatures_1[_i]; + var thisType = getThisTypeOfSignature(thenSignature); + if (thisType && thisType !== voidType && !isTypeRelatedTo(type, thisType, subtypeRelation)) { + thisTypeForError = thisType; + } + else { + candidates = ts.append(candidates, thenSignature); + } + } + if (!candidates) { + ts.Debug.assertIsDefined(thisTypeForError); + if (thisTypeForErrorOut) { + thisTypeForErrorOut.value = thisTypeForError; + } + if (errorNode) { + error(errorNode, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError)); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(candidates, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -81303,6 +82333,34 @@ var ts; isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : type; } + function isAwaitedTypeNeeded(type) { + // If this is already an `Awaited`, we shouldn't wrap it. This helps to avoid `Awaited>` in higher-order. + if (isTypeAny(type) || isAwaitedTypeInstantiation(type)) { + return false; + } + // We only need `Awaited` if `T` contains possibly non-primitive types. + if (isGenericObjectType(type)) { + var baseConstraint = getBaseConstraintOfType(type); + // 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) : + maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { + return true; + } + } + return false; + } + function tryCreateAwaitedType(type) { + // Nothing to do if `Awaited` doesn't exist + var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); + if (awaitedSymbol) { + // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where + // an `Awaited` would suffice. + return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); + } + return undefined; + } function createAwaitedTypeIfNeeded(type) { // We wrap type `T` in `Awaited` based on the following conditions: // - `T` is not already an `Awaited`, and @@ -81311,26 +82369,10 @@ var ts; // - `T` has no base constraint, or // - The base constraint of `T` is `any`, `unknown`, `object`, or `{}`, or // - The base constraint of `T` is an object type with a callable `then` method. - if (isTypeAny(type)) { - return type; - } - // If this is already an `Awaited`, just return it. This helps to avoid `Awaited>` in higher-order. - if (isAwaitedTypeInstantiation(type)) { - return type; - } - // Only instantiate `Awaited` if `T` contains possibly non-primitive types. - if (isGenericObjectType(type)) { - var baseConstraint = getBaseConstraintOfType(type); - // Only instantiate `Awaited` if `T` 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)) { - // Nothing to do if `Awaited` doesn't exist - var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); - if (awaitedSymbol) { - // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where - // an `Awaited` would suffice. - return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); - } + if (isAwaitedTypeNeeded(type)) { + var awaitedType = tryCreateAwaitedType(type); + if (awaitedType) { + return awaitedType; } } ts.Debug.assert(getPromisedTypeOfPromise(type) === undefined, "type provided should not be a non-generic 'promise'-like."); @@ -81370,10 +82412,24 @@ var ts; } // For a union, get a union of the awaited types of each constituent. if (type.flags & 1048576 /* TypeFlags.Union */) { + if (awaitedTypeStack.lastIndexOf(type.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } var mapper = errorNode ? function (constituentType) { return getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeNoAlias; - return typeAsAwaitable.awaitedTypeOfType = mapType(type, mapper); + awaitedTypeStack.push(type.id); + var mapped = mapType(type, mapper); + awaitedTypeStack.pop(); + return typeAsAwaitable.awaitedTypeOfType = mapped; } - var promisedType = getPromisedTypeOfPromise(type); + // If `type` is generic and should be wrapped in `Awaited`, return it. + if (isAwaitedTypeNeeded(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + var thisTypeForErrorOut = { value: undefined }; + var promisedType = getPromisedTypeOfPromise(type, /*errorNode*/ undefined, thisTypeForErrorOut); if (promisedType) { if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose @@ -81442,7 +82498,12 @@ var ts; if (isThenableType(type)) { if (errorNode) { ts.Debug.assertIsDefined(diagnosticMessage); - error(errorNode, diagnosticMessage, arg0); + var chain = void 0; + if (thisTypeForErrorOut.value) { + chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value)); + } + chain = ts.chainDiagnosticMessages(chain, diagnosticMessage, arg0); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, chain)); } return undefined; } @@ -81638,8 +82699,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { - var typeNode = types_22[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */ || typeNode.kind === 197 /* SyntaxKind.NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } @@ -81679,18 +82740,18 @@ var ts; } /** Check the decorators of a node */ function checkDecorators(node) { - if (!node.decorators) { - return; - } // skip this check for nodes that cannot have decorators. These should have already had an error reported by // checkGrammarDecorators. - if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node) || !node.modifiers || !ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning); } - var firstDecorator = node.decorators[0]; + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (!firstDecorator) { + return; + } checkExternalEmitHelpers(firstDecorator, 8 /* ExternalEmitHelpers.Decorate */); if (node.kind === 164 /* SyntaxKind.Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* ExternalEmitHelpers.Param */); @@ -81734,7 +82795,12 @@ var ts; break; } } - ts.forEach(node.decorators, checkDecorator); + for (var _f = 0, _g = node.modifiers; _f < _g.length; _f++) { + var modifier = _g[_f]; + if (ts.isDecorator(modifier)) { + checkDecorator(modifier); + } + } } function checkFunctionDeclaration(node) { addLazyDiagnostic(checkFunctionDeclarationDiagnostics); @@ -81765,6 +82831,11 @@ var ts; function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } + function checkJSDocLinkLikeTag(node) { + if (node.name) { + resolveJSDocMemberName(node.name, /*ignoreErrors*/ true); + } + } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); } @@ -82004,8 +83075,8 @@ var ts; return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); - for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { - var typeParameter = typeParameters_3[_i]; + for (var _i = 0, typeParameters_4 = typeParameters; _i < typeParameters_4.length; _i++) { + var typeParameter = typeParameters_4[_i]; if (!isTypeParameterUnused(typeParameter)) continue; var name = ts.idText(typeParameter.name); @@ -82165,6 +83236,22 @@ var ts; } }); } + function checkPotentialUncheckedRenamedBindingElementsInTypes() { + var _a; + for (var _i = 0, potentialUnusedRenamedBindingElementsInTypes_1 = potentialUnusedRenamedBindingElementsInTypes; _i < potentialUnusedRenamedBindingElementsInTypes_1.length; _i++) { + var node = potentialUnusedRenamedBindingElementsInTypes_1[_i]; + if (!((_a = getSymbolOfNode(node)) === null || _a === void 0 ? void 0 : _a.isReferenced)) { + var wrappingDeclaration = ts.walkUpBindingElementsAndPatterns(node); + ts.Debug.assert(ts.isParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here"); + var diagnostic = ts.createDiagnosticForNode(node.name, ts.Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, ts.declarationNameToString(node.name), ts.declarationNameToString(node.propertyName)); + if (!wrappingDeclaration.type) { + // entire parameter does not have type annotation, suggest adding an annotation + ts.addRelatedInfo(diagnostic, ts.createFileDiagnostic(ts.getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, ts.Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, ts.declarationNameToString(node.propertyName))); + } + diagnostics.add(diagnostic); + } + } + } function bindingNameText(name) { switch (name.kind) { case 79 /* SyntaxKind.Identifier */: @@ -82461,11 +83548,22 @@ var ts; // well known symbols. if (node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.name); - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkExpressionCached(node.initializer); } } if (ts.isBindingElement(node)) { + if (node.propertyName && + ts.isIdentifier(node.name) && + ts.isParameterDeclaration(node) && + ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + // type F = ({a: string}) => void; + // ^^^^^^ + // variable renaming in function type notation is confusing, + // so we forbid it even if noUnusedLocals is not enabled + potentialUnusedRenamedBindingElementsInTypes.push(node); + return; + } if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ScriptTarget.ES2018 */) { checkExternalEmitHelpers(node, 4 /* ExternalEmitHelpers.Rest */); } @@ -82498,14 +83596,14 @@ var ts; ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (ts.isParameter(node) && node.initializer && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; - var needCheckWidenedType = node.name.elements.length === 0; + var needCheckInitializer = ts.hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; + var needCheckWidenedType = !ts.some(node.name.elements, ts.not(ts.isOmittedExpression)); if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error var widenedType = getWidenedTypeForVariableLikeDeclaration(node); @@ -82532,7 +83630,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.kind === 203 /* SyntaxKind.BindingElement */ ? node.parent.parent : node)) { checkAliasSymbol(node); return; } @@ -82540,7 +83638,7 @@ var ts; if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - var initializer = ts.getEffectiveInitializer(node); + var initializer = ts.hasOnlyExpressionInitializer(node) && ts.getEffectiveInitializer(node); if (initializer) { var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && @@ -82565,7 +83663,7 @@ var ts; !(symbol.flags & 67108864 /* SymbolFlags.Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); } - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { @@ -82658,7 +83756,7 @@ var ts; return; var type = checkTruthinessExpression(location); var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) && isTypeAssertion(location.expression); - if (getFalsyFlags(type) || isPropertyExpressionCast) + if (!(getTypeFacts(type) & 4194304 /* TypeFacts.Truthy */) || isPropertyExpressionCast) return; // While it technically should be invalid for any known-truthy value // to be tested, we de-scope to functions and Promises unreferenced in @@ -83124,17 +84222,28 @@ var ts; * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. */ function getIterationTypesOfIterable(type, use, errorNode) { + var _a, _b; if (isTypeAny(type)) { return anyIterationTypes; } if (!(type.flags & 1048576 /* TypeFlags.Union */)) { - var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode); + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); if (iterationTypes_1 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } return undefined; } + else if ((_a = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _a === void 0 ? void 0 : _a.length) { + for (var _i = 0, _c = errorOutputContainer.errors; _i < _c.length; _i++) { + var diag = _c[_i]; + diagnostics.add(diag); + } + } return iterationTypes_1; } var cacheKey = use & 2 /* IterationUse.AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; @@ -83142,19 +84251,27 @@ var ts; if (cachedTypes) return cachedTypes === noIterationTypes ? undefined : cachedTypes; var allIterationTypes; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituent = _a[_i]; - var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode); + for (var _d = 0, _e = type.types; _d < _e.length; _d++) { + var constituent = _e[_d]; + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer); if (iterationTypes_2 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } setCachedIterationTypes(type, cacheKey, noIterationTypes); return undefined; } - else { - allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); + else if ((_b = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _b === void 0 ? void 0 : _b.length) { + for (var _f = 0, _g = errorOutputContainer.errors; _f < _g.length; _f++) { + var diag = _g[_f]; + diagnostics.add(diag); + } } + allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); } var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes; setCachedIterationTypes(type, cacheKey, iterationTypes); @@ -83182,47 +84299,62 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableWorker(type, use, errorNode) { + function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) { if (isTypeAny(type)) { return anyIterationTypes; } + // If we are reporting errors and encounter a cached `noIterationTypes`, we should ignore the cached value and continue as if nothing was cached. + // In addition, we should not cache any new results for this call. + var noCache = false; if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver); if (iterationTypes) { - return use & 8 /* IterationUse.ForOfFlag */ ? - getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : - iterationTypes; + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; + } + else { + return use & 8 /* IterationUse.ForOfFlag */ ? + getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : + iterationTypes; + } } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver); if (iterationTypes) { - if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - // for a sync iterable in an async context, only use the cached types if they are valid. - if (iterationTypes !== noIterationTypes) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode)); - } + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; } else { - return iterationTypes; + if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { + // for a sync iterable in an async context, only use the cached types if they are valid. + if (iterationTypes !== noIterationTypes) { + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); + } + } + else { + return iterationTypes; + } } } } if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { return iterationTypes; } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes - ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) - : noIterationTypes); + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); } else { return iterationTypes; @@ -83243,7 +84375,7 @@ var ts; } function getIterationTypesOfGlobalIterableType(globalType, resolver) { var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || - getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; } /** @@ -83297,26 +84429,26 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableSlow(type, resolver, errorNode) { + function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var _a; var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* SymbolFlags.Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); + return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); } var signatures = methodType ? getSignaturesOfType(methodType, 0 /* SignatureKind.Call */) : undefined; if (!ts.some(signatures)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); + return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); } var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature)); - var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes; - return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); + var iterationTypes = (_a = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache)) !== null && _a !== void 0 ? _a : noIterationTypes; + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { 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; - errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. @@ -83324,13 +84456,29 @@ var ts; * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, `undefined` is returned. */ - function getIterationTypesOfIterator(type, resolver, errorNode) { + function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { + return getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, /*noCache*/ false); + } + /** + * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. + * + * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` + * record is returned. Otherwise, `undefined` is returned. + * + * NOTE: You probably don't want to call this directly and should be calling + * `getIterationTypesOfIterator` instead. + */ + function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) { if (isTypeAny(type)) { return anyIterationTypes; } var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || - getIterationTypesOfIteratorFast(type, resolver) || - getIterationTypesOfIteratorSlow(type, resolver, errorNode); + getIterationTypesOfIteratorFast(type, resolver); + if (iterationTypes === noIterationTypes && errorNode) { + iterationTypes = undefined; + noCache = true; + } + iterationTypes !== null && iterationTypes !== void 0 ? iterationTypes : (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache)); return iterationTypes === noIterationTypes ? undefined : iterationTypes; } /** @@ -83368,7 +84516,7 @@ var ts; // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any` // and `undefined` in our libs by default, a custom lib *could* use different definitions. var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || - getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType; return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } @@ -83438,8 +84586,8 @@ var ts; * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, we return `undefined`. */ - function getIterationTypesOfMethod(type, resolver, methodName, errorNode) { - var _a, _b, _c, _d; + function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) { + var _a, _b, _c, _d, _e, _f; var method = getPropertyOfType(type, methodName); // Ignore 'return' or 'throw' if they are missing. if (!method && methodName !== "next") { @@ -83459,9 +84607,15 @@ var ts; var diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic; - error(errorNode, diagnostic, methodName); + if (errorOutputContainer) { + (_a = errorOutputContainer.errors) !== null && _a !== void 0 ? _a : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, diagnostic, methodName)); + } + else { + error(errorNode, diagnostic, methodName); + } } - return methodName === "next" ? anyIterationTypes : undefined; + return methodName === "next" ? noIterationTypes : undefined; } // If the method signature comes exclusively from the global iterator or generator type, // create iteration types from its type arguments like `getIterationTypesOfIteratorFast` @@ -83473,8 +84627,8 @@ var ts; if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) { var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false); var globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false); - var isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) === null || _a === void 0 ? void 0 : _a.members) === null || _b === void 0 ? void 0 : _b.get(methodName)) === methodType.symbol; - var isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) === null || _c === void 0 ? void 0 : _c.members) === null || _d === void 0 ? void 0 : _d.get(methodName)) === methodType.symbol; + var isGeneratorMethod = ((_c = (_b = globalGeneratorType.symbol) === null || _b === void 0 ? void 0 : _b.members) === null || _c === void 0 ? void 0 : _c.get(methodName)) === methodType.symbol; + var isIteratorMethod = !isGeneratorMethod && ((_e = (_d = globalIteratorType.symbol) === null || _d === void 0 ? void 0 : _d.members) === null || _e === void 0 ? void 0 : _e.get(methodName)) === methodType.symbol; if (isGeneratorMethod || isIteratorMethod) { var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType; var mapper = methodType.mapper; @@ -83514,7 +84668,13 @@ var ts; var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType); if (iterationTypes === noIterationTypes) { if (errorNode) { - error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + if (errorOutputContainer) { + (_f = errorOutputContainer.errors) !== null && _f !== void 0 ? _f : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName)); + } + else { + error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + } } yieldType = anyType; returnTypes = ts.append(returnTypes, anyType); @@ -83535,13 +84695,13 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterator` instead. */ - function getIterationTypesOfIteratorSlow(type, resolver, errorNode) { + function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var iterationTypes = combineIterationTypes([ - getIterationTypesOfMethod(type, resolver, "next", errorNode), - getIterationTypesOfMethod(type, resolver, "return", errorNode), - getIterationTypesOfMethod(type, resolver, "throw", errorNode), + getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer), ]); - return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); } /** * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like, @@ -83562,7 +84722,7 @@ var ts; var use = isAsyncGenerator ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) || - getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined); } function checkBreakOrContinueStatement(node) { // Grammar checking @@ -83573,9 +84733,14 @@ var ts; function unwrapReturnType(returnType, functionFlags) { var isGenerator = !!(functionFlags & 1 /* FunctionFlags.Generator */); var isAsync = !!(functionFlags & 2 /* FunctionFlags.Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync) || errorType : - isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : - returnType; + if (isGenerator) { + var returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync); + if (!returnIterationType) { + return errorType; + } + return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType; + } + return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func)); @@ -83795,9 +84960,10 @@ var ts; } var indexInfos = getApplicableIndexInfos(type, propNameType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; - var localPropDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || - name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ || getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_28 = function (info) { + var propDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || + name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; + var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; + 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 @@ -83805,12 +84971,16 @@ var ts; var errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !ts.some(getBaseTypes(type), function (base) { return !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType); }) ? interfaceDeclaration : undefined); if (errorNode && !isTypeAssignableTo(propType, info.type)) { - error(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + var diagnostic = createError(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + if (propDeclaration && errorNode !== propDeclaration) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(propDeclaration, ts.Diagnostics._0_is_declared_here, symbolToString(prop))); + } + diagnostics.add(diagnostic); } }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_28(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -83818,7 +84988,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_29 = 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; @@ -83833,7 +85003,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_29(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -84022,8 +85192,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { - grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (firstDecorator && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(firstDecorator, ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -84152,7 +85323,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_30 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -84169,7 +85340,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_30(member); + _loop_32(member); } } /** @@ -84257,7 +85428,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_31 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -84276,7 +85447,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_31(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -84344,18 +85515,17 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. - var _a, _b; + var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { - continue; + return "continue"; } var baseSymbol = getPropertyOfObjectType(type, base.escapedName); if (!baseSymbol) { - continue; + return "continue"; } var derived = getTargetSymbol(baseSymbol); var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); @@ -84373,14 +85543,14 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { - var otherBaseType = _d[_c]; + for (var _e = 0, _f = getBaseTypes(type); _e < _f.length; _e++) { + var otherBaseType = _f[_e]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1); if (derivedElsewhere && derivedElsewhere !== base) { - continue basePropertyCheck; + return "continue-basePropertyCheck"; } } if (derivedClassDecl.kind === 226 /* SyntaxKind.ClassExpression */) { @@ -84395,20 +85565,19 @@ var ts; // derived overrides base. var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* ModifierFlags.Private */ || derivedDeclarationFlags & 8 /* ModifierFlags.Private */) { - // either base or derived property is private - not override, skip it - continue; + return "continue"; } var errorMessage = void 0; var basePropertyFlags = base.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; var derivedPropertyFlags = derived.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor - if (baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */ + if ((ts.getCheckFlags(base) & 6 /* CheckFlags.Synthetic */ + ? (_a = base.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); }) + : (_b = base.declarations) === null || _b === void 0 ? void 0 : _b.every(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); })) + || ts.getCheckFlags(base) & 262144 /* CheckFlags.Mapped */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { - // when the base property is abstract or from an interface, base/derived flags don't need to match - // same when the derived property is from an assignment - continue; + return "continue"; } var overriddenInstanceProperty = basePropertyFlags !== 4 /* SymbolFlags.Property */ && derivedPropertyFlags === 4 /* SymbolFlags.Property */; var overriddenInstanceAccessor = basePropertyFlags === 4 /* SymbolFlags.Property */ && derivedPropertyFlags !== 4 /* SymbolFlags.Property */; @@ -84419,12 +85588,12 @@ var ts; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { - var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); + var uninitialized = (_c = derived.declarations) === null || _c === void 0 ? void 0 : _c.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* SymbolFlags.Transient */) && !(baseDeclarationFlags & 128 /* ModifierFlags.Abstract */) && !(derivedDeclarationFlags & 128 /* ModifierFlags.Abstract */) - && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { + && !((_d = derived.declarations) === null || _d === void 0 ? void 0 : _d.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -84437,13 +85606,11 @@ var ts; } } } - // correct case - continue; + return "continue"; } else if (isPrototypeProperty(base)) { if (isPrototypeProperty(derived) || derived.flags & 4 /* SymbolFlags.Property */) { - // method is overridden with method or property -- correct case - continue; + return "continue"; } else { ts.Debug.assert(!!(derived.flags & 98304 /* SymbolFlags.Accessor */)); @@ -84458,9 +85625,20 @@ var ts; } error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } + }; + basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var state_10 = _loop_34(baseProperty); + switch (state_10) { + case "continue-basePropertyCheck": continue basePropertyCheck; + } } } - function getNonInterhitedProperties(type, baseTypes, properties) { + function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { + return baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && (!ts.isPropertyDeclaration(declaration) || !declaration.initializer) + || ts.isInterfaceDeclaration(declaration.parent); + } + function getNonInheritedProperties(type, baseTypes, properties) { if (!ts.length(baseTypes)) { return properties; } @@ -84529,7 +85707,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName) || ts.isComputedPropertyName(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || containsUndefinedType(type))) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -84554,7 +85732,7 @@ var ts; ts.setParent(reference, staticBlock); reference.flowNode = staticBlock.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - if (!(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */)) { + if (!containsUndefinedType(flowType)) { return true; } } @@ -84569,7 +85747,7 @@ var ts; ts.setParent(reference, constructor); reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */); + return !containsUndefinedType(flowType); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -85085,6 +86263,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a, _b, _c, _d, _e; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -85095,6 +86274,31 @@ var ts; // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). symbol = getMergedSymbol(symbol.exportSymbol || symbol); + // A type-only import/export will already have a grammar error in a JS file, so no need to issue more errors within + if (ts.isInJSFile(node) && !(target.flags & 111551 /* SymbolFlags.Value */) && !ts.isTypeOnlyImportOrExportDeclaration(node)) { + var errorNode = ts.isImportOrExportSpecifier(node) ? node.propertyName || node.name : + ts.isNamedDeclaration(node) ? node.name : + node; + ts.Debug.assert(node.kind !== 274 /* SyntaxKind.NamespaceExport */); + if (node.kind === 275 /* SyntaxKind.ExportSpecifier */) { + var diag = error(errorNode, ts.Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); + var alreadyExportedSymbol = (_b = (_a = ts.getSourceFileOfNode(node).symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.get((node.propertyName || node.name).escapedText); + if (alreadyExportedSymbol === target) { + var exportingDeclaration = (_c = alreadyExportedSymbol.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isJSDocNode); + if (exportingDeclaration) { + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(exportingDeclaration, ts.Diagnostics._0_is_automatically_exported_here, ts.unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName))); + } + } + } + else { + ts.Debug.assert(node.kind !== 254 /* SyntaxKind.VariableDeclaration */); + var importDeclaration = ts.findAncestor(node, ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration)); + var moduleSpecifier = (_e = (importDeclaration && ((_d = ts.tryGetModuleSpecifierFromDeclaration(importDeclaration)) === null || _d === void 0 ? void 0 : _d.text))) !== null && _e !== void 0 ? _e : "..."; + var importedIdentifier = ts.unescapeLeadingUnderscores(ts.isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); + error(errorNode, ts.Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, "import(\"".concat(moduleSpecifier, "\").").concat(importedIdentifier)); + } + return; + } 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); @@ -85200,10 +86404,10 @@ var ts; var override = ts.getResolutionModeOverrideForClause(declaration.assertClause, validForTypeAssertions ? grammarErrorOnNode : undefined); if (validForTypeAssertions && override) { if (!ts.isNightly()) { - grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } return; // Other grammar checks do not apply to type-only imports with resolution mode assertions } @@ -85410,7 +86614,9 @@ var ts; error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { - markExportAsReferenced(node); + if (!node.isTypeOnly && !node.parent.parent.isTypeOnly) { + markExportAsReferenced(node); + } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); @@ -85552,12 +86758,16 @@ var ts; } } function checkSourceElementWorker(node) { - if (ts.isInJSFile(node)) { - ts.forEach(node.jsDoc, function (_a) { - var tags = _a.tags; - return ts.forEach(tags, checkSourceElement); + ts.forEach(node.jsDoc, function (_a) { + var comment = _a.comment, tags = _a.tags; + checkJSDocCommentWorker(comment); + ts.forEach(tags, function (tag) { + checkJSDocCommentWorker(tag.comment); + if (ts.isInJSFile(node)) { + checkSourceElement(tag); + } }); - } + }); var kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessively @@ -85643,6 +86853,10 @@ var ts; return checkJSDocTemplateTag(node); case 343 /* SyntaxKind.JSDocTypeTag */: return checkJSDocTypeTag(node); + case 324 /* SyntaxKind.JSDocLink */: + case 325 /* SyntaxKind.JSDocLinkCode */: + case 326 /* SyntaxKind.JSDocLinkPlain */: + return checkJSDocLinkLikeTag(node); case 340 /* SyntaxKind.JSDocParameterTag */: return checkJSDocParameterTag(node); case 347 /* SyntaxKind.JSDocPropertyTag */: @@ -85737,6 +86951,15 @@ var ts; return checkMissingDeclaration(node); } } + function checkJSDocCommentWorker(node) { + if (ts.isArray(node)) { + ts.forEach(node, function (tag) { + if (ts.isJSDocLinkLike(tag)) { + checkSourceElement(tag); + } + }); + } + } function checkJSDocTypeIsInJsFile(node) { if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); @@ -85904,6 +87127,7 @@ var ts; ts.clear(potentialNewTargetCollisions); ts.clear(potentialWeakMapSetCollisions); ts.clear(potentialReflectCollisions); + ts.clear(potentialUnusedRenamedBindingElementsInTypes); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -85919,6 +87143,9 @@ var ts; } }); } + if (!node.isDeclarationFile) { + checkPotentialUncheckedRenamedBindingElementsInTypes(); + } }); if (compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ && !node.isDeclarationFile && @@ -86292,7 +87519,7 @@ var ts; if (!result && isJSDoc_1) { var container = ts.findAncestor(name, ts.or(ts.isClassLike, ts.isInterfaceDeclaration)); if (container) { - return resolveJSDocMemberName(name, getSymbolOfNode(container)); + return resolveJSDocMemberName(name, /*ignoreErrors*/ false, getSymbolOfNode(container)); } } return result; @@ -86338,11 +87565,11 @@ var ts; * * For unqualified names, a container K may be provided as a second argument. */ - function resolveJSDocMemberName(name, container) { + function resolveJSDocMemberName(name, ignoreErrors, container) { if (ts.isEntityName(name)) { // resolve static values first var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */ | 111551 /* SymbolFlags.Value */; - var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, ignoreErrors, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); if (!symbol && ts.isIdentifier(name) && container) { symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning)); } @@ -86350,7 +87577,7 @@ var ts; return symbol; } } - var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left); + var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container); var right = ts.isIdentifier(name) ? name.escapedText : name.right.escapedText; if (left) { var proto = left.flags & 111551 /* SymbolFlags.Value */ && getPropertyOfType(getTypeOfSymbol(left), "prototype"); @@ -87341,13 +88568,20 @@ var ts; if (!fileToDirective) { return undefined; } + // computed property name should use node as value // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; - if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + var meaning; + if (node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) { meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; } + else { + meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; + if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; + } + } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -87631,7 +88865,10 @@ var ts; return checkGrammarDecorators(node) || checkGrammarModifiers(node); } function checkGrammarDecorators(node) { - if (!node.decorators) { + if (ts.canHaveIllegalDecorators(node) && ts.some(node.illegalDecorators)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node)) { return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { @@ -87644,7 +88881,7 @@ var ts; } else if (node.kind === 172 /* SyntaxKind.GetAccessor */ || node.kind === 173 /* SyntaxKind.SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + if (ts.hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } } @@ -87659,6 +88896,8 @@ var ts; var flags = 0 /* ModifierFlags.None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; if (modifier.kind !== 145 /* SyntaxKind.ReadonlyKeyword */) { if (node.kind === 166 /* SyntaxKind.PropertySignature */ || node.kind === 168 /* SyntaxKind.MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); @@ -87944,6 +89183,13 @@ var ts; case 164 /* SyntaxKind.Parameter */: case 163 /* SyntaxKind.TypeParameter */: return false; + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 179 /* SyntaxKind.FunctionType */: + case 276 /* SyntaxKind.MissingDeclaration */: + return true; default: if (node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 305 /* SyntaxKind.SourceFile */) { return false; @@ -87954,20 +89200,26 @@ var ts; case 257 /* SyntaxKind.ClassDeclaration */: case 180 /* SyntaxKind.ConstructorType */: return nodeHasAnyModifiersExcept(node, 126 /* SyntaxKind.AbstractKeyword */); + case 226 /* SyntaxKind.ClassExpression */: case 258 /* SyntaxKind.InterfaceDeclaration */: case 237 /* SyntaxKind.VariableStatement */: case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: return true; case 260 /* SyntaxKind.EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 85 /* SyntaxKind.ConstKeyword */); default: - ts.Debug.fail(); + ts.Debug.assertNever(node); } } } function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; + return modifier.kind !== allowedModifier; + } + return false; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { @@ -88259,14 +89511,20 @@ var ts; grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration - if (prop.modifiers) { + if (ts.canHaveModifiers(prop) && prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */) { + if (ts.isModifier(mod) && (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */)) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } + else if (ts.canHaveIllegalModifiers(prop) && prop.modifiers) { + for (var _d = 0, _e = prop.modifiers; _d < _e.length; _d++) { + var mod = _e[_d]; + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and @@ -88278,10 +89536,9 @@ var ts; var currentKind = void 0; switch (prop.kind) { case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); - // falls through case 296 /* SyntaxKind.PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* SyntaxKind.NumericLiteral */) { checkGrammarNumericLiteral(name); @@ -88720,9 +89977,6 @@ var ts; else { return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (!isConstOrReadonly || isInvalidInitializer) { - return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } } } function checkGrammarVariableDeclaration(node) { @@ -88889,7 +90143,7 @@ var ts; } } function checkGrammarConstructorTypeAnnotation(node) { - var type = ts.getEffectiveReturnTypeNode(node); + var type = node.type || ts.getEffectiveReturnTypeNode(node); if (type) { return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } @@ -88913,6 +90167,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Interfaces cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } @@ -88921,6 +90177,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Type literals cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } @@ -89295,7 +90553,6 @@ var ts; if (nodes === undefined || visitor === undefined) { return nodes; } - var updated; // Ensure start and count have valid values var length = nodes.length; if (start === undefined || start < 0) { @@ -89308,12 +90565,49 @@ var ts; var pos = -1; var end = -1; if (start > 0 || count < length) { - // If we are not visiting all of the original nodes, we must always create a new array. // Since this is a fragment of a node array, we do not copy over the previous location // and will only copy over `hasTrailingComma` if we are including the last element. - updated = []; hasTrailingComma = nodes.hasTrailingComma && start + count === length; } + else { + pos = nodes.pos; + end = nodes.end; + hasTrailingComma = nodes.hasTrailingComma; + } + var updated = visitArrayWorker(nodes, visitor, test, start, count); + if (updated !== nodes) { + // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. + var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); + ts.setTextRangePosEnd(updatedArray, pos, end); + return updatedArray; + } + return nodes; + } + ts.visitNodes = visitNodes; + /* @internal */ + function visitArray(nodes, visitor, test, start, count) { + if (nodes === undefined) { + return nodes; + } + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + return visitArrayWorker(nodes, visitor, test, start, count); + } + ts.visitArray = visitArray; + /* @internal */ + function visitArrayWorker(nodes, visitor, test, start, count) { + var updated; + var length = nodes.length; + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + updated = []; + } // Visit each original node. for (var i = 0; i < count; i++) { var node = nodes[i + start]; @@ -89322,9 +90616,6 @@ var ts; if (updated === undefined) { // Ensure we have a copy of `nodes`, up to the current index. updated = nodes.slice(0, i); - hasTrailingComma = nodes.hasTrailingComma; - pos = nodes.pos; - end = nodes.end; } if (visited) { if (ts.isArray(visited)) { @@ -89341,15 +90632,8 @@ var ts; } } } - if (updated) { - // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. - var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); - ts.setTextRangePosEnd(updatedArray, pos, end); - return updatedArray; - } - return nodes; + return updated !== null && updated !== void 0 ? updated : nodes; } - ts.visitNodes = visitNodes; /** * Starts a new lexical environment and visits a statement list, ending the lexical environment * and merging hoisted declarations upon completion. @@ -89421,7 +90705,7 @@ var ts; /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) : factory.getGeneratedNameForNode(parameter)), ]))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, /*initializer*/ undefined); } function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { @@ -89429,7 +90713,7 @@ var ts; context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([ factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(ts.setEmitFlags(factory.cloneNode(name), 48 /* EmitFlags.NoSourceMap */), ts.setEmitFlags(initializer, 48 /* EmitFlags.NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* EmitFlags.NoComments */)), parameter), 1536 /* EmitFlags.NoComments */)) ]), parameter), 1 /* EmitFlags.SingleLine */ | 32 /* EmitFlags.NoTrailingSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */ | 1536 /* EmitFlags.NoComments */))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, /*initializer*/ undefined); } function visitFunctionBody(node, visitor, context, nodeVisitor) { @@ -89495,7 +90779,7 @@ var ts; return factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); case 164 /* SyntaxKind.Parameter */: ts.Debug.type(node); - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + return factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 165 /* SyntaxKind.Decorator */: ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -89505,7 +90789,7 @@ var ts; return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 167 /* SyntaxKind.PropertyDeclaration */: ts.Debug.type(node); - return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), + return factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 168 /* SyntaxKind.MethodSignature */: @@ -89513,21 +90797,21 @@ var ts; return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 169 /* SyntaxKind.MethodDeclaration */: ts.Debug.type(node); - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 171 /* SyntaxKind.Constructor */: ts.Debug.type(node); - return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 172 /* SyntaxKind.GetAccessor */: ts.Debug.type(node); - return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 173 /* SyntaxKind.SetAccessor */: ts.Debug.type(node); - return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: ts.Debug.type(node); context.startLexicalEnvironment(); context.suspendLexicalEnvironment(); - return factory.updateClassStaticBlockDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 174 /* SyntaxKind.CallSignature */: ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -89536,7 +90820,7 @@ var ts; return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 176 /* SyntaxKind.IndexSignature */: ts.Debug.type(node); - return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types case 177 /* SyntaxKind.TypePredicate */: ts.Debug.type(node); @@ -89582,13 +90866,13 @@ var ts; return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); case 200 /* SyntaxKind.ImportType */: ts.Debug.type(node); - return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); case 295 /* SyntaxKind.ImportTypeAssertionContainer */: ts.Debug.type(node); return factory.updateImportTypeAssertionContainer(node, nodeVisitor(node.assertClause, visitor, ts.isNode), node.multiLine); case 197 /* SyntaxKind.NamedTupleMember */: ts.Debug.type(node); - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + return factory.updateNamedTupleMember(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 191 /* SyntaxKind.ParenthesizedType */: ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -89653,7 +90937,7 @@ var ts; return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 210 /* SyntaxKind.TaggedTemplateExpression */: ts.Debug.type(node); - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); case 211 /* SyntaxKind.TypeAssertionExpression */: ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -89701,7 +90985,7 @@ var ts; return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 226 /* SyntaxKind.ClassExpression */: ts.Debug.type(node); - return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 228 /* SyntaxKind.ExpressionWithTypeArguments */: ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); @@ -89782,22 +91066,22 @@ var ts; return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 256 /* SyntaxKind.FunctionDeclaration */: ts.Debug.type(node); - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 257 /* SyntaxKind.ClassDeclaration */: ts.Debug.type(node); - return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 258 /* SyntaxKind.InterfaceDeclaration */: ts.Debug.type(node); - return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + return factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 259 /* SyntaxKind.TypeAliasDeclaration */: ts.Debug.type(node); - return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 260 /* SyntaxKind.EnumDeclaration */: ts.Debug.type(node); - return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + return factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 261 /* SyntaxKind.ModuleDeclaration */: ts.Debug.type(node); - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + return factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); case 262 /* SyntaxKind.ModuleBlock */: ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); @@ -89809,10 +91093,10 @@ var ts; return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); case 265 /* SyntaxKind.ImportEqualsDeclaration */: ts.Debug.type(node); - return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); + return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); case 266 /* SyntaxKind.ImportDeclaration */: ts.Debug.type(node); - return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 293 /* SyntaxKind.AssertClause */: ts.Debug.type(node); return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); @@ -89836,10 +91120,10 @@ var ts; return factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); case 271 /* SyntaxKind.ExportAssignment */: ts.Debug.type(node); - return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); + return factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); case 272 /* SyntaxKind.ExportDeclaration */: ts.Debug.type(node); - return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 273 /* SyntaxKind.NamedExports */: ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); @@ -90932,6 +92216,126 @@ var ts; return !ts.isStatic(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); } ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; + if (decorators || ts.hasDecorators(parameter)) { + if (!decorators) { + decorators = new Array(numParameters); + } + decorators[i] = ts.getDecorators(parameter); + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfClass(node) { + var decorators = ts.getDecorators(node); + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + ts.getAllDecoratorsOfClass = getAllDecoratorsOfClass; + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param parent The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(member, parent) { + switch (member.kind) { + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: + return getAllDecoratorsOfAccessors(member, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 167 /* SyntaxKind.PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + ts.getAllDecoratorsOfClassElement = getAllDecoratorsOfClassElement; + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param parent The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(accessor, parent) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(parent.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = ts.hasDecorators(firstAccessor) ? firstAccessor : + secondAccessor && ts.hasDecorators(secondAccessor) ? secondAccessor : + undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = ts.getDecorators(firstAccessorWithDecorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters, + getDecorators: getAccessor && ts.getDecorators(getAccessor), + setDecorators: setAccessor && ts.getDecorators(setAccessor) + }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = ts.getDecorators(method); + var parameters = getDecoratorsOfParameters(method); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = ts.getDecorators(property); + if (!ts.some(decorators)) { + return undefined; + } + return { decorators: decorators }; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -91205,8 +92609,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */ - && !(element.transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -91272,7 +92676,7 @@ var ts; if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -91494,8 +92898,6 @@ var ts; var USE_NEW_TYPE_METADATA_FORMAT = false; var TypeScriptSubstitutionFlags; (function (TypeScriptSubstitutionFlags) { - /** Enables substitutions for decorated classes. */ - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; /** Enables substitutions for namespace exports. */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; /* Enables substitutions for unqualified enum members */ @@ -91521,9 +92923,9 @@ var ts; var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); - var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var typeSerializer = compilerOptions.emitDecoratorMetadata ? ts.createRuntimeTypeSerializer(context) : undefined; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -91538,7 +92940,6 @@ var ts; var currentNamespace; var currentNamespaceContainerName; var currentLexicalScope; - var currentNameScope; var currentScopeFirstDeclarationsOfName; var currentClassHasParameterProperties; /** @@ -91546,11 +92947,6 @@ var ts; * They are persisted between each SourceFile transformation and should not be reset. */ var enabledSubstitutions; - /** - * A map that keeps track of aliases created for classes with decorators to avoid issues - * with the double-binding behavior of classes. - */ - var classAliases; /** * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. @@ -91594,7 +92990,6 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentLexicalScope; - var savedCurrentNameScope = currentNameScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties; // Handle state changes before visiting a node. @@ -91605,7 +93000,6 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } currentLexicalScope = savedCurrentScope; - currentNameScope = savedCurrentNameScope; currentClassHasParameterProperties = savedCurrentClassHasParameterProperties; return visited; } @@ -91621,7 +93015,6 @@ var ts; case 262 /* SyntaxKind.ModuleBlock */: case 235 /* SyntaxKind.Block */: currentLexicalScope = node; - currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; case 257 /* SyntaxKind.ClassDeclaration */: @@ -91639,10 +93032,6 @@ var ts; // programs may also have an undefined name. ts.Debug.assert(node.kind === 257 /* SyntaxKind.ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)); } - if (ts.isClassDeclaration(node)) { - // XXX: should probably also cover interfaces and type aliases that can have type variables? - currentNameScope = node; - } break; } } @@ -91744,40 +93133,73 @@ var ts; return node; } /** - * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * Gets a specialized visitor that visits the immediate children of a class with TypeScript syntax. * - * @param node The node to visit. + * @param parent The class containing the elements to visit. */ - function classElementVisitor(node) { - return saveStateAndInvoke(node, classElementVisitorWorker); + function getClassElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return classElementVisitorWorker(n, parent); }); }; } /** * Specialized visitor that visits the immediate children of a class with TypeScript syntax. * * @param node The node to visit. */ - function classElementVisitorWorker(node) { + function classElementVisitorWorker(node, parent) { switch (node.kind) { case 171 /* SyntaxKind.Constructor */: return visitConstructor(node); case 167 /* SyntaxKind.PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. - return visitPropertyDeclaration(node); - case 176 /* SyntaxKind.IndexSignature */: + return visitPropertyDeclaration(node, parent); case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - // Fallback to the default visit behavior. - return visitorWorker(node); + return ts.visitEachChild(node, visitor, context); case 234 /* SyntaxKind.SemicolonClassElement */: return node; + case 176 /* SyntaxKind.IndexSignature */: + // Index signatures are elided + return; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function getObjectLiteralElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return objectLiteralElementVisitorWorker(n, parent); }); }; + } + function objectLiteralElementVisitorWorker(node, parent) { + switch (node.kind) { + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 298 /* SyntaxKind.SpreadAssignment */: + return visitor(node); + case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); + case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { + if (ts.isDecorator(node)) + return undefined; if (ts.modifierToFlag(node.kind) & 116958 /* ModifierFlags.TypeScriptModifier */) { return undefined; } @@ -91845,22 +93267,14 @@ var ts; // TypeScript type nodes are elided. // falls through case 176 /* SyntaxKind.IndexSignature */: - // TypeScript index signatures are elided. - // falls through - case 165 /* SyntaxKind.Decorator */: - // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + // TypeScript index signatures are elided. return undefined; case 259 /* SyntaxKind.TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return factory.createNotEmittedStatement(node); - case 167 /* SyntaxKind.PropertyDeclaration */: - // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects - return visitPropertyDeclaration(node); case 264 /* SyntaxKind.NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 171 /* SyntaxKind.Constructor */: - return visitConstructor(node); case 258 /* SyntaxKind.InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. @@ -91894,16 +93308,15 @@ var ts; case 228 /* SyntaxKind.ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); + case 205 /* SyntaxKind.ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 171 /* SyntaxKind.Constructor */: + case 167 /* SyntaxKind.PropertyDeclaration */: case 169 /* SyntaxKind.MethodDeclaration */: - // TypeScript method declarations may have decorators, modifiers - // or type annotations. - return visitMethodDeclaration(node); case 172 /* SyntaxKind.GetAccessor */: - // Get Accessors can have TypeScript modifiers, decorators, and type annotations. - return visitGetAccessor(node); case 173 /* SyntaxKind.SetAccessor */: - // Set Accessors can have TypeScript modifiers and type annotations. - return visitSetAccessor(node); + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + return ts.Debug.fail("Class and object literal elements must be visited with their respective visitors"); case 256 /* SyntaxKind.FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); @@ -91969,6 +93382,9 @@ var ts; !ts.isJsonSourceFile(node); return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } + function visitObjectLiteralExpression(node) { + return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, getObjectLiteralElementVisitor(node), ts.isObjectLiteralElement)); + } function getClassFacts(node, staticProperties) { var facts = 0 /* ClassFacts.None */; if (ts.some(staticProperties)) @@ -91991,17 +93407,18 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { - return ts.some(node.decorators) + return ts.hasDecorators(node) || ts.some(node.typeParameters) || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) || ts.some(node.members, hasTypeScriptClassSyntax); } function visitClassDeclaration(node) { if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */))) { - return ts.visitEachChild(node, visitor, context); + return factory.updateClassDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); var facts = getClassFacts(node, staticProperties); @@ -92009,14 +93426,25 @@ var ts; context.startLexicalEnvironment(); } var name = node.name || (facts & 5 /* ClassFacts.NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined); - var classStatement = facts & 2 /* ClassFacts.HasConstructorDecorators */ - ? createClassDeclarationHeadWithDecorators(node, name) - : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : ts.elideNodes(factory, node.modifiers); // preserve positions, if available + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var classStatement = factory.updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { + emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; + } + ts.setEmitFlags(classStatement, emitFlags); var statements = [classStatement]; - // Write any decorators of the node. - addClassElementDecorationStatements(statements, node, /*isStatic*/ false); - addClassElementDecorationStatements(statements, node, /*isStatic*/ true); - addConstructorDecorationStatement(statements, node); if (facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) { // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the // 'es2015' transformer can properly nest static initializers and decorators. The result @@ -92076,164 +93504,13 @@ var ts; } return ts.singleOrMany(statements); } - /** - * Transforms a non-decorated class declaration and appends the resulting statements. - * - * @param node A ClassDeclaration node. - * @param name The name of the class. - * @param facts Precomputed facts about the class. - */ - function createClassDeclarationHeadWithoutDecorators(node, name, facts) { - // ${modifiers} class ${name} ${heritageClauses} { - // ${members} - // } - // we do not emit modifiers on the declaration if we are emitting an IIFE - var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) - ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) - : undefined; - var classDeclaration = factory.createClassDeclaration( - /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - // To better align with the old emitter, we should not emit a trailing source map - // entry if the class has static properties. - var emitFlags = ts.getEmitFlags(node); - if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { - emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; - } - ts.setTextRange(classDeclaration, node); - ts.setOriginalNode(classDeclaration, node); - ts.setEmitFlags(classDeclaration, emitFlags); - return classDeclaration; - } - /** - * Transforms a decorated class declaration and appends the resulting statements. If - * the class requires an alias to avoid issues with double-binding, the alias is returned. - */ - function createClassDeclarationHeadWithDecorators(node, name) { - // When we emit an ES6 class that has a class decorator, we must tailor the - // emit to certain specific cases. - // - // In the simplest case, we emit the class declaration as a let declaration, and - // evaluate decorators after the close of the class body: - // - // [Example 1] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // class C { | } - // } | C = __decorate([dec], C); - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | } - // } | C = __decorate([dec], C); - // | export { C }; - // --------------------------------------------------------------------- - // - // If a class declaration contains a reference to itself *inside* of the class body, - // this introduces two bindings to the class: One outside of the class body, and one - // inside of the class body. If we apply decorators as in [Example 1] above, there - // is the possibility that the decorator `dec` will return a new value for the - // constructor, which would result in the binding inside of the class no longer - // pointing to the same reference as the binding outside of the class. - // - // As a result, we must instead rewrite all references to the class *inside* of the - // class body to instead point to a local temporary alias for the class: - // - // [Example 2] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = C_1 = class C { - // class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | var C_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export { C }; - // | var C_1; - // --------------------------------------------------------------------- - // - // If a class declaration is the default export of a module, we instead emit - // the export after the decorated declaration: - // - // [Example 3] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let default_1 = class { - // export default class { | } - // } | default_1 = __decorate([dec], default_1); - // | export default default_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | } - // } | C = __decorate([dec], C); - // | export default C; - // --------------------------------------------------------------------- - // - // If the class declaration is the default export and a reference to itself - // inside of the class body, we must emit both an alias for the class *and* - // move the export after the declaration: - // - // [Example 4] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export default C; - // | var C_1; - // --------------------------------------------------------------------- - // - var location = ts.moveRangePastDecorators(node); - var classAlias = getClassAliasIfNeeded(node); - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - // ... = class ${name} ${heritageClauses} { - // ${members} - // } - var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node); - var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, location); - // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference - // or decoratedClassAlias if the class contain self-reference. - var statement = factory.createVariableStatement( - /*modifiers*/ undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(declName, - /*exclamationToken*/ undefined, - /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) - ], 1 /* NodeFlags.Let */)); - ts.setOriginalNode(statement, node); - ts.setTextRange(statement, location); - ts.setCommentRange(statement, node); - return statement; - } function visitClassExpression(node) { - if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { - return ts.visitEachChild(node, visitor, context); - } - var classExpression = factory.createClassExpression( - /*decorators*/ undefined, - /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, node); - return classExpression; + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + return factory.updateClassExpression(node, decorators, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), isClassLikeDeclarationWithTypeScriptSyntax(node) ? + transformClassMembers(node) : + ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } /** * Transforms the members of a class. @@ -92250,7 +93527,6 @@ var ts; var parameter = parametersWithPropertyAssignments_1[_i]; if (ts.isIdentifier(parameter.name)) { members.push(ts.setOriginalNode(factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameter.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -92258,159 +93534,9 @@ var ts; } } } - ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + ts.addRange(members, ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - /** - * Gets either the static or instance members of a class that are decorated, or have - * parameters that are decorated. - * - * @param node The class containing the member. - * @param isStatic A value indicating whether to retrieve static or instance members of - * the class. - */ - function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); - } - /** - * Determines whether a class member is a static member of a class that is decorated, or - * has parameters that are decorated. - * - * @param member The class member. - */ - function isStaticDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ true, parent); - } - /** - * Determines whether a class member is an instance member of a class that is decorated, - * or has parameters that are decorated. - * - * @param member The class member. - */ - function isInstanceDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ false, parent); - } - /** - * Determines whether a class member is either a static or an instance member of a class - * that is decorated, or has parameters that are decorated. - * - * @param member The class member. - */ - function isDecoratedClassElement(member, isStaticElement, parent) { - return ts.nodeOrChildIsDecorated(member, parent) - && isStaticElement === ts.isStatic(member); - } - /** - * Gets an array of arrays of decorators for the parameters of a function-like node. - * The offset into the result array should correspond to the offset of the parameter. - * - * @param node The function-like node. - */ - function getDecoratorsOfParameters(node) { - var decorators; - if (node) { - var parameters = node.parameters; - var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); - var firstParameterOffset = firstParameterIsThis ? 1 : 0; - var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i + firstParameterOffset]; - if (decorators || parameter.decorators) { - if (!decorators) { - decorators = new Array(numParameters); - } - decorators[i] = parameter.decorators; - } - } - } - return decorators; - } - /** - * Gets an AllDecorators object containing the decorators for the class and the decorators for the - * parameters of the constructor of the class. - * - * @param node The class node. - */ - function getAllDecoratorsOfConstructor(node) { - var decorators = node.decorators; - var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); - if (!decorators && !parameters) { - return undefined; - } - return { - decorators: decorators, - parameters: parameters - }; - } - /** - * Gets an AllDecorators object containing the decorators for the member and its parameters. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function getAllDecoratorsOfClassElement(node, member) { - switch (member.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - return getAllDecoratorsOfAccessors(node, member); - case 169 /* SyntaxKind.MethodDeclaration */: - return getAllDecoratorsOfMethod(member); - case 167 /* SyntaxKind.PropertyDeclaration */: - return getAllDecoratorsOfProperty(member); - default: - return undefined; - } - } - /** - * Gets an AllDecorators object containing the decorators for the accessor and its parameters. - * - * @param node The class node that contains the accessor. - * @param accessor The class accessor member. - */ - function getAllDecoratorsOfAccessors(node, accessor) { - if (!accessor.body) { - return undefined; - } - var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; - if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { - return undefined; - } - var decorators = firstAccessorWithDecorators.decorators; - var parameters = getDecoratorsOfParameters(setAccessor); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the method and its parameters. - * - * @param method The class method member. - */ - function getAllDecoratorsOfMethod(method) { - if (!method.body) { - return undefined; - } - var decorators = method.decorators; - var parameters = getDecoratorsOfParameters(method); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the property. - * - * @param property The class property member. - */ - function getAllDecoratorsOfProperty(property) { - var decorators = property.decorators; - if (!decorators) { - return undefined; - } - return { decorators: decorators }; - } /** * Transforms all of the decorators for a declaration into an array of expressions. * @@ -92418,212 +93544,89 @@ var ts; * @param allDecorators An object containing all of the decorators for the declaration. */ function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + var _a, _b, _c, _d; if (!allDecorators) { return undefined; } - var decoratorExpressions = []; - ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); - ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, container, decoratorExpressions); - return decoratorExpressions; - } - /** - * Generates statements used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate statements for static or - * instance members. - */ - function addClassElementDecorationStatements(statements, node, isStatic) { - ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); - } - /** - * Generates expressions used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate expressions for static or - * instance members. - */ - function generateClassElementDecorationExpressions(node, isStatic) { - var members = getDecoratedClassElements(node, isStatic); - var expressions; - for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { - var member = members_8[_i]; - var expression = generateClassElementDecorationExpression(node, member); - if (expression) { - if (!expressions) { - expressions = [expression]; - } - else { - expressions.push(expression); - } - } - } - return expressions; - } - /** - * Generates an expression used to evaluate class element decorators at runtime. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function generateClassElementDecorationExpression(node, member) { - var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - // Emit the call to __decorate. Given the following: - // - // class C { - // @dec method(@dec2 x) {} - // @dec get accessor() {} - // @dec prop; - // } - // - // The emit for a method is: - // - // __decorate([ - // dec, - // __param(0, dec2), - // __metadata("design:type", Function), - // __metadata("design:paramtypes", [Object]), - // __metadata("design:returntype", void 0) - // ], C.prototype, "method", null); - // - // The emit for an accessor is: - // - // __decorate([ - // dec - // ], C.prototype, "accessor", null); - // - // The emit for a property is: - // - // __decorate([ - // dec - // ], C.prototype, "prop"); - // - var prefix = getClassMemberPrefix(node, member); - var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); - var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ - ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ - // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it - // should not invoke `Object.getOwnPropertyDescriptor`. - ? factory.createVoidZero() - // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. - // We have this extra argument here so that we can inject an explicit property descriptor at a later date. - : factory.createNull() - : undefined; - var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); - ts.setTextRange(helper, ts.moveRangePastDecorators(member)); - ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - return helper; - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function addConstructorDecorationStatement(statements, node) { - var expression = generateConstructorDecorationExpression(node); - if (expression) { - statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); - } - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function generateConstructorDecorationExpression(node) { - var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); - var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); - ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); - ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); - return expression; - } - /** - * Transforms a decorator into an expression. - * - * @param decorator The decorator node. - */ - function transformDecorator(decorator) { - return ts.visitNode(decorator.expression, visitor, ts.isExpression); + var decorators = ts.visitArray(allDecorators.decorators, visitor, ts.isDecorator); + var parameterDecorators = ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter); + var metadataDecorators = ts.some(decorators) || ts.some(parameterDecorators) ? getTypeMetadata(node, container) : undefined; + var result = factory.createNodeArray(ts.concatenate(ts.concatenate(decorators, parameterDecorators), metadataDecorators)); + var pos = (_b = (_a = ts.firstOrUndefined(allDecorators.decorators)) === null || _a === void 0 ? void 0 : _a.pos) !== null && _b !== void 0 ? _b : -1; + var end = (_d = (_c = ts.lastOrUndefined(allDecorators.decorators)) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : -1; + ts.setTextRangePosEnd(result, pos, end); + return result; } /** - * Transforms the decorators of a parameter. + * Transforms the decorators of a parameter into decorators of the class/method. * - * @param decorators The decorators for the parameter at the provided offset. + * @param parameterDecorators The decorators for the parameter at the provided offset. * @param parameterOffset The offset of the parameter. */ - function transformDecoratorsOfParameter(decorators, parameterOffset) { - var expressions; - if (decorators) { - expressions = []; - for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { - var decorator = decorators_1[_i]; - var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); - ts.setTextRange(helper, decorator.expression); + function transformDecoratorsOfParameter(parameterDecorators, parameterOffset) { + if (parameterDecorators) { + var decorators = []; + for (var _i = 0, parameterDecorators_1 = parameterDecorators; _i < parameterDecorators_1.length; _i++) { + var parameterDecorator = parameterDecorators_1[_i]; + var expression = ts.visitNode(parameterDecorator.expression, visitor, ts.isExpression); + var helper = emitHelpers().createParamHelper(expression, parameterOffset); + ts.setTextRange(helper, parameterDecorator.expression); ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - expressions.push(helper); + var decorator = factory.createDecorator(helper); + ts.setSourceMapRange(decorator, parameterDecorator.expression); + ts.setCommentRange(decorator, parameterDecorator.expression); + ts.setEmitFlags(decorator, 1536 /* EmitFlags.NoComments */); + decorators.push(decorator); } + return decorators; } - return expressions; } /** - * Adds optional type metadata for a declaration. + * Gets optional type metadata for a declaration. * * @param node The declaration node. - * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node, container, decoratorExpressions) { - if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, container, decoratorExpressions); - } - else { - addOldTypeMetadata(node, container, decoratorExpressions); - } + function getTypeMetadata(node, container) { + return USE_NEW_TYPE_METADATA_FORMAT ? + getNewTypeMetadata(node, container) : + getOldTypeMetadata(node, container); } - function addOldTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getOldTypeMetadata(node, container) { + if (typeSerializer) { + var decorators = void 0; if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node))); + var typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(typeMetadata)); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container))); + var paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container)); + decorators = ts.append(decorators, factory.createDecorator(paramTypesMetadata)); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node))); + var returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(returnTypeMetadata)); } + return decorators; } } - function addNewTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getNewTypeMetadata(node, container) { + if (typeSerializer) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + var typeProperty = factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, typeProperty); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + var paramTypeProperty = factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container))); + properties = ts.append(properties, paramTypeProperty); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + var returnTypeProperty = factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, returnTypeProperty); } if (properties) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true))); + var typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)); + return [factory.createDecorator(typeInfoMetadata)]; } } } @@ -92670,347 +93673,6 @@ var ts; } return false; } - function getAccessorTypeNode(node) { - var accessors = resolver.getAllAccessorDeclarations(node); - return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) - || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); - } - /** - * Serializes the type of a node for use with decorator type metadata. - * - * @param node The node that should have its type serialized. - */ - function serializeTypeOfNode(node) { - switch (node.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 164 /* SyntaxKind.Parameter */: - return serializeTypeNode(node.type); - case 173 /* SyntaxKind.SetAccessor */: - case 172 /* SyntaxKind.GetAccessor */: - return serializeTypeNode(getAccessorTypeNode(node)); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - return factory.createIdentifier("Function"); - default: - return factory.createVoidZero(); - } - } - /** - * Serializes the types of the parameters of a node for use with decorator type metadata. - * - * @param node The node that should have its parameter types serialized. - */ - function serializeParameterTypesOfNode(node, container) { - var valueDeclaration = ts.isClassLike(node) - ? ts.getFirstConstructorWithBody(node) - : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) - ? node - : undefined; - var expressions = []; - if (valueDeclaration) { - var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); - var numParameters = parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { - continue; - } - if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); - } - else { - expressions.push(serializeTypeOfNode(parameter)); - } - } - } - return factory.createArrayLiteralExpression(expressions); - } - function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { - var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; - if (setAccessor) { - return setAccessor.parameters; - } - } - return node.parameters; - } - /** - * Serializes the return type of a node for use with decorator type metadata. - * - * @param node The node that should have its return type serialized. - */ - function serializeReturnTypeOfNode(node) { - if (ts.isFunctionLike(node) && node.type) { - return serializeTypeNode(node.type); - } - else if (ts.isAsyncFunction(node)) { - return factory.createIdentifier("Promise"); - } - return factory.createVoidZero(); - } - /** - * Serializes a type node for use with decorator type metadata. - * - * Types are serialized in the following fashion: - * - Void types point to "undefined" (e.g. "void 0") - * - Function and Constructor types point to the global "Function" constructor. - * - Interface types with a call or construct signature types point to the global - * "Function" constructor. - * - Array and Tuple types point to the global "Array" constructor. - * - Type predicates and booleans point to the global "Boolean" constructor. - * - String literal types and strings point to the global "String" constructor. - * - Enum and number types point to the global "Number" constructor. - * - Symbol types point to the global "Symbol" constructor. - * - Type references to classes (or class-like variables) point to the constructor for the class. - * - Anything else points to the global "Object" constructor. - * - * @param node The type node to serialize. - */ - function serializeTypeNode(node) { - if (node === undefined) { - return factory.createIdentifier("Object"); - } - switch (node.kind) { - case 114 /* SyntaxKind.VoidKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - return factory.createVoidZero(); - case 191 /* SyntaxKind.ParenthesizedType */: - return serializeTypeNode(node.type); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - return factory.createIdentifier("Function"); - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: - return factory.createIdentifier("Array"); - case 177 /* SyntaxKind.TypePredicate */: - case 133 /* SyntaxKind.BooleanKeyword */: - return factory.createIdentifier("Boolean"); - case 198 /* SyntaxKind.TemplateLiteralType */: - case 150 /* SyntaxKind.StringKeyword */: - return factory.createIdentifier("String"); - case 148 /* SyntaxKind.ObjectKeyword */: - return factory.createIdentifier("Object"); - case 196 /* SyntaxKind.LiteralType */: - switch (node.literal.kind) { - case 10 /* SyntaxKind.StringLiteral */: - case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: - return factory.createIdentifier("String"); - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 8 /* SyntaxKind.NumericLiteral */: - return factory.createIdentifier("Number"); - case 9 /* SyntaxKind.BigIntLiteral */: - return getGlobalBigIntNameWithFallback(); - case 110 /* SyntaxKind.TrueKeyword */: - case 95 /* SyntaxKind.FalseKeyword */: - return factory.createIdentifier("Boolean"); - case 104 /* SyntaxKind.NullKeyword */: - return factory.createVoidZero(); - default: - return ts.Debug.failBadSyntaxKind(node.literal); - } - case 147 /* SyntaxKind.NumberKeyword */: - return factory.createIdentifier("Number"); - case 158 /* SyntaxKind.BigIntKeyword */: - return getGlobalBigIntNameWithFallback(); - case 151 /* SyntaxKind.SymbolKeyword */: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case 178 /* SyntaxKind.TypeReference */: - return serializeTypeReferenceNode(node); - case 188 /* SyntaxKind.IntersectionType */: - case 187 /* SyntaxKind.UnionType */: - return serializeTypeList(node.types); - case 189 /* SyntaxKind.ConditionalType */: - return serializeTypeList([node.trueType, node.falseType]); - case 193 /* SyntaxKind.TypeOperator */: - if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { - return serializeTypeNode(node.type); - } - break; - case 181 /* SyntaxKind.TypeQuery */: - case 194 /* SyntaxKind.IndexedAccessType */: - case 195 /* SyntaxKind.MappedType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 192 /* SyntaxKind.ThisType */: - case 200 /* SyntaxKind.ImportType */: - break; - // handle JSDoc types from an invalid parse - case 312 /* SyntaxKind.JSDocAllType */: - case 313 /* SyntaxKind.JSDocUnknownType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 318 /* SyntaxKind.JSDocVariadicType */: - case 319 /* SyntaxKind.JSDocNamepathType */: - break; - case 314 /* SyntaxKind.JSDocNullableType */: - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 316 /* SyntaxKind.JSDocOptionalType */: - return serializeTypeNode(node.type); - default: - return ts.Debug.failBadSyntaxKind(node); - } - return factory.createIdentifier("Object"); - } - function serializeTypeList(types) { - // Note when updating logic here also update getEntityNameForDecoratorMetadata - // so that aliases can be marked as referenced - var serializedUnion; - for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { - var typeNode = types_23[_i]; - while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 196 /* SyntaxKind.LiteralType */ && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */ || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { - // One of the individual is global object, return immediately - return serializedIndividual; - } - // If there exists union that is not void 0 expression, check if the the common type is identifier. - // anything more complex and we will just default to Object - else if (serializedUnion) { - // Different types - if (!ts.isIdentifier(serializedUnion) || - !ts.isIdentifier(serializedIndividual) || - serializedUnion.escapedText !== serializedIndividual.escapedText) { - return factory.createIdentifier("Object"); - } - } - else { - // Initialize the union type - serializedUnion = serializedIndividual; - } - } - // If we were able to find common type, use it - return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never - } - /** - * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with - * decorator type metadata. - * - * @param node The type reference node. - */ - function serializeTypeReferenceNode(node) { - var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); - switch (kind) { - case ts.TypeReferenceSerializationKind.Unknown: - // From conditional type type reference that cannot be resolved is Similar to any or unknown - if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { - return factory.createIdentifier("Object"); - } - var serialized = serializeEntityNameAsExpressionFallback(node.typeName); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), - /*questionToken*/ undefined, temp, - /*colonToken*/ undefined, factory.createIdentifier("Object")); - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName); - case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: - return factory.createVoidZero(); - case ts.TypeReferenceSerializationKind.BigIntLikeType: - return getGlobalBigIntNameWithFallback(); - case ts.TypeReferenceSerializationKind.BooleanType: - return factory.createIdentifier("Boolean"); - case ts.TypeReferenceSerializationKind.NumberLikeType: - return factory.createIdentifier("Number"); - case ts.TypeReferenceSerializationKind.StringLikeType: - return factory.createIdentifier("String"); - case ts.TypeReferenceSerializationKind.ArrayLikeType: - return factory.createIdentifier("Array"); - case ts.TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - return factory.createIdentifier("Function"); - case ts.TypeReferenceSerializationKind.Promise: - return factory.createIdentifier("Promise"); - case ts.TypeReferenceSerializationKind.ObjectType: - return factory.createIdentifier("Object"); - default: - return ts.Debug.assertNever(kind); - } - } - function createCheckedValue(left, right) { - return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right); - } - /** - * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 79 /* SyntaxKind.Identifier */) { - // A -> typeof A !== undefined && A - var copied = serializeEntityNameAsExpression(node); - return createCheckedValue(copied, copied); - } - if (node.left.kind === 79 /* SyntaxKind.Identifier */) { - // A.B -> typeof A !== undefined && A.B - return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); - } - // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C - var left = serializeEntityNameAsExpressionFallback(node.left); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right)); - } - /** - * Serializes an entity name as an expression for decorator type metadata. - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpression(node) { - switch (node.kind) { - case 79 /* SyntaxKind.Identifier */: - // Create a clone of the name with a new parent, and treat it as if it were - // a source tree node for the purposes of the checker. - var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); - name.original = undefined; - ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. - return name; - case 161 /* SyntaxKind.QualifiedName */: - return serializeQualifiedNameAsExpression(node); - } - } - /** - * Serializes an qualified name as an expression for decorator type metadata. - * - * @param node The qualified name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * qualified name at runtime. - */ - function serializeQualifiedNameAsExpression(node) { - return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); - } - /** - * Gets an expression that points to the global "Symbol" constructor at runtime if it is - * available. - */ - function getGlobalSymbolNameWithFallback() { - return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("Symbol"), - /*colonToken*/ undefined, factory.createIdentifier("Object")); - } - /** - * Gets an expression that points to the global "BigInt" constructor at runtime if it is - * available. - */ - function getGlobalBigIntNameWithFallback() { - return languageVersion < 99 /* ScriptTarget.ESNext */ - ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("BigInt"), - /*colonToken*/ undefined, factory.createIdentifier("Object")) - : factory.createIdentifier("BigInt"); - } /** * Gets an expression that represents a property name (for decorated properties or enums). * For a computed property, a name is generated for the node. @@ -93047,7 +93709,7 @@ var ts; // The names are used more than once when: // - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments). // - the property has a decorator. - if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) { + if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.hasDecorators(member))) { var expression = ts.visitNode(name.expression, visitor, ts.isExpression); var innerExpression = ts.skipPartiallyEmittedExpressions(expression); if (!ts.isSimpleInlineableExpression(innerExpression)) { @@ -93095,28 +93757,29 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } - function visitPropertyDeclaration(node) { - if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)) { + function visitPropertyDeclaration(node, parent) { + var isAmbient = node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */); + if (isAmbient && !ts.hasDecorators(node)) { return undefined; } - var updated = factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), + var allDecorators = ts.getAllDecoratorsOfClassElement(node, parent); + var decorators = transformAllDecoratorsOfDeclaration(node, parent, allDecorators); + // Preserve a `declare x` property with decorators to be handled by the decorators transform + if (isAmbient) { + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, factory.createModifiersFromModifierFlags(2 /* ModifierFlags.Ambient */)), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } return factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node)); } function transformConstructorBody(body, constructor) { @@ -93155,7 +93818,8 @@ var ts; statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, prologueStatementCount), true), parameterPropertyAssignments, true), statements.slice(prologueStatementCount), true); } // Add remaining statements from the body, skipping the super() call if it was found and any (already added) prologue statements - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, superStatementIndex + 1 + prologueStatementCount)); + var start = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, start)); // End the lexical environment. statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true); @@ -93181,22 +93845,19 @@ var ts; ts.setEmitFlags(localName, 1536 /* EmitFlags.NoComments */); return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(factory.createExpressionStatement(factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1)))); } - function visitMethodDeclaration(node) { + function visitMethodDeclaration(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + var allDecorators = ts.isClassLike(parent) ? ts.getAllDecoratorsOfClassElement(node, parent) : undefined; + var decorators = ts.isClassLike(parent) ? transformAllDecoratorsOfDeclaration(node, parent, allDecorators) : undefined; + return factory.updateMethodDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), node.asteriskToken, visitPropertyNameOfClassElement(node), /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } /** * Determines whether to emit an accessor declaration. We should not emit the @@ -93207,41 +93868,36 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)); } - function visitGetAccessor(node) { + function visitGetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateGetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } - function visitSetAccessor(node) { + function visitSetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateSetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return factory.createNotEmittedStatement(node); } - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + var updated = factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); if (isExportOfNamespace(node)) { @@ -93270,9 +93926,8 @@ var ts; if (ts.parameterIsThisKeyword(node)) { return undefined; } - var updated = factory.updateParameterDeclaration(node, - /*decorators*/ undefined, - /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), // preserve positions, if available + node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); if (updated !== node) { @@ -93432,7 +94087,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); @@ -93662,7 +94317,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); @@ -93775,7 +94430,6 @@ var ts; compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ ? factory.updateImportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, importClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -93850,7 +94504,6 @@ var ts; var exportClause = ts.visitNode(node.exportClause, function (bindings) { return visitNamedExportBindings(bindings, allowEmpty); }, ts.isNamedExportBindings); return exportClause ? factory.updateExportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -93908,7 +94561,6 @@ var ts; // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'. if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */) { return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, node.moduleReference.expression, /*assertClause*/ undefined), node), node); @@ -93968,12 +94620,6 @@ var ts; return isExternalModuleExport(node) && ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */); } - /** - * Creates a statement for the provided expression. This is used in calls to `map`. - */ - function expressionToStatement(expression) { - return factory.createExpressionStatement(expression); - } function addExportMemberAssignment(statements, node) { var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); @@ -94005,44 +94651,12 @@ var ts; function getNamespaceContainerName(node) { return factory.getGeneratedNameForNode(node); } - /** - * Gets a local alias for a class declaration if it is a decorated class with an internal - * reference to the static side of the class. This is necessary to avoid issues with - * double-binding semantics for the class name. - */ - function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { - enableSubstitutionForClassAliases(); - var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - hoistVariableDeclaration(classAlias); - return classAlias; - } - } - function getClassPrototype(node) { - return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); - } - function getClassMemberPrefix(node, member) { - return ts.isStatic(member) - ? factory.getDeclarationName(node) - : getClassPrototype(node); - } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */; context.enableSubstitution(79 /* SyntaxKind.Identifier */); } } - function enableSubstitutionForClassAliases() { - if ((enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) === 0) { - enabledSubstitutions |= 1 /* TypeScriptSubstitutionFlags.ClassAliases */; - // We need to enable substitutions for identifiers. This allows us to - // substitute class names inside of a class declaration. - context.enableSubstitution(79 /* SyntaxKind.Identifier */); - // Keep track of class aliases. - classAliases = []; - } - } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2 /* TypeScriptSubstitutionFlags.NamespaceExports */) === 0) { enabledSubstitutions |= 2 /* TypeScriptSubstitutionFlags.NamespaceExports */; @@ -94127,32 +94741,9 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - return trySubstituteClassAlias(node) - || trySubstituteNamespaceExportedName(node) + return trySubstituteNamespaceExportedName(node) || node; } - function trySubstituteClassAlias(node) { - if (enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - // Also, when emitting statics for class expressions, we must substitute a class alias for - // constructor references in static property initializers. - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = classAliases[declaration.id]; // TODO: GH#18217 - if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; - } - } - } - } - return undefined; - } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { @@ -94290,7 +94881,7 @@ var ts; return visited; } function visitorWorker(node, valueIsDiscarded) { - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */) { + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */) { switch (node.kind) { case 226 /* SyntaxKind.ClassExpression */: case 257 /* SyntaxKind.ClassDeclaration */: @@ -94305,8 +94896,8 @@ var ts; return visitClassStaticBlockDeclaration(node); } } - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */ || - node.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */ && + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */ || + node.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */ && shouldTransformSuperInStaticInitializers && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { @@ -94446,7 +95037,7 @@ var ts; return node; } function visitMethodOrAccessorDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.isPrivateIdentifier(node.name)) { return ts.visitEachChild(node, classElementVisitor, context); } @@ -94458,7 +95049,7 @@ var ts; } var functionName = getHoistedFunctionName(node); if (functionName) { - getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return ts.isModifier(m) && !ts.isStaticModifier(m); }), node.asteriskToken, functionName, /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); } @@ -94482,7 +95073,7 @@ var ts; } } function visitPropertyDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (ts.isPrivateIdentifier(node.name)) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { if (ts.isStatic(node)) { @@ -94490,8 +95081,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + return factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); @@ -94513,9 +95103,7 @@ var ts; if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); if (initializerStatement) { - var staticBlock = factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([initializerStatement])); + var staticBlock = factory.createClassStaticBlockDeclaration(factory.createBlock([initializerStatement])); ts.setOriginalNode(staticBlock, node); ts.setCommentRange(staticBlock, node); // Set the comment range for the statement to an empty synthetic range @@ -94591,10 +95179,11 @@ var ts; } function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) { if (node.operator === 45 /* SyntaxKind.PlusPlusToken */ || node.operator === 46 /* SyntaxKind.MinusMinusToken */) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + var operand = ts.skipParentheses(node.operand); + if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(operand)) { var info = void 0; - if (info = accessPrivateIdentifier(node.operand.name)) { - var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression); + if (info = accessPrivateIdentifier(operand.name)) { + var receiver = ts.visitNode(operand.expression, visitor, ts.isExpression); var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; var expression = createPrivateIdentifierAccess(info, readExpression); var temp = ts.isPrefixUnaryExpression(node) || valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); @@ -94610,7 +95199,7 @@ var ts; } } else if (shouldTransformSuperInStaticInitializers && - ts.isSuperProperty(node.operand) && + ts.isSuperProperty(operand) && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { // converts `++super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = ++_a), _classTemp), _b)` @@ -94623,31 +95212,31 @@ var ts; // converts `super[f()]--` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = _b--), _classTemp), _c)` var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; if (facts & 1 /* ClassFacts.ClassWasDecorated */) { - var operand = visitInvalidSuperProperty(node.operand); + var expression = visitInvalidSuperProperty(operand); return ts.isPrefixUnaryExpression(node) ? - factory.updatePrefixUnaryExpression(node, operand) : - factory.updatePostfixUnaryExpression(node, operand); + factory.updatePrefixUnaryExpression(node, expression) : + factory.updatePostfixUnaryExpression(node, expression); } if (classConstructor && superClassReference) { var setterName = void 0; var getterName = void 0; - if (ts.isPropertyAccessExpression(node.operand)) { - if (ts.isIdentifier(node.operand.name)) { - getterName = setterName = factory.createStringLiteralFromNode(node.operand.name); + if (ts.isPropertyAccessExpression(operand)) { + if (ts.isIdentifier(operand.name)) { + getterName = setterName = factory.createStringLiteralFromNode(operand.name); } } else { - if (ts.isSimpleInlineableExpression(node.operand.argumentExpression)) { - getterName = setterName = node.operand.argumentExpression; + if (ts.isSimpleInlineableExpression(operand.argumentExpression)) { + getterName = setterName = operand.argumentExpression; } else { getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, ts.visitNode(node.operand.argumentExpression, visitor, ts.isExpression)); + setterName = factory.createAssignment(getterName, ts.visitNode(operand.argumentExpression, visitor, ts.isExpression)); } } if (setterName && getterName) { var expression = factory.createReflectGetCall(superClassReference, getterName, classConstructor); - ts.setTextRange(expression, node.operand); + ts.setTextRange(expression, operand); var temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); expression = ts.expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp); expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor); @@ -94880,13 +95469,13 @@ var ts; facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } if (ts.isPropertyDeclaration(member) || ts.isClassStaticBlockDeclaration(member)) { - if (shouldTransformThisInStaticInitializers && member.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */) { + if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */) { facts |= 8 /* ClassFacts.NeedsSubstitutionForThisInClassStaticField */; if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } } - if (shouldTransformSuperInStaticInitializers && member.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */) { + if (shouldTransformSuperInStaticInitializers && member.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */) { if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */ | 4 /* ClassFacts.NeedsClassSuperReference */; } @@ -94924,8 +95513,7 @@ var ts; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* SyntaxKind.NullKeyword */); var statements = [ - factory.updateClassDeclaration(node, - /*decorators*/ undefined, node.modifiers, node.name, + factory.updateClassDeclaration(node, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; if (pendingClassReferenceAssignment) { @@ -94977,7 +95565,7 @@ var ts; temp = createClassTempVar(); getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); } - var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, + var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || ts.isPrivateIdentifier(p.name); }); if (hasTransformableStatics || ts.some(pendingExpressions)) { @@ -95045,9 +95633,7 @@ var ts; members.push(constructor); } if (!shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(pendingExpressions)) { - members.push(factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([ + members.push(factory.createClassStaticBlockDeclaration(factory.createBlock([ factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)) ]))); pendingExpressions = undefined; @@ -95084,7 +95670,6 @@ var ts; return undefined; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { @@ -95471,10 +96056,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_3 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_3, node); - ts.setCommentRange(clone_3, node); - return clone_3; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -95836,6 +96421,1001 @@ var ts; })(ts || (ts = {})); /*@internal*/ var ts; +(function (ts) { + function createRuntimeTypeSerializer(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var currentLexicalScope; + var currentNameScope; + return { + serializeTypeNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeNode, node); }, + serializeTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeOfNode, node); }, + serializeParameterTypesOfNode: function (serializerContext, node, container) { return setSerializerContextAnd(serializerContext, serializeParameterTypesOfNode, node, container); }, + serializeReturnTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeReturnTypeOfNode, node); }, + }; + function setSerializerContextAnd(serializerContext, cb, node, arg) { + var savedCurrentLexicalScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + currentLexicalScope = serializerContext.currentLexicalScope; + currentNameScope = serializerContext.currentNameScope; + var result = arg === undefined ? cb(node) : cb(node, arg); + currentLexicalScope = savedCurrentLexicalScope; + currentNameScope = savedCurrentNameScope; + return result; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 167 /* SyntaxKind.PropertyDeclaration */: + case 164 /* SyntaxKind.Parameter */: + return serializeTypeNode(node.type); + case 173 /* SyntaxKind.SetAccessor */: + case 172 /* SyntaxKind.GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 169 /* SyntaxKind.MethodDeclaration */: + return ts.factory.createIdentifier("Function"); + default: + return ts.factory.createVoidZero(); + } + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.factory.createArrayLiteralExpression(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.factory.createIdentifier("Promise"); + } + return ts.factory.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.factory.createIdentifier("Object"); + } + node = ts.skipTypeParentheses(node); + switch (node.kind) { + case 114 /* SyntaxKind.VoidKeyword */: + case 153 /* SyntaxKind.UndefinedKeyword */: + case 143 /* SyntaxKind.NeverKeyword */: + return ts.factory.createVoidZero(); + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + return ts.factory.createIdentifier("Function"); + case 183 /* SyntaxKind.ArrayType */: + case 184 /* SyntaxKind.TupleType */: + return ts.factory.createIdentifier("Array"); + case 177 /* SyntaxKind.TypePredicate */: + return node.assertsModifier ? + ts.factory.createVoidZero() : + ts.factory.createIdentifier("Boolean"); + case 133 /* SyntaxKind.BooleanKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 198 /* SyntaxKind.TemplateLiteralType */: + case 150 /* SyntaxKind.StringKeyword */: + return ts.factory.createIdentifier("String"); + case 148 /* SyntaxKind.ObjectKeyword */: + return ts.factory.createIdentifier("Object"); + case 196 /* SyntaxKind.LiteralType */: + return serializeLiteralOfLiteralTypeNode(node.literal); + case 147 /* SyntaxKind.NumberKeyword */: + return ts.factory.createIdentifier("Number"); + case 158 /* SyntaxKind.BigIntKeyword */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 151 /* SyntaxKind.SymbolKeyword */: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case 178 /* SyntaxKind.TypeReference */: + return serializeTypeReferenceNode(node); + case 188 /* SyntaxKind.IntersectionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ true); + case 187 /* SyntaxKind.UnionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ false); + case 189 /* SyntaxKind.ConditionalType */: + return serializeUnionOrIntersectionConstituents([node.trueType, node.falseType], /*isIntersection*/ false); + case 193 /* SyntaxKind.TypeOperator */: + if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { + return serializeTypeNode(node.type); + } + break; + case 181 /* SyntaxKind.TypeQuery */: + case 194 /* SyntaxKind.IndexedAccessType */: + case 195 /* SyntaxKind.MappedType */: + case 182 /* SyntaxKind.TypeLiteral */: + case 130 /* SyntaxKind.AnyKeyword */: + case 155 /* SyntaxKind.UnknownKeyword */: + case 192 /* SyntaxKind.ThisType */: + case 200 /* SyntaxKind.ImportType */: + break; + // handle JSDoc types from an invalid parse + case 312 /* SyntaxKind.JSDocAllType */: + case 313 /* SyntaxKind.JSDocUnknownType */: + case 317 /* SyntaxKind.JSDocFunctionType */: + case 318 /* SyntaxKind.JSDocVariadicType */: + case 319 /* SyntaxKind.JSDocNamepathType */: + break; + case 314 /* SyntaxKind.JSDocNullableType */: + case 315 /* SyntaxKind.JSDocNonNullableType */: + case 316 /* SyntaxKind.JSDocOptionalType */: + return serializeTypeNode(node.type); + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.factory.createIdentifier("Object"); + } + function serializeLiteralOfLiteralTypeNode(node) { + switch (node.kind) { + case 10 /* SyntaxKind.StringLiteral */: + case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: + return ts.factory.createIdentifier("String"); + case 219 /* SyntaxKind.PrefixUnaryExpression */: { + var operand = node.operand; + switch (operand.kind) { + case 8 /* SyntaxKind.NumericLiteral */: + case 9 /* SyntaxKind.BigIntLiteral */: + return serializeLiteralOfLiteralTypeNode(operand); + default: + return ts.Debug.failBadSyntaxKind(operand); + } + } + case 8 /* SyntaxKind.NumericLiteral */: + return ts.factory.createIdentifier("Number"); + case 9 /* SyntaxKind.BigIntLiteral */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 110 /* SyntaxKind.TrueKeyword */: + case 95 /* SyntaxKind.FalseKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 104 /* SyntaxKind.NullKeyword */: + return ts.factory.createVoidZero(); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function serializeUnionOrIntersectionConstituents(types, isIntersection) { + // Note when updating logic here also update `getEntityNameForDecoratorMetadata` in checker.ts so that aliases can be marked as referenced + var serializedType; + for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { + var typeNode = types_22[_i]; + typeNode = ts.skipTypeParentheses(typeNode); + if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { + if (isIntersection) + return ts.factory.createVoidZero(); // Reduce to `never` in an intersection + continue; // Elide `never` in a union + } + if (typeNode.kind === 155 /* SyntaxKind.UnknownKeyword */) { + if (!isIntersection) + return ts.factory.createIdentifier("Object"); // Reduce to `unknown` in a union + continue; // Elide `unknown` in an intersection + } + if (typeNode.kind === 130 /* SyntaxKind.AnyKeyword */) { + return ts.factory.createIdentifier("Object"); // Reduce to `any` in a union or intersection + } + if (!strictNullChecks && ((ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */) || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedConstituent = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedConstituent; + } + // If there exists union that is not `void 0` expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + if (serializedType) { + // Different types + if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) { + return ts.factory.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedType = serializedConstituent; + } + } + // If we were able to find common type, use it + return serializedType !== null && serializedType !== void 0 ? serializedType : (ts.factory.createVoidZero()); // Fallback is only hit if all union constituents are null/undefined/never + } + function equateSerializedTypeNodes(left, right) { + return ( + // temp vars used in fallback + ts.isGeneratedIdentifier(left) ? ts.isGeneratedIdentifier(right) : + // entity names + ts.isIdentifier(left) ? ts.isIdentifier(right) + && left.escapedText === right.escapedText : + ts.isPropertyAccessExpression(left) ? ts.isPropertyAccessExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) + && equateSerializedTypeNodes(left.name, right.name) : + // `void 0` + ts.isVoidExpression(left) ? ts.isVoidExpression(right) + && ts.isNumericLiteral(left.expression) && left.expression.text === "0" + && ts.isNumericLiteral(right.expression) && right.expression.text === "0" : + // `"undefined"` or `"function"` in `typeof` checks + ts.isStringLiteral(left) ? ts.isStringLiteral(right) + && left.text === right.text : + // used in `typeof` checks for fallback + ts.isTypeOfExpression(left) ? ts.isTypeOfExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // parens in `typeof` checks with temps + ts.isParenthesizedExpression(left) ? ts.isParenthesizedExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // conditionals used in fallback + ts.isConditionalExpression(left) ? ts.isConditionalExpression(right) + && equateSerializedTypeNodes(left.condition, right.condition) + && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) + && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : + // logical binary and assignments used in fallback + ts.isBinaryExpression(left) ? ts.isBinaryExpression(right) + && left.operatorToken.kind === right.operatorToken.kind + && equateSerializedTypeNodes(left.left, right.left) + && equateSerializedTypeNodes(left.right, right.right) : + false); + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with decorator type metadata. + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope !== null && currentNameScope !== void 0 ? currentNameScope : currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.factory.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createAssignment(temp, serialized), "function"), + /*questionToken*/ undefined, temp, + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.factory.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.factory.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.factory.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.factory.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.factory.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.factory.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.factory.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.factory.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + /** + * Produces an expression that results in `right` if `left` is not undefined at runtime: + * + * ``` + * typeof left !== "undefined" && right + * ``` + * + * We use `typeof L !== "undefined"` (rather than `L !== undefined`) since `L` may not be declared. + * It's acceptable for this expression to result in `false` at runtime, as the result is intended to be + * further checked by any containing expression. + */ + function createCheckedValue(left, right) { + return ts.factory.createLogicalAnd(ts.factory.createStrictInequality(ts.factory.createTypeOfExpression(left), ts.factory.createStringLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 79 /* SyntaxKind.Identifier */) { + // A -> typeof A !== "undefined" && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 79 /* SyntaxKind.Identifier */) { + // A.B -> typeof A !== "undefined" && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== "undefined" && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createLogicalAnd(ts.factory.createLogicalAnd(left.left, ts.factory.createStrictInequality(ts.factory.createAssignment(temp, left.right), ts.factory.createVoidZero())), ts.factory.createPropertyAccessExpression(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); + name.original = undefined; + ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. + return name; + case 161 /* SyntaxKind.QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * @param node The qualified name to serialize. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); + } + function getGlobalConstructorWithFallback(name) { + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createIdentifier(name), "function"), + /*questionToken*/ undefined, ts.factory.createIdentifier(name), + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + } + function getGlobalConstructor(name, minLanguageVersion) { + return languageVersion < minLanguageVersion ? + getGlobalConstructorWithFallback(name) : + ts.factory.createIdentifier(name); + } + } + ts.createRuntimeTypeSerializer = createRuntimeTypeSerializer; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformLegacyDecorators(context) { + var factory = context.factory, emitHelpers = context.getEmitHelperFactory, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + // Save the previous transformation hooks. + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onSubstituteNode = onSubstituteNode; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function modifierVisitor(node) { + return ts.isDecorator(node) ? undefined : node; + } + function visitor(node) { + if (!(node.transformFlags & 33554432 /* TransformFlags.ContainsDecorators */)) { + return node; + } + switch (node.kind) { + case 165 /* SyntaxKind.Decorator */: + // Decorators are elided. They will be emitted as part of `visitClassDeclaration`. + return undefined; + case 257 /* SyntaxKind.ClassDeclaration */: + return visitClassDeclaration(node); + case 226 /* SyntaxKind.ClassExpression */: + return visitClassExpression(node); + case 171 /* SyntaxKind.Constructor */: + return visitConstructorDeclaration(node); + case 169 /* SyntaxKind.MethodDeclaration */: + return visitMethodDeclaration(node); + case 173 /* SyntaxKind.SetAccessor */: + return visitSetAccessorDeclaration(node); + case 172 /* SyntaxKind.GetAccessor */: + return visitGetAccessorDeclaration(node); + case 167 /* SyntaxKind.PropertyDeclaration */: + return visitPropertyDeclaration(node); + case 164 /* SyntaxKind.Parameter */: + return visitParameterDeclaration(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitClassDeclaration(node) { + if (!(ts.classOrConstructorParameterIsDecorated(node) || ts.childIsDecorated(node))) + return ts.visitEachChild(node, visitor, context); + var statements = ts.hasDecorators(node) ? + transformClassDeclarationWithClassDecorators(node, node.name) : + transformClassDeclarationWithoutClassDecorators(node, node.name); + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(factory.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statements[0], ts.getEmitFlags(statements[0]) | 4194304 /* EmitFlags.HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + function decoratorContainsPrivateIdentifierInExpression(decorator) { + return !!(decorator.transformFlags & 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); + } + function parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators) { + return ts.some(parameterDecorators, decoratorContainsPrivateIdentifierInExpression); + } + function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.canHaveDecorators(member)) + continue; + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) + return true; + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) + return true; + } + return false; + } + function transformDecoratorsOfClassElements(node, members) { + var decorationStatements = []; + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ false); + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ true); + if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { + members = ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], members, true), [ + factory.createClassStaticBlockDeclaration(factory.createBlock(decorationStatements, /*multiLine*/ true)) + ], false)), members); + decorationStatements = undefined; + } + return { decorationStatements: decorationStatements, members: members }; + } + /** + * Transforms a non-decorated class declaration. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + */ + function transformClassDeclarationWithoutClassDecorators(node, name) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var _a; + var modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var updated = factory.updateClassDeclaration(node, modifiers, name, + /*typeParameters*/ undefined, heritageClauses, members); + return ts.addRange([updated], decorationStatements); + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function transformClassDeclarationWithClassDecorators(node, name) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var _a; + var location = ts.moveRangePastModifiers(node); + var classAlias = getClassAliasIfNeeded(node); + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var classExpression = factory.createClassExpression( + /*modifiers*/ undefined, name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(declName, + /*exclamationToken*/ undefined, + /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* NodeFlags.Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + var statements = [statement]; + ts.addRange(statements, decorationStatements); + addConstructorDecorationStatement(statements, node); + return statements; + } + function visitClassExpression(node) { + // Legacy decorators were not supported on class expressions + return factory.updateClassExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)); + } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)); + } + function finishClassElement(updated, original) { + if (updated !== original) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, original); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(original)); + } + return updated; + } + function visitMethodDeclaration(node) { + return finishClassElement(factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitGetAccessorDeclaration(node) { + return finishClassElement(factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitSetAccessorDeclaration(node) { + return finishClassElement(factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitPropertyDeclaration(node) { + if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */)) { + return undefined; + } + return finishClassElement(factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function visitParameterDeclaration(node) { + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* EmitFlags.NoTrailingSourceMap */); + } + return updated; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), function (expr) { return factory.createExpressionStatement(expr); })); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStaticElement, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStaticElement === ts.isStatic(member); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, function (m) { return isDecoratedClassElement(m, isStatic, node); }); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { + var member = members_8[_i]; + expressions = ts.append(expressions, generateClassElementDecorationExpression(node, member)); + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); + var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ + ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? factory.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : factory.createNull() + : undefined; + var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(helper, ts.moveRangePastModifiers(member)); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); + var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); + ts.setTextRange(helper, decorator.expression); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Gets an expression that represents a property name (for decorated properties or enums). + * For a computed property, a name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isPrivateIdentifier(name)) { + return factory.createIdentifier(""); + } + else if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression) + ? factory.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return factory.createStringLiteral(ts.idText(name)); + } + else { + return factory.cloneNode(name); + } + } + function enableSubstitutionForClassAliases() { + if (!classAliases) { + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(79 /* SyntaxKind.Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.isStatic(member) + ? factory.getDeclarationName(node) + : getClassPrototype(node); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* EmitHint.Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + var _a; + return (_a = trySubstituteClassAlias(node)) !== null && _a !== void 0 ? _a : node; + } + function trySubstituteClassAlias(node) { + if (classAliases) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; + } + } + } + } + return undefined; + } + } + ts.transformLegacyDecorators = transformLegacyDecorators; +})(ts || (ts = {})); +/*@internal*/ +var ts; (function (ts) { var ES2017SubstitutionFlags; (function (ES2017SubstitutionFlags) { @@ -96054,8 +97634,7 @@ var ts; * @param node The node to visit. */ function visitMethodDeclaration(node) { - return factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ @@ -96071,8 +97650,7 @@ var ts; * @param node The node to visit. */ function visitFunctionDeclaration(node) { - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96087,7 +97665,7 @@ var ts; * @param node The node to visit. */ function visitFunctionExpression(node) { - return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96102,7 +97680,7 @@ var ts; * @param node The node to visit. */ function visitArrowFunction(node) { - return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96404,7 +97982,6 @@ var ts; /* typeParameters */ undefined, /* parameters */ [ factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "v", /* questionToken */ undefined, @@ -96684,7 +98261,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -96757,7 +98334,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* SyntaxKind.CommaToken */) { @@ -96788,7 +98365,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* FlattenLevel.ObjectRest */); @@ -96829,7 +98406,7 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } @@ -96848,7 +98425,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* HierarchyFacts.IterationStatementExcludes */, 2 /* HierarchyFacts.IterationStatementIncludes */); - if (node.initializer.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -96955,17 +98532,15 @@ var ts; function visitParameter(node) { if (parametersWithPrecedingObjectRestOrSpread === null || parametersWithPrecedingObjectRestOrSpread === void 0 ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); } - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); @@ -96979,7 +98554,7 @@ var ts; if (parameters) { parameters.add(parameter); } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { parameters = new ts.Set(); } } @@ -96990,8 +98565,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateConstructorDeclaration(node, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -97001,8 +98575,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), + var updated = factory.updateGetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -97013,8 +98586,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateSetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -97024,9 +98596,8 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ - ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + var updated = factory.updateMethodDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifierLike) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), @@ -97043,8 +98614,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + var updated = factory.updateFunctionDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined @@ -97202,7 +98772,7 @@ var ts; statements = ts.append(statements, statement); } } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { containsPrecedingObjectRestOrSpread = true; var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* FlattenLevel.ObjectRest */, factory.getGeneratedNameForNode(parameter), /*doNotRecordTempVariablesInLine*/ false, @@ -97699,7 +99269,7 @@ var ts; var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1]; if (ts.isExternalModule(node)) { // Add `import` statement - var importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); + var importStatement = factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); ts.setParentRecursive(importStatement, /*incremental*/ false); statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement); } @@ -97930,22 +99500,29 @@ var ts; if (node === undefined) { return factory.createTrue(); } - else if (node.kind === 10 /* SyntaxKind.StringLiteral */) { + if (node.kind === 10 /* SyntaxKind.StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 288 /* SyntaxKind.JsxExpression */) { + if (node.kind === 288 /* SyntaxKind.JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } return ts.visitNode(node.expression, visitor, ts.isExpression); } - else { - return ts.Debug.failBadSyntaxKind(node); + if (ts.isJsxElement(node)) { + return visitJsxElement(node, /*isChild*/ false); } + if (ts.isJsxSelfClosingElement(node)) { + return visitJsxSelfClosingElement(node, /*isChild*/ false); + } + if (ts.isJsxFragment(node)) { + return visitJsxFragment(node, /*isChild*/ false); + } + return ts.Debug.failBadSyntaxKind(node); } function visitJsxText(node) { var fixed = fixupWhitespaceAndDecodeEntities(node.text); @@ -98567,7 +100144,7 @@ var ts; && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -98940,7 +100517,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], + /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], /*type*/ undefined, transformClassBody(node, extendsClauseElement)); // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier @@ -99018,7 +100595,6 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), @@ -99131,7 +100707,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass || superCallExpression) { - if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */)) { + if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -99283,7 +100859,6 @@ var ts; // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, @@ -99295,7 +100870,6 @@ var ts; else if (node.initializer) { // Initializers are elided return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.name, /*questionToken*/ undefined, @@ -99676,7 +101250,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { + if (node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { hierarchyFacts |= 65536 /* HierarchyFacts.CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -99735,8 +101309,7 @@ var ts; : node.name; exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -99962,7 +101535,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */) { + if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */) { if (node.flags & 3 /* NodeFlags.BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -99975,7 +101548,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */ + if (node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -100299,7 +101872,7 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 524288 /* TransformFlags.ContainsYield */ && + if ((property.transformFlags & 1048576 /* TransformFlags.ContainsYield */ && hierarchyFacts & 4 /* HierarchyFacts.AsyncFunctionBody */) || (hasComputed = ts.Debug.checkDefined(property.name).kind === 162 /* SyntaxKind.ComputedPropertyName */)) { numInitialProperties = i; @@ -100572,7 +102145,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 0 /* EmitFlags.None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -100687,7 +102260,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 524288 /* EmitFlags.ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -100830,7 +102403,7 @@ var ts; } } else { - loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + loopParameters.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); var checkFlags = resolver.getNodeCheckFlags(decl); if (checkFlags & 4194304 /* NodeCheckFlags.NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { var outParamName = factory.createUniqueName("out_" + ts.idText(name)); @@ -100987,10 +102560,10 @@ var ts; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); if (node.kind === 172 /* SyntaxKind.GetAccessor */) { - updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + updated = factory.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); } else { - updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body); + updated = factory.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; @@ -101169,7 +102742,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */ || + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */ || node.expression.kind === 106 /* SyntaxKind.SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -101177,7 +102750,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* EmitFlags.NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -102019,10 +103592,10 @@ var ts; case 247 /* SyntaxKind.ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -102086,8 +103659,7 @@ var ts; function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. if (node.asteriskToken) { - node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, node.modifiers, + node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(node.modifiers, /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body)), @@ -102227,7 +103799,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -103285,7 +104857,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + return !!node && (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -103916,7 +105488,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], /*type*/ undefined, factory.createBlock(buildResult, /*multiLine*/ buildResult.length > 0)), 524288 /* EmitFlags.ReuseTempVariableScope */)); } @@ -104334,7 +105906,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */ || + node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -104435,8 +106007,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ], false))) @@ -104457,7 +106029,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], /*type*/ undefined, ts.setTextRange(factory.createBlock([ factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([ factory.createVariableStatement( @@ -104506,8 +106078,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ])) @@ -104536,7 +106108,7 @@ var ts; var amdDependency = _a[_i]; if (amdDependency.name) { aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); } else { unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); @@ -104557,7 +106129,7 @@ var ts; // This is so that when printer will not substitute the identifier ts.setEmitFlags(importAliasName, 4 /* EmitFlags.NoSubstitution */); aliasedModuleNames.push(externalModuleName); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); } else { unaliasedModuleNames.push(externalModuleName); @@ -104671,7 +106243,7 @@ var ts; function visitorWorker(node, valueIsDiscarded) { // This visitor does not need to descend into the tree if there is no dynamic import, destructuring assignment, or update expression // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & (4194304 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (8388608 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -104822,7 +106394,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), visitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -104877,8 +106449,8 @@ var ts; var resolve = factory.createUniqueName("resolve"); var reject = factory.createUniqueName("reject"); var parameters = [ - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) ]; var body = factory.createBlock([ factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), @@ -105166,8 +106738,7 @@ var ts; function visitFunctionDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor), /*type*/ undefined, ts.visitEachChild(node.body, visitor, context)), /*location*/ node), @@ -105194,8 +106765,7 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor), ts.visitNodes(node.members, visitor)), node), node)); } else { @@ -105809,7 +107379,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -105842,8 +107412,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) ], /*type*/ undefined, moduleBodyBlock); // Write the call to `System.register` @@ -105978,7 +107548,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 1048576 /* TransformFlags.ContainsAwait */ ? + var modifiers = node.transformFlags & 2097152 /* TransformFlags.ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* ModifierFlags.Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -106065,10 +107635,9 @@ var ts; /*typeArguments*/ undefined, [n]))); } return factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, exportStarFunction, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], /*type*/ undefined, factory.createBlock([ factory.createVariableStatement( /*modifiers*/ undefined, factory.createVariableDeclarationList([ @@ -106159,7 +107728,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true))); } return factory.createArrayLiteralExpression(setters, /*multiLine*/ true); @@ -106257,7 +107826,7 @@ var ts; */ function visitFunctionDeclaration(node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock))); } @@ -106285,8 +107854,7 @@ var ts; var name = factory.getLocalName(node); hoistVariableDeclaration(name); // Rewrite the class declaration into an assignment of a class expression. - statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, visitor, ts.isDecorator), - /*modifiers*/ undefined, node.name, + statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -106887,7 +108455,7 @@ var ts; * @param node The node to visit. */ function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 4194304 /* TransformFlags.ContainsDynamicImport */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 8388608 /* TransformFlags.ContainsDynamicImport */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -107334,7 +108902,7 @@ var ts; // Though an error in es2020 modules, in node-flavor es2020 modules, we can helpfully transform this to a synthetic `require` call // To give easy access to a synchronous `require` in node-flavor esm. We do the transform even in scenarios where we error, but `import.meta.url` // is available, just because the output is reasonable for a node-like runtime. - return ts.getEmitScriptTarget(compilerOptions) >= ts.ModuleKind.ES2020 ? visitImportEqualsDeclaration(node) : undefined; + return ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.Node16 ? visitImportEqualsDeclaration(node) : undefined; case 271 /* SyntaxKind.ExportAssignment */: return visitExportAssignment(node); case 272 /* SyntaxKind.ExportDeclaration */: @@ -107357,7 +108925,6 @@ var ts; if (!importRequireStatements) { var createRequireName = factory.createUniqueName("_createRequire", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */); var importStatement = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamedImports([ @@ -107400,7 +108967,6 @@ var ts; function appendExportsOfImportEqualsDeclaration(statements, node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { statements = ts.append(statements, factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, ts.idText(node.name))]))); } return statements; @@ -107421,13 +108987,11 @@ var ts; var oldIdentifier = node.exportClause.name; var synthName = factory.getGeneratedNameForNode(oldIdentifier); var importDecl = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier, node.assertClause); ts.setOriginalNode(importDecl, node.exportClause); var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, synthName, oldIdentifier)])); ts.setOriginalNode(exportDecl, node); @@ -107679,7 +109243,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.SyntaxKind[node.kind])); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(node.kind))); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 254 /* SyntaxKind.VariableDeclaration */ || node.kind === 203 /* SyntaxKind.BindingElement */) { @@ -107890,7 +109454,7 @@ var ts; ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1; default: - return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.SyntaxKind[node.parent.kind])); + return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind))); } } function getTypeParameterConstraintVisibilityError() { @@ -108055,7 +109619,8 @@ var ts; trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, reportNonlocalAugmentation: reportNonlocalAugmentation, - reportNonSerializableProperty: reportNonSerializableProperty + reportNonSerializableProperty: reportNonSerializableProperty, + reportImportTypeNodeResolutionModeOverride: reportImportTypeNodeResolutionModeOverride, }; var errorNameNode; var errorFallbackNode; @@ -108182,6 +109747,11 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName)); } } + function reportImportTypeNodeResolutionModeOverride() { + if (!ts.isNightly() && (errorNameNode || errorFallbackNode)) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ @@ -108221,7 +109791,7 @@ var ts; resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -108364,7 +109934,7 @@ var ts; }); return ret; } - function filterBindingPatternInitializers(name) { + function filterBindingPatternInitializersAndRenamings(name) { if (name.kind === 79 /* SyntaxKind.Identifier */) { return name; } @@ -108380,7 +109950,12 @@ var ts; if (elem.kind === 227 /* SyntaxKind.OmittedExpression */) { return elem; } - return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + if (elem.propertyName && ts.isIdentifier(elem.propertyName) && ts.isIdentifier(elem.name) && !elem.symbol.isReferenced) { + // Unnecessary property renaming is forbidden in types, so remove renaming + return factory.updateBindingElement(elem, elem.dotDotDotToken, + /* propertyName */ undefined, elem.propertyName, shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializersAndRenamings(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); } } function ensureParameter(p, modifierMask, type) { @@ -108389,8 +109964,7 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } - var newParam = factory.updateParameterDeclaration(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + var newParam = factory.updateParameterDeclaration(p, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -108441,7 +110015,7 @@ var ts; if (node.kind === 164 /* SyntaxKind.Parameter */ || node.kind === 167 /* SyntaxKind.PropertyDeclaration */ || node.kind === 166 /* SyntaxKind.PropertySignature */) { - if (!node.initializer) + if (ts.isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } @@ -108527,7 +110101,6 @@ var ts; } if (!newValueParameter) { newValueParameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "value"); } @@ -108585,8 +110158,7 @@ var ts; if (decl.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); - return factory.updateImportEqualsDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + return factory.updateImportEqualsDeclaration(decl, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } else { var oldDiag = getSymbolAccessibilityDiagnostic; @@ -108599,31 +110171,28 @@ var ts; function transformImportDeclaration(decl) { if (!decl.importClause) { // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // The `importClause` visibility corresponds to the default's visibility. var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; if (!decl.importClause.namedBindings) { // No named bindings (either namespace or list), meaning the import is just default or should be elided - return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, + return visibleDefaultBinding && factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } if (decl.importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; - return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; + return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; } // Named imports (optionally with visible default) var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); if ((bindingList && bindingList.length) || visibleDefaultBinding) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Augmentation of export depends on import if (resolver.isImportRequiredByAugmentation(decl)) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, + return factory.updateImportDeclaration(decl, decl.modifiers, /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Nothing visible @@ -108632,7 +110201,7 @@ var ts; var mode = ts.getResolutionModeOverrideForClause(assertClause); if (mode !== undefined) { if (!ts.isNightly()) { - context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); } return assertClause; } @@ -108656,7 +110225,7 @@ var ts; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.Debug.formatSyntaxKind(i.kind))); } var priorNeedsDeclare = needsDeclare; needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); @@ -108720,7 +110289,7 @@ var ts; if (ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)) { if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; // Elide all but the first overload - return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + return cleanup(factory.createPropertyDeclaration(ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); } } if (canProduceDiagnostic && !suppressNewDiagnosticContexts) { @@ -108752,7 +110321,6 @@ var ts; case 171 /* SyntaxKind.Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* ModifierFlags.None */), /*body*/ undefined); return cleanup(ctor); @@ -108761,8 +110329,7 @@ var ts; if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - var sig = factory.createMethodDeclaration( - /*decorators*/ undefined, ensureModifiers(input), + var sig = factory.createMethodDeclaration(ensureModifiers(input), /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined); return cleanup(sig); @@ -108772,24 +110339,21 @@ var ts; return cleanup(/*returnValue*/ undefined); } var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); - return cleanup(factory.updateGetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), + return cleanup(factory.updateGetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), /*body*/ undefined)); } case 173 /* SyntaxKind.SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updateSetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), + return cleanup(factory.updateSetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), /*body*/ undefined)); } case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updatePropertyDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); + return cleanup(factory.updatePropertyDeclaration(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); case 166 /* SyntaxKind.PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); @@ -108805,8 +110369,7 @@ var ts; return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } case 176 /* SyntaxKind.IndexSignature */: { - return cleanup(factory.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); + return cleanup(factory.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); } case 254 /* SyntaxKind.VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { @@ -108845,7 +110408,7 @@ var ts; return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.assertions, input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); } - default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.SyntaxKind[input.kind])); + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(input.kind))); } } if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) { @@ -108889,8 +110452,7 @@ var ts; resultHasScopeMarker = true; // Always visible if the parent node isn't dropped for being not visible // Rewrite external module names if necessary - return factory.updateExportDeclaration(input, - /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); + return factory.updateExportDeclaration(input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); } case 271 /* SyntaxKind.ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible @@ -108913,7 +110475,7 @@ var ts; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* NodeFlags.Const */)); preserveJsDoc(statement, input); ts.removeAllComments(input); - return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + return [statement, factory.updateExportAssignment(input, input.modifiers, newId)]; } } } @@ -108928,7 +110490,7 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (125951 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (257023 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { @@ -108964,22 +110526,19 @@ var ts; var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 259 /* SyntaxKind.TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all - return cleanup(factory.updateTypeAliasDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + return cleanup(factory.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 258 /* SyntaxKind.InterfaceDeclaration */: { - return cleanup(factory.updateInterfaceDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + return cleanup(factory.updateInterfaceDeclaration(input, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 256 /* SyntaxKind.FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - var clean = cleanup(factory.updateFunctionDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), + var clean = cleanup(factory.updateFunctionDeclaration(input, ensureModifiers(input), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); if (clean && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { var props = resolver.getPropertiesOfContainerFunction(input); // Use parseNodeFactory so it is usable as an enclosing declaration - var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace_1, enclosingDeclaration); fakespace_1.locals = ts.createSymbolTable(props); fakespace_1.symbol = props[0].parent; @@ -109005,26 +110564,22 @@ var ts; } else { declarations.push(factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) { var gen = _a[0], exp = _a[1]; return factory.createExportSpecifier(/*isTypeOnly*/ false, gen, exp); })))); } - var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); + var namespaceDecl = factory.createModuleDeclaration(ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); if (!ts.hasEffectiveModifier(clean, 512 /* ModifierFlags.Default */)) { return [clean, namespaceDecl]; } var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ModifierFlags.ExportDefault */) | 2 /* ModifierFlags.Ambient */); - var cleanDeclaration = factory.updateFunctionDeclaration(clean, - /*decorators*/ undefined, modifiers, + var cleanDeclaration = factory.updateFunctionDeclaration(clean, modifiers, /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, /*body*/ undefined); - var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, - /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body); + var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, modifiers, namespaceDecl.name, namespaceDecl.body); var exportDefaultDeclaration = factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, namespaceDecl.name); if (ts.isSourceFile(input.parent)) { @@ -109067,8 +110622,7 @@ var ts; needsScopeFixMarker = oldNeedsScopeFix; resultHasScopeMarker = oldHasScopeFix; var mods = ensureModifiers(input); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; @@ -109079,8 +110633,7 @@ var ts; var id = ts.getOriginalNodeId(inner); // TODO: GH#18217 var body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, input.name, body)); } } case 257 /* SyntaxKind.ClassDeclaration */: { @@ -109097,8 +110650,7 @@ var ts; return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 79 /* SyntaxKind.Identifier */) { - return preserveJsDoc(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + return preserveJsDoc(factory.createPropertyDeclaration(ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } else { // Pattern - this is currently an error, but we emit declarations for it somewhat correctly @@ -109114,8 +110666,7 @@ var ts; elems = ts.concatenate(elems, walkBindingPattern(elem.name)); } elems = elems || []; - elems.push(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), elem.name, + elems.push(factory.createPropertyDeclaration(ensureModifiers(param), elem.name, /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), /*initializer*/ undefined)); } @@ -109129,7 +110680,6 @@ var ts; // Prevents other classes with the same public members from being used in place of the current class var privateIdentifier = hasPrivateIdentifier ? [ factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"), /*questionToken*/ undefined, /*type*/ undefined, @@ -109159,20 +110709,18 @@ var ts; } return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 104 /* SyntaxKind.NullKeyword */; })), visitDeclarationSubtree)); })); - return [statement, cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + return [statement, cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 } else { var heritageClauses = transformHeritageClauses(input.heritageClauses); - return cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + return cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members)); } } case 237 /* SyntaxKind.VariableStatement */: { return cleanup(transformVariableStatement(input)); } case 260 /* SyntaxKind.EnumDeclaration */: { - return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(factory.updateEnumDeclaration(input, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; // Rewrite enum values to their constants, if available @@ -109182,7 +110730,7 @@ var ts; } } // Anything left unhandled is an error, so this should be unreachable - return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.SyntaxKind[input.kind])); + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.Debug.formatSyntaxKind(input.kind))); function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; @@ -109256,12 +110804,12 @@ var ts; var currentFlags = ts.getEffectiveModifierFlags(node); var newFlags = ensureModifierFlags(node); if (currentFlags === newFlags) { - return node.modifiers; + return ts.visitArray(node.modifiers, function (n) { return ts.tryCast(n, ts.isModifier); }, ts.isModifier); } return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 125951 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files + var mask = 257023 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* ModifierFlags.Ambient */ : 0 /* ModifierFlags.None */; var parentIsFile = node.parent.kind === 305 /* SyntaxKind.SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { @@ -109302,7 +110850,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 125951 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } + if (modifierMask === void 0) { modifierMask = 257023 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* ModifierFlags.None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* ModifierFlags.Default */ && !(flags & 1 /* ModifierFlags.Export */)) { @@ -109424,6 +110972,7 @@ var ts; var transformers = []; ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory)); transformers.push(ts.transformTypeScript); + transformers.push(ts.transformLegacyDecorators); transformers.push(ts.transformClassFields); if (ts.getJSXTransformEnabled(compilerOptions)) { transformers.push(ts.transformJsx); @@ -110184,7 +111733,6 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; - var exportedModulesFromDeclarationEmit; // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); @@ -110194,7 +111742,6 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, - exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath; @@ -110248,14 +111795,16 @@ var ts; return; } var version = ts.version; // Extracted into a const so the form is stable between namespace and module - ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false); + var buildInfo = { bundle: bundle, program: program, version: version }; + // Pass buildinfo as additional data to avoid having to reparse + ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText(buildInfo), /*writeByteOrderMark*/ false, /*sourceFiles*/ undefined, { buildInfo: buildInfo }); } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) { if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) { return; } // Make sure not to write js file and source map file if any of them cannot be written - if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit) { emitSkipped = true; return; } @@ -110284,7 +111833,7 @@ var ts; substituteNode: transform.substituteNode, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); if (bundleBuildInfo) @@ -110320,7 +111869,7 @@ var ts; noEmitHelpers: true, module: compilerOptions.module, target: compilerOptions.target, - sourceMap: compilerOptions.sourceMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, inlineSourceMap: compilerOptions.inlineSourceMap, extendedDiagnostics: compilerOptions.extendedDiagnostics, onlyPrintJsDocStyle: true, @@ -110340,17 +111889,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: !forceDtsEmit && compilerOptions.declarationMap, + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform, declarationPrinter, { + sourceMap: printerOptions.sourceMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 305 /* SyntaxKind.SourceFile */) { - var sourceFile = declarationTransform.transformed[0]; - exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; - } } declarationTransform.dispose(); if (bundleBuildInfo) @@ -110369,7 +111914,8 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, mapOptions) { + var sourceFileOrBundle = transform.transformed[0]; var bundle = sourceFileOrBundle.kind === 306 /* SyntaxKind.Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 305 /* SyntaxKind.SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; @@ -110402,13 +111948,20 @@ var ts; if (sourceMapFilePath) { var sourceMap = sourceMapGenerator.toString(); ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + if (printer.bundleFileInfo) + printer.bundleFileInfo.mapHash = ts.computeSignature(sourceMap, ts.maybeBind(host, host.createHash)); } } else { writer.writeLine(); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos }); + var text = writer.getText(); + ts.writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos, diagnostics: transform.diagnostics }); + // We store the hash of the text written in the buildinfo to ensure that text of the referenced d.ts file is same as whats in the buildinfo + // This is needed because incremental can be toggled between two runs and we might use stale file text to do text manipulation in prepend mode + if (printer.bundleFileInfo) + printer.bundleFileInfo.hash = ts.computeSignature(text, ts.maybeBind(host, host.createHash)); // Reset state writer.clear(); } @@ -110551,34 +112104,56 @@ var ts; } /*@internal*/ function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) { + var createHash = ts.maybeBind(host, host.createHash); var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath)); - if (!buildInfoText) + var buildInfo; + if (host.getBuildInfo) { + // If host directly provides buildinfo we can get it directly. This allows host to cache the buildinfo + var hostBuildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); + if (!hostBuildInfo) + return buildInfoPath; + buildInfo = hostBuildInfo; + } + else { + var buildInfoText = host.readFile(buildInfoPath); + if (!buildInfoText) + return buildInfoPath; + buildInfo = getBuildInfo(buildInfoText); + } + if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationFilePath && !buildInfo.bundle.dts)) return buildInfoPath; var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath)); if (!jsFileText) return jsFilePath; + // If the jsFileText is not same has what it was created with, tsbuildinfo is stale so dont use it + if (ts.computeSignature(jsFileText, createHash) !== buildInfo.bundle.js.hash) + return jsFilePath; var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); // error if no source map or for now if inline sourcemap if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap) return sourceMapFilePath || "inline sourcemap decoding"; + if (sourceMapFilePath && ts.computeSignature(sourceMapText, createHash) !== buildInfo.bundle.js.mapHash) + return sourceMapFilePath; // read declaration text var declarationText = declarationFilePath && host.readFile(declarationFilePath); if (declarationFilePath && !declarationText) return declarationFilePath; + if (declarationFilePath && ts.computeSignature(declarationText, createHash) !== buildInfo.bundle.dts.hash) + return declarationFilePath; var declarationMapText = declarationMapPath && host.readFile(declarationMapPath); // error if no source map or for now if inline sourcemap if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding"; - var buildInfo = getBuildInfo(buildInfoText); - if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts)) - return buildInfoPath; + if (declarationMapPath && ts.computeSignature(declarationMapText, createHash) !== buildInfo.bundle.dts.mapHash) + return declarationMapPath; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, /*onlyOwnText*/ true); var outputFiles = []; var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); }); var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host); + var changedDtsText; + var changedDtsData; var emitHost = { getPrependNodes: ts.memoize(function () { return __spreadArray(__spreadArray([], prependNodes, true), [ownPrependInput], false); }), getCanonicalFileName: host.getCanonicalFileName, @@ -110594,7 +112169,7 @@ var ts; getResolvedProjectReferenceToRedirect: ts.returnUndefined, getProjectReferenceRedirect: ts.returnUndefined, isSourceOfProjectReferenceRedirect: ts.returnFalse, - writeFile: function (name, text, writeByteOrderMark) { + writeFile: function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { switch (name) { case jsFilePath: if (jsFileText === text) @@ -110605,8 +112180,12 @@ var ts; return; break; case buildInfoPath: - var newBuildInfo = getBuildInfo(text); + var newBuildInfo = data.buildInfo; newBuildInfo.program = buildInfo.program; + if (newBuildInfo.program && changedDtsText !== undefined && config.options.composite) { + // Update the output signature + newBuildInfo.program.outSignature = ts.computeSignature(changedDtsText, createHash, changedDtsData); + } // Update sourceFileInfo var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles; newBuildInfo.bundle.js.sources = js.sources; @@ -110614,11 +112193,13 @@ var ts; newBuildInfo.bundle.dts.sources = dts.sources; } newBuildInfo.bundle.sourceFiles = sourceFiles; - outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark }); + outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark, buildInfo: newBuildInfo }); return; case declarationFilePath: if (declarationText === text) return; + changedDtsText = text; + changedDtsData = data; break; case declarationMapPath: if (declarationMapText === text) @@ -110637,6 +112218,7 @@ var ts; getSourceFileFromReference: ts.returnUndefined, redirectTargetsMap: ts.createMultiMap(), getFileIncludeReasons: ts.notImplemented, + createHash: createHash, }; emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers)); @@ -111724,8 +113306,7 @@ var ts; } } function emitParameter(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); @@ -111736,7 +113317,7 @@ var ts; emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); @@ -111746,7 +113327,6 @@ var ts; // Type members // function emitPropertySignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); @@ -111754,8 +113334,7 @@ var ts; writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); emit(node.exclamationToken); @@ -111765,7 +113344,6 @@ var ts; } function emitMethodSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); @@ -111776,16 +113354,13 @@ var ts; popNameGenerationScope(node); } function emitMethodDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.asteriskToken); emit(node.name); emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitClassStaticBlockDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("static"); emitBlockFunctionBody(node.body); } @@ -111795,8 +113370,7 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword(node.kind === 172 /* SyntaxKind.GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); @@ -111804,8 +113378,6 @@ var ts; } function emitCallSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); @@ -111814,8 +113386,6 @@ var ts; } function emitConstructSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -111825,7 +113395,6 @@ var ts; popNameGenerationScope(node); } function emitIndexSignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); @@ -112218,7 +113787,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitSignatureAndBody(node, emitArrowFunctionHead); } @@ -112699,7 +114267,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitFunctionDeclarationOrExpression(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); emit(node.asteriskToken); @@ -112757,8 +114324,8 @@ var ts; if (!ts.nodeIsSynthesized(body) && currentSourceFile && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { return false; } - if (getLeadingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */) - || getClosingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */)) { + if (getLeadingLineTerminatorCount(body, ts.firstOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */) + || getClosingLineTerminatorCount(body, ts.lastOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */, body.statements)) { return false; } var previousStatement; @@ -112806,8 +114373,7 @@ var ts; } function emitClassDeclarationOrExpression(node) { ts.forEach(node.members, generateMemberNames); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword("class"); if (node.name) { writeSpace(); @@ -112828,7 +114394,6 @@ var ts; } } function emitInterfaceDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("interface"); writeSpace(); @@ -112841,7 +114406,6 @@ var ts; writePunctuation("}"); } function emitTypeAliasDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("type"); writeSpace(); @@ -113468,8 +115032,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* BundleFileSectionKind.Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_24 = types; _d < types_24.length; _d++) { - var directive = types_24[_d]; + for (var _d = 0, types_23 = types; _d < types_23.length; _d++) { + var directive = types_23[_d]; var pos = writer.getTextPos(); var resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.impliedNodeFormat) ? "resolution-mode=\"".concat(directive.resolutionMode === ts.ModuleKind.ESNext ? "import" : "require", "\"") @@ -113643,12 +115207,52 @@ var ts; emit(node); write = savedWrite; } - function emitModifiers(node, modifiers) { - if (modifiers && modifiers.length) { - emitList(node, modifiers, 262656 /* ListFormat.Modifiers */); - writeSpace(); + function emitDecoratorsAndModifiers(node, modifiers) { + if (modifiers === null || modifiers === void 0 ? void 0 : modifiers.length) { + if (ts.every(modifiers, ts.isModifier)) { + // if all modifier-likes are `Modifier`, simply emit the array as modifiers. + return emitModifiers(node, modifiers); + } + if (ts.every(modifiers, ts.isDecorator)) { + // if all modifier-likes are `Decorator`, simply emit the array as decorators. + return emitDecorators(node, modifiers); + } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(modifiers); + // partition modifiers into contiguous chunks of `Modifier` or `Decorator` + var lastMode = void 0; + var mode = void 0; + var start = 0; + var pos = 0; + while (start < modifiers.length) { + while (pos < modifiers.length) { + var modifier = modifiers[pos]; + mode = ts.isDecorator(modifier) ? "decorators" : "modifiers"; + if (lastMode === undefined) { + lastMode = mode; + } + else if (mode !== lastMode) { + break; + } + pos++; + } + var textRange = { pos: -1, end: -1 }; + if (start === 0) + textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) + textRange.end = modifiers.end; + emitNodeListItems(emit, node, modifiers, lastMode === "modifiers" ? 2359808 /* ListFormat.Modifiers */ : 2146305 /* ListFormat.Decorators */, + /*parenthesizerRule*/ undefined, start, pos - start, + /*hasTrailingComma*/ false, textRange); + start = pos; + lastMode = mode; + pos++; + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(modifiers); } } + function emitModifiers(node, modifiers) { + emitList(node, modifiers, 2359808 /* ListFormat.Modifiers */); + } function emitTypeAnnotation(node) { if (node) { writePunctuation(":"); @@ -113726,11 +115330,9 @@ var ts; && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head && !parentNode.type // arrow function may not have return type annotation - && !ts.some(parentNode.decorators) // parent may not have decorators - && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.modifiers) // parent may not have decorators or modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters - && !ts.some(parameter.decorators) // parameter may not have decorators - && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !ts.some(parameter.modifiers) // parameter may not have decorators or modifiers && !parameter.dotDotDotToken // parameter may not be rest && !parameter.questionToken // parameter may not be optional && !parameter.type // parameter may not have a type annotation @@ -113785,12 +115387,8 @@ var ts; } var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 32768 /* ListFormat.OptionalIfEmpty */) { - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); return; } if (format & 15360 /* ListFormat.BracketsMask */) { @@ -113799,9 +115397,7 @@ var ts; emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); if (isEmpty) { // Write a line terminator if the parent node was multi-line if (format & 1 /* ListFormat.MultiLine */ && !(preserveSourceNewlines && (!parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { @@ -113812,123 +115408,128 @@ var ts; } } else { - ts.Debug.type(children); - // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; - var shouldEmitInterveningComments = mayEmitInterveningComments; - var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217 - if (leadingLineTerminatorCount) { - writeLine(leadingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { - writeSpace(); - } - // Increase the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { - increaseIndent(); + emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, children.hasTrailingComma, children); + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); + if (format & 15360 /* ListFormat.BracketsMask */) { + if (isEmpty && children) { + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } - var emitListItem = getEmitListItem(emit, parenthesizerRule); - // Emit each child. - var previousSibling = void 0; - var previousSourceFileTextKind = void 0; - var shouldDecreaseIndentAfterEmit = false; - for (var i = 0; i < count; i++) { - var child = children[start + i]; - // Write the delimiter if this is not the first node. - if (format & 32 /* ListFormat.AsteriskDelimited */) { - // always write JSDoc in the format "\n *" - writeLine(); - writeDelimiter(format); - } - else if (previousSibling) { - // i.e - // function commentedParameters( - // /* Parameter a */ - // a - // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline - // , - if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { - emitLeadingCommentsOfPosition(previousSibling.end); - } - writeDelimiter(format); - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write either a line terminator or whitespace to separate the elements. - var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); - if (separatingLineTerminatorCount > 0) { - // If a synthesized node in a single-line list starts on a new - // line, we should increase the indent. - if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { - increaseIndent(); - shouldDecreaseIndentAfterEmit = true; - } - writeLine(separatingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { - writeSpace(); - } - } - // Emit this child. - previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); - if (shouldEmitInterveningComments) { - var commentRange = ts.getCommentRange(child); - emitTrailingCommentsOfPosition(commentRange.pos); - } - else { - shouldEmitInterveningComments = mayEmitInterveningComments; - } - nextListElementPos = child.pos; - emitListItem(child, emit, parenthesizerRule, i); - if (shouldDecreaseIndentAfterEmit) { - decreaseIndent(); - shouldDecreaseIndentAfterEmit = false; + writePunctuation(getClosingBracket(format)); + } + } + /** + * Emits a list without brackets or raising events. + * + * NOTE: You probably don't want to call this directly and should be using `emitList` or `emitExpressionList` instead. + */ + function emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, hasTrailingComma, childrenTextRange) { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children[start], format); + if (leadingLineTerminatorCount) { + writeLine(leadingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + increaseIndent(); + } + var emitListItem = getEmitListItem(emit, parenthesizerRule); + // Emit each child. + var previousSibling; + var previousSourceFileTextKind; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* ListFormat.AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write either a line terminator or whitespace to separate the elements. + var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); + if (separatingLineTerminatorCount > 0) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(separatingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { + writeSpace(); } - previousSibling = child; } - // Write a trailing comma, if requested. - var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; - var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); - var hasTrailingComma = (children === null || children === void 0 ? void 0 : children.hasTrailingComma) && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); - if (hasTrailingComma) { - if (previousSibling && !skipTrailingComments) { - emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); - } - else { - writePunctuation(","); - } + // Emit this child. + previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); + if (shouldEmitInterveningComments) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); } - // Emit any trailing comment of the last element in the list - // i.e - // var array = [... - // 2 - // /* end of element 2 */ - // ]; - if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { - emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); - } - // Decrease the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + nextListElementPos = child.pos; + emitListItem(child, emit, parenthesizerRule, i); + if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; } - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write the closing line terminator or closing whitespace. - var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format); - if (closingLineTerminatorCount) { - writeLine(closingLineTerminatorCount); + previousSibling = child; + } + // Write a trailing comma, if requested. + var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; + var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); + var emitTrailingComma = hasTrailingComma && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); + if (emitTrailingComma) { + if (previousSibling && !skipTrailingComments) { + emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); } - else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { - writeSpace(); + else { + writePunctuation(","); } } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { + emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange === null || childrenTextRange === void 0 ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end); } - if (format & 15360 /* ListFormat.BracketsMask */) { - if (isEmpty && children) { - emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists - } - writePunctuation(getClosingBracket(format)); + // Decrease the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + decreaseIndent(); + } + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write the closing line terminator or closing whitespace. + var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children[start + count - 1], format, childrenTextRange); + if (closingLineTerminatorCount) { + writeLine(closingLineTerminatorCount); + } + else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { + writeSpace(); } } // Writers @@ -114058,16 +115659,15 @@ var ts; decreaseIndent(); } } - function getLeadingLineTerminatorCount(parentNode, children, format) { + function getLeadingLineTerminatorCount(parentNode, firstChild, format) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var firstChild_1 = children[0]; - if (firstChild_1 === undefined) { + if (firstChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (firstChild_1.pos === nextListElementPos) { + if (firstChild.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading // line terminators have already been written as the separating line terminators of the // parent list. Example: @@ -114085,20 +115685,20 @@ var ts; // leading newline to start the modifiers. return 0; } - if (firstChild_1.kind === 11 /* SyntaxKind.JsxText */) { + if (firstChild.kind === 11 /* SyntaxKind.JsxText */) { // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && - !ts.nodeIsSynthesized(firstChild_1) && - (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { + !ts.nodeIsSynthesized(firstChild) && + (!firstChild.parent || ts.getOriginalNode(firstChild.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild.pos, parentNode.pos, currentSourceFile, includeComments); }); } - return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; + return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; } - if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) { + if (synthesizedNodeStartsOnNewLine(firstChild, format)) { return 1; } } @@ -114138,18 +115738,17 @@ var ts; } return format & 1 /* ListFormat.MultiLine */ ? 1 : 0; } - function getClosingLineTerminatorCount(parentNode, children, format) { + function getClosingLineTerminatorCount(parentNode, lastChild, format, childrenTextRange) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { - var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; + var end_1 = childrenTextRange && !ts.positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; @@ -114187,14 +115786,14 @@ var ts; return lines; } function writeLineSeparatorsAndIndentBefore(node, parent) { - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, node, 0 /* ListFormat.None */); if (leadingNewlines) { writeLinesAndIndent(leadingNewlines, /*writeSpaceIfNotIndenting*/ false); } return !!leadingNewlines; } function writeLineSeparatorsAfter(node, parent) { - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, node, 0 /* ListFormat.None */, /*childrenTextRange*/ undefined); if (trailingNewlines) { writeLine(trailingNewlines); } @@ -115721,12 +117320,10 @@ var ts; } ts.createCompilerHost = createCompilerHost; /*@internal*/ - // TODO(shkamat): update this after reworking ts build API function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = new ts.Map(); var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); - var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash; function getSourceFile(fileName, languageVersionOrOptions, onError) { var text; try { @@ -115759,7 +117356,7 @@ var ts; // NOTE: If patchWriteFileEnsuringDirectory has been called, // the system.writeFile will do its own directory creation and // the ensureDirectoriesExist call will always be redundant. - ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -115769,35 +117366,6 @@ var ts; } } } - var outputFingerprints; - function writeFileWorker(fileName, data, writeByteOrderMark) { - if (!ts.isWatchSet(options) || !system.getModifiedTime) { - system.writeFile(fileName, data, writeByteOrderMark); - return; - } - if (!outputFingerprints) { - outputFingerprints = new ts.Map(); - } - var hash = computeHash(data); - var mtimeBefore = system.getModifiedTime(fileName); - if (mtimeBefore) { - var fingerprint = outputFingerprints.get(fileName); - // If output has not been changed, and the file has no external modification - if (fingerprint && - fingerprint.byteOrderMark === writeByteOrderMark && - fingerprint.hash === hash && - fingerprint.mtime.getTime() === mtimeBefore.getTime()) { - return; - } - } - system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; - outputFingerprints.set(fileName, { - hash: hash, - byteOrderMark: writeByteOrderMark, - mtime: mtimeAfter - }); - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -115904,7 +117472,7 @@ var ts; }; } // directoryExists - if (originalDirectoryExists && originalCreateDirectory) { + if (originalDirectoryExists) { host.directoryExists = function (directory) { var key = toPath(directory); var value = directoryExistsCache.get(key); @@ -115914,11 +117482,13 @@ var ts; directoryExistsCache.set(key, !!newValue); return newValue; }; - host.createDirectory = function (directory) { - var key = toPath(directory); - directoryExistsCache.delete(key); - originalCreateDirectory.call(host, directory); - }; + if (originalCreateDirectory) { + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } } return { originalReadFile: originalReadFile, @@ -116139,12 +117709,14 @@ var ts; } ts.loadWithTypeDirectiveCache = loadWithTypeDirectiveCache; ; - /* @internal */ + /** + * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly + * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. + */ function getModeForFileReference(ref, containingFileMode) { return (ts.isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode; } ts.getModeForFileReference = getModeForFileReference; - /* @internal */ function getModeForResolutionAtIndex(file, index) { if (file.impliedNodeFormat === undefined) return undefined; @@ -116165,7 +117737,15 @@ var ts; return false; } ts.isExclusivelyTypeOnlyImportOrExport = isExclusivelyTypeOnlyImportOrExport; - /* @internal */ + /** + * Calculates the final resolution mode for a given module reference node. This is generally the explicitly provided resolution mode, if + * one exists, or the mode of the containing source file. (Excepting import=require, which is always commonjs, and dynamic import, which is always esm). + * Notably, this function always returns `undefined` if the containing file has an `undefined` `impliedNodeFormat` - this field is only set when + * `moduleResolution` is `node16`+. + * @param file The file the import or import-like reference is contained within + * @param usage The module reference string + * @returns The final resolution mode of the import + */ function getModeForUsageLocation(file, usage) { var _a, _b; if (file.impliedNodeFormat === undefined) @@ -116411,6 +117991,12 @@ var ts; * @returns `undefined` if the path has no relevant implied format, `ModuleKind.ESNext` for esm format, and `ModuleKind.CommonJS` for cjs format */ function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, options) { + var result = getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options); + return typeof result === "object" ? result.impliedNodeFormat : result; + } + ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + /*@internal*/ + function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) { switch (ts.getEmitModuleResolutionKind(options)) { case ts.ModuleResolutionKind.Node16: case ts.ModuleResolutionKind.NodeNext: @@ -116422,11 +118008,16 @@ var ts; return undefined; } function lookupFromPackageJson() { - var scope = ts.getPackageScopeForPath(fileName, packageJsonInfoCache, host, options); - return (scope === null || scope === void 0 ? void 0 : scope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + var state = ts.getTemporaryModuleResolutionState(packageJsonInfoCache, host, options); + var packageJsonLocations = []; + state.failedLookupLocations = packageJsonLocations; + state.affectingLocations = packageJsonLocations; + var packageJsonScope = ts.getPackageScopeForPath(fileName, state); + var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope }; } } - ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + ts.getImpliedNodeFormatForFileWorker = getImpliedNodeFormatForFileWorker; /** @internal */ ts.plainJSErrors = new ts.Set([ // binder errors @@ -116519,6 +118110,9 @@ var ts; ts.Diagnostics.extends_clause_already_seen.code, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + ts.Diagnostics.Class_constructor_may_not_be_a_generator.code, + ts.Diagnostics.Class_constructor_may_not_be_an_accessor.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]); /** * Determine if source file needs to be re-created even if its text hasn't changed @@ -116748,7 +118342,7 @@ var ts; for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); - if (shouldCreateNewSourceFile || !newFile || + if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // old file wasn't redirect but new file is (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); @@ -117085,7 +118679,7 @@ var ts; // `result[i]` is either a `ResolvedModuleFull` or a marker. // If it is the former, we can leave it as is. if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; // TODO: GH#18217 + result[i] = undefined; } } else { @@ -117141,7 +118735,7 @@ var ts; }); } function tryReuseStructureFromOldProgram() { - var _a; + var _a, _b; if (!oldProgram) { return 0 /* StructureIsReused.Not */; } @@ -117182,12 +118776,15 @@ var ts; var seenPackageNames = new ts.Map(); for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; + var sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options); var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat) + : host.getSourceFile(oldSourceFile.fileName, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat); // TODO: GH#18217 if (!newSourceFile) { return 0 /* StructureIsReused.Not */; } + newSourceFile.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope; ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); var fileChanged = void 0; if (oldSourceFile.redirectInfo) { @@ -117227,38 +118824,43 @@ var ts; seenPackageNames.set(packageName, newKind); } if (fileChanged) { + if (oldSourceFile.impliedNodeFormat !== newSourceFile.impliedNodeFormat) { + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } // The `newSourceFile` object was created for the new program. - if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { // 'lib' references has changed. Matches behavior in changesAffectModuleResolution structureIsReused = 1 /* StructureIsReused.SafeModules */; } - if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + else if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files structureIsReused = 1 /* StructureIsReused.SafeModules */; } // check tripleslash references - if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed structureIsReused = 1 /* StructureIsReused.SafeModules */; } - // check imports and module augmentations - collectExternalModuleReferences(newSourceFile); - if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - // imports has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - // moduleAugmentations has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { - // dynamicImport has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - // 'types' references has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; + else { + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); @@ -117276,18 +118878,18 @@ var ts; return structureIsReused; } var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); - for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) { - var oldFile = oldSourceFiles_3[_b]; + for (var _c = 0, oldSourceFiles_3 = oldSourceFiles; _c < oldSourceFiles_3.length; _c++) { + var oldFile = oldSourceFiles_3[_c]; if (!ts.contains(modifiedFiles, oldFile)) { - for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) { - var moduleName = _d[_c]; + for (var _d = 0, _e = oldFile.ambientModuleNames; _d < _e.length; _d++) { + var moduleName = _e[_d]; ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); } } } // try to verify results of module resolution - for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) { - var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile; + for (var _f = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _f < modifiedSourceFiles_1.length; _f++) { + var _g = modifiedSourceFiles_1[_f], oldSourceFile = _g.oldFile, newSourceFile = _g.newFile; var moduleNames = getModuleNames(newSourceFile); var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); // ensure that module resolution results are still correct @@ -117314,14 +118916,14 @@ var ts; if (structureIsReused !== 2 /* StructureIsReused.Completely */) { return structureIsReused; } - if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host))) { + if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_b = host.hasChangedAutomaticTypeDirectiveNames) === null || _b === void 0 ? void 0 : _b.call(host))) { return 1 /* StructureIsReused.SafeModules */; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); - for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) { - var newSourceFile = newSourceFiles_1[_g]; + for (var _h = 0, newSourceFiles_1 = newSourceFiles; _h < newSourceFiles_1.length; _h++) { + var newSourceFile = newSourceFiles_1[_h]; filesByName.set(newSourceFile.path, newSourceFile); } var oldFilesByNameMap = oldProgram.getFilesByNameMap(); @@ -117383,6 +118985,7 @@ var ts; getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); }, redirectTargetsMap: redirectTargetsMap, getFileIncludeReasons: program.getFileIncludeReasons, + createHash: ts.maybeBind(host, host.createHash), }; } function writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data) { @@ -117736,7 +119339,7 @@ var ts; } } function walkArray(nodes, parent) { - if (parent.decorators === nodes && !options.experimentalDecorators) { + if (ts.canHaveModifiers(parent) && parent.modifiers === nodes && ts.some(nodes, ts.isDecorator) && !options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { @@ -117767,7 +119370,7 @@ var ts; if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { + if (ts.isModifier(modifier) && modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); } } @@ -117776,7 +119379,7 @@ var ts; break; case 164 /* SyntaxKind.Parameter */: // Check modifiers of parameter declaration - if (nodes === parent.modifiers) { + if (nodes === parent.modifiers && ts.some(nodes, ts.isModifier)) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -117895,7 +119498,7 @@ var ts; } function createSyntheticImport(text, file) { var externalHelpersModuleReference = ts.factory.createStringLiteral(text); - var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); + var importDecl = ts.factory.createImportDeclaration(/*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); ts.addEmitFlags(importDecl, 67108864 /* EmitFlags.NeverApplyImportHelper */); ts.setParent(externalHelpersModuleReference, importDecl); ts.setParent(importDecl, file); @@ -118103,13 +119706,16 @@ var ts; addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) { + var _a; var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; redirect.resolvedPath = resolvedPath; redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + redirect.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + redirect.packageJsonScope = sourceFileOptions.packageJsonScope; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { @@ -118138,14 +119744,14 @@ var ts; // It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache // and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way // to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront. - var impliedNodeFormat = getImpliedNodeFormatForFile(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); - return { - languageVersion: ts.getEmitScriptTarget(options), - impliedNodeFormat: impliedNodeFormat, - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(options) - }; + var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); + var languageVersion = ts.getEmitScriptTarget(options); + var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options); + return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) : + { languageVersion: languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator }; } function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { + var _a, _b; var path = toPath(fileName); if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(path); @@ -118232,14 +119838,15 @@ var ts; } } // We haven't looked for this file, do so now and cache result - var file = host.getSourceFile(fileName, getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options), function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile); + var sourceFileOptions = getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options); + var file = host.getSourceFile(fileName, sourceFileOptions, function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile || (((_a = oldProgram === null || oldProgram === void 0 ? void 0 : oldProgram.getSourceFileByPath(toPath(fileName))) === null || _a === void 0 ? void 0 : _a.impliedNodeFormat) !== sourceFileOptions.impliedNodeFormat)); if (packageId) { var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName, sourceFileOptions); redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, redirectedPath); addFileIncludeReason(dupFile, reason); @@ -118260,6 +119867,8 @@ var ts; file.path = path; file.resolvedPath = toPath(fileName); file.originalFileName = originalFileName; + file.packageJsonLocations = ((_b = sourceFileOptions.packageJsonLocations) === null || _b === void 0 ? void 0 : _b.length) ? sourceFileOptions.packageJsonLocations : undefined; + file.packageJsonScope = sourceFileOptions.packageJsonScope; addFileIncludeReason(file, reason); if (host.useCaseSensitiveFileNames()) { var pathLowerCase = ts.toFileNameLowerCase(path); @@ -118399,13 +120008,13 @@ var ts; ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); var mode = ref.resolutionMode || file.impliedNodeFormat; if (mode && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { - programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); + programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); } processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, }); } } function processTypeReferenceDirective(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -118890,7 +120499,7 @@ var ts; fileIncludeReasons = undefined; var location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason); var fileIncludeReasonDetails = fileIncludeReasons && ts.chainDiagnosticMessages(fileIncludeReasons, ts.Diagnostics.The_file_is_in_the_program_because_Colon); - var redirectInfo = file && ts.explainIfFileIsRedirect(file); + var redirectInfo = file && ts.explainIfFileIsRedirectAndImpliedFormat(file); var chain = ts.chainDiagnosticMessages.apply(void 0, __spreadArray([redirectInfo ? fileIncludeReasonDetails ? __spreadArray([fileIncludeReasonDetails], redirectInfo, true) : redirectInfo : fileIncludeReasonDetails, diagnostic], args || ts.emptyArray, false)); return location && isReferenceFileLocation(location) ? ts.createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : @@ -118960,7 +120569,7 @@ var ts; } var matchedByInclude = ts.getMatchedIncludeSpec(program, fileName); // Could be additional files specified as roots - if (!matchedByInclude) + if (!matchedByInclude || !ts.isString(matchedByInclude)) return undefined; configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude); message = ts.Diagnostics.File_is_matched_by_include_pattern_specified_here; @@ -119484,8 +121093,8 @@ var ts; (function (ts) { function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) { var outputFiles = []; - var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit; - return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; + var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics; + return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -119496,13 +121105,9 @@ var ts; function createManyToManyPathMap() { function create(forward, reverse, deleted) { var map = { - clone: function () { return create(new ts.Map(forward), new ts.Map(reverse), deleted && new ts.Set(deleted)); }, - forEach: function (fn) { return forward.forEach(fn); }, getKeys: function (v) { return reverse.get(v); }, getValues: function (k) { return forward.get(k); }, - hasKey: function (k) { return forward.has(k); }, keys: function () { return forward.keys(); }, - deletedKeys: function () { return deleted; }, deleteKey: function (k) { (deleted || (deleted = new ts.Set())).add(k); var set = forward.get(k); @@ -119529,11 +121134,6 @@ var ts; }); return map; }, - clear: function () { - forward.clear(); - reverse.clear(); - deleted === null || deleted === void 0 ? void 0 : deleted.clear(); - } }; return map; } @@ -119661,18 +121261,21 @@ var ts; * Creates the state of file references and signature for the new program from oldState if it is safe */ function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b, _c; var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? createManyToManyPathMap() : undefined; var exportedModulesMap = referencedMap ? createManyToManyPathMap() : undefined; - var hasCalledUpdateShapeSignature = new ts.Set(); var useOldState = canReuseOldState(referencedMap, oldState); // Ensure source files have parent pointers set newProgram.getTypeChecker(); // Create the reference map, and set the file infos - for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + for (var _i = 0, _d = newProgram.getSourceFiles(); _i < _d.length; _i++) { + var sourceFile = _d[_i]; var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); - var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined; + var oldUncommittedSignature = useOldState ? (_a = oldState.oldSignatures) === null || _a === void 0 ? void 0 : _a.get(sourceFile.resolvedPath) : undefined; + var signature = oldUncommittedSignature === undefined ? + useOldState ? (_b = oldState.fileInfos.get(sourceFile.resolvedPath)) === null || _b === void 0 ? void 0 : _b.signature : undefined : + oldUncommittedSignature || undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -119680,19 +121283,26 @@ var ts; } // Copy old visible to outside files map if (useOldState) { - var exportedModules = oldState.exportedModulesMap.getValues(sourceFile.resolvedPath); + var oldUncommittedExportedModules = (_c = oldState.oldExportedModulesMap) === null || _c === void 0 ? void 0 : _c.get(sourceFile.resolvedPath); + var exportedModules = oldUncommittedExportedModules === undefined ? + oldState.exportedModulesMap.getValues(sourceFile.resolvedPath) : + oldUncommittedExportedModules || undefined; if (exportedModules) { exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, impliedFormat: sourceFile.impliedNodeFormat }); + fileInfos.set(sourceFile.resolvedPath, { + version: version_2, + signature: signature, + affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, + impliedFormat: sourceFile.impliedNodeFormat + }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } @@ -119706,120 +121316,95 @@ var ts; } BuilderState.releaseCache = releaseCache; /** - * Creates a clone of the state + * Gets the files affected by the path from the program */ - function clone(state) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var _a, _b; - // Dont need to backup allFiles info since its cache anyway - return { - fileInfos: new ts.Map(state.fileInfos), - referencedMap: (_a = state.referencedMap) === null || _a === void 0 ? void 0 : _a.clone(), - exportedModulesMap: (_b = state.exportedModulesMap) === null || _b === void 0 ? void 0 : _b.clone(), - hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), - useFileVersionAsSignature: state.useFileVersionAsSignature, - }; + var result = getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); + return result; } - BuilderState.clone = clone; - /** - * Gets the files affected by the path from the program - */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { - // Since the operation could be cancelled, the signatures are always stored in the cache - // They will be committed once it is safe to use them - // eg when calling this api from tsserver, if there is no cancellation of the operation - // In the other cases the affected files signatures are committed only after the iteration through the result is complete - var signatureCache = cacheToUpdateSignature || new ts.Map(); + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var sourceFile = programOfThisState.getSourceFileByPath(path); if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); - if (!cacheToUpdateSignature) { - // Commit all the signatures in the signature cache - updateSignaturesFromCache(state, signatureCache); - } - return result; - } - BuilderState.getFilesAffectedBy = getFilesAffectedBy; - /** - * Updates the signatures from the cache into state's fileinfo signatures - * This should be called whenever it is safe to commit the state of the builder - */ - function updateSignaturesFromCache(state, signatureCache) { - signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); }); + return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName); } - BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + BuilderState.getFilesAffectedByWithOldState = getFilesAffectedByWithOldState; function updateSignatureOfFile(state, signature, path) { state.fileInfos.get(path).signature = signature; - state.hasCalledUpdateShapeSignature.add(path); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(path); } BuilderState.updateSignatureOfFile = updateSignatureOfFile; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache, useFileVersionAsSignature) { + function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName, useFileVersionAsSignature) { + var _a; if (useFileVersionAsSignature === void 0) { useFileVersionAsSignature = state.useFileVersionAsSignature; } - ts.Debug.assert(!!sourceFile); - ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) { + if ((_a = state.hasCalledUpdateShapeSignature) === null || _a === void 0 ? void 0 : _a.has(sourceFile.resolvedPath)) return false; - } var info = state.fileInfos.get(sourceFile.resolvedPath); - if (!info) - return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) { - var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, - /*emitOnlyDtsFiles*/ true, cancellationToken, + programOfThisState.emit(sourceFile, function (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) { + ts.Debug.assert(ts.isDeclarationFileName(fileName), "File extension for signature expected to be dts: Got:: ".concat(fileName)); + latestSignature = ts.computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data); + if (latestSignature !== prevSignature) { + updateExportedModules(state, sourceFile, sourceFiles[0].exportedModulesFromDeclarationEmit); + } + }, cancellationToken, + /*emitOnlyDtsFiles*/ true, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); - if (firstDts_1) { - ts.Debug.assert(ts.isDeclarationFileName(firstDts_1.name), "File extension for signature expected to be dts", function () { return "Found: ".concat(ts.getAnyExtensionFromPath(firstDts_1.name), " for ").concat(firstDts_1.name, ":: All output files: ").concat(JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; }))); }); - latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); - if (exportedModulesMapCache && latestSignature !== prevSignature) { - updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); - } - } } // Default is to use file version as signature if (latestSignature === undefined) { latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { + if (state.exportedModulesMap && latestSignature !== prevSignature) { + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); // All the references in this file are exported var references = state.referencedMap ? state.referencedMap.getValues(sourceFile.resolvedPath) : undefined; if (references) { - exportedModulesMapCache.set(sourceFile.resolvedPath, references); + state.exportedModulesMap.set(sourceFile.resolvedPath, references); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } } } - cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); + (state.oldSignatures || (state.oldSignatures = new ts.Map())).set(sourceFile.resolvedPath, prevSignature || false); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(sourceFile.resolvedPath); + info.signature = latestSignature; return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** * Coverts the declaration emit result into exported modules map */ - function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + function updateExportedModules(state, sourceFile, exportedModulesFromDeclarationEmit) { + if (!state.exportedModulesMap) + return; + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); if (!exportedModulesFromDeclarationEmit) { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); return; } var exportedModules; exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFilesFromImportedModuleSymbol(symbol)); }); if (exportedModules) { - exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules); + state.exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } function addExportedModule(exportedModulePaths) { if (exportedModulePaths === null || exportedModulePaths === void 0 ? void 0 : exportedModulePaths.length) { @@ -119831,19 +121416,6 @@ var ts; } } BuilderState.updateExportedModules = updateExportedModules; - /** - * Updates the exported modules from cache into state's exported modules map - * This should be called whenever it is safe to commit the state of the builder - */ - function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { - var _a; - if (exportedModulesMapCache) { - ts.Debug.assert(!!state.exportedModulesMap); - (_a = exportedModulesMapCache.deletedKeys()) === null || _a === void 0 ? void 0 : _a.forEach(function (path) { return state.exportedModulesMap.deleteKey(path); }); - exportedModulesMapCache.forEach(function (exportedModules, path) { return state.exportedModulesMap.set(path, exportedModules); }); - } - } - BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -119964,7 +121536,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cancellationToken, computeHash, getCanonicalFileName) { if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -119984,7 +121556,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, computeHash, getCanonicalFileName)) { queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } @@ -120010,32 +121582,33 @@ var ts; * Create the state so that we can iterate on changedFiles/affected files */ function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; + var outFilePath = ts.outFile(compilerOptions); // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them - if (!ts.outFile(compilerOptions)) { + if (!outFilePath) { state.semanticDiagnosticsPerFile = new ts.Map(); } + else if (compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.outSignature) && outFilePath === ts.outFile(oldState === null || oldState === void 0 ? void 0 : oldState.compilerOptions)) { + state.outSignature = oldState === null || oldState === void 0 ? void 0 : oldState.outSignature; + } state.changedFilesSet = new ts.Set(); + state.latestChangedDtsFile = compilerOptions.composite ? oldState === null || oldState === void 0 ? void 0 : oldState.latestChangedDtsFile : undefined; var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + var canCopyEmitSignatures = compilerOptions.composite && + (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && + !outFilePath && + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); if (useOldState) { - // Verify the sanity of old state - if (!oldState.currentChangedFilePath) { - var affectedSignatures = oldState.currentAffectedFilesSignatures; - ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); - } - var changedFilesSet = oldState.changedFilesSet; - if (canCopySemanticDiagnostics) { - ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); - } // Copy old state's changed files set - changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); }); - if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) { + (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); + if (!outFilePath && oldState.affectedFilesPendingEmit) { state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice(); state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind); state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; @@ -120056,6 +121629,8 @@ var ts; !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || // versions dont match oldInfo.version !== info.version || + // Implied formats dont match + oldInfo.impliedFormat !== info.impliedFormat || // Referenced files changed !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || // Referenced file was deleted in the new program @@ -120079,27 +121654,25 @@ var ts; state.semanticDiagnosticsFromOldState.add(sourceFilePath); } } + if (canCopyEmitSignatures) { + var oldEmitSignature = oldState.emitSignatures.get(sourceFilePath); + if (oldEmitSignature) + (state.emitSignatures || (state.emitSignatures = new ts.Map())).set(sourceFilePath, oldEmitSignature); + } }); // If the global file is removed, add all files as changed if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) { ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined) .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); }); } - else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { + else if (oldCompilerOptions && !outFilePath && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { // Add all files to affectedFilesPendingEmit since emit changed newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* BuilderFileEmit.Full */); }); ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set(); } - if (useOldState) { - // Any time the interpretation of a source file changes, mark it as changed - ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { - if (state.fileInfos.has(sourceFilePath) && state.fileInfos.get(sourceFilePath).impliedFormat !== info.impliedFormat) { - state.changedFilesSet.add(sourceFilePath); - } - }); - } - state.buildInfoEmitPending = !!state.changedFilesSet.size; + // Since old states change files set is copied, any additional change means we would need to emit build info + state.buildInfoEmitPending = !useOldState || state.changedFilesSet.size !== (((_b = oldState.changedFilesSet) === null || _b === void 0 ? void 0 : _b.size) || 0); return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -120135,30 +121708,35 @@ var ts; ts.BuilderState.releaseCache(state); state.program = undefined; } - /** - * Creates a clone of the state - */ - function cloneBuilderProgramState(state) { - var _a; - var newState = ts.BuilderState.clone(state); - newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile); - newState.changedFilesSet = new ts.Set(state.changedFilesSet); - newState.affectedFiles = state.affectedFiles; - newState.affectedFilesIndex = state.affectedFilesIndex; - newState.currentChangedFilePath = state.currentChangedFilePath; - newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures); - newState.currentAffectedFilesExportedModulesMap = (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clone(); - newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles); - newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; - newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState); - newState.program = state.program; - newState.compilerOptions = state.compilerOptions; - newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(); - newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind); - newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; - newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles); - newState.programEmitComplete = state.programEmitComplete; - return newState; + function backupBuilderProgramEmitState(state) { + var outFilePath = ts.outFile(state.compilerOptions); + // Only in --out changeFileSet is kept around till emit + ts.Debug.assert(!state.changedFilesSet.size || outFilePath); + return { + affectedFilesPendingEmit: state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(), + affectedFilesPendingEmitKind: state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind), + affectedFilesPendingEmitIndex: state.affectedFilesPendingEmitIndex, + seenEmittedFiles: state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles), + programEmitComplete: state.programEmitComplete, + emitSignatures: state.emitSignatures && new ts.Map(state.emitSignatures), + outSignature: state.outSignature, + latestChangedDtsFile: state.latestChangedDtsFile, + hasChangedEmitSignature: state.hasChangedEmitSignature, + changedFilesSet: outFilePath ? new ts.Set(state.changedFilesSet) : undefined, + }; + } + function restoreBuilderProgramEmitState(state, savedEmitState) { + state.affectedFilesPendingEmit = savedEmitState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitKind = savedEmitState.affectedFilesPendingEmitKind; + state.affectedFilesPendingEmitIndex = savedEmitState.affectedFilesPendingEmitIndex; + state.seenEmittedFiles = savedEmitState.seenEmittedFiles; + state.programEmitComplete = savedEmitState.programEmitComplete; + state.emitSignatures = savedEmitState.emitSignatures; + state.outSignature = savedEmitState.outSignature; + state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile; + state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; + if (savedEmitState.changedFilesSet) + state.changedFilesSet = savedEmitState.changedFilesSet; } /** * Verifies that source file is ok to be used in calls that arent handled by next @@ -120172,8 +121750,8 @@ var ts; * This is to allow the callers to be able to actually remove affected file only when the operation is complete * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained */ - function getNextAffectedFile(state, cancellationToken, computeHash, host) { - var _a; + function getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { @@ -120184,7 +121762,7 @@ var ts; if (!seenAffectedFiles.has(affectedFile.resolvedPath)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); return affectedFile; } affectedFilesIndex++; @@ -120193,10 +121771,8 @@ var ts; state.changedFilesSet.delete(state.currentChangedFilePath); state.currentChangedFilePath = undefined; // Commit the changes in file signature - ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); - state.currentAffectedFilesSignatures.clear(); - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); - (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clear(); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); state.affectedFiles = undefined; } // Get next changed file @@ -120214,12 +121790,7 @@ var ts; return program; } // Get next batch of affected files - if (!state.currentAffectedFilesSignatures) - state.currentAffectedFilesSignatures = new ts.Map(); - if (state.exportedModulesMap) { - state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap()); - } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedByWithOldState(state, program, nextKey.value, cancellationToken, computeHash, getCanonicalFileName); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; if (!state.seenAffectedFiles) @@ -120270,8 +121841,7 @@ var ts; * Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ - function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -120279,19 +121849,18 @@ var ts; // When a change affects the global scope, all files are considered to be affected without updating their signature // That means when affected file is handled, its signature can be out of date // To avoid this, ensure that we update the signature for any affected file in this scenario. - ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, cancellationToken, computeHash, getCanonicalFileName); return; } - ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: ".concat(affectedFile.fileName)); if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; - handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); } /** * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled, * Also we need to make sure signature is updated for these files */ - function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, host) { + function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { var program = ts.Debug.checkDefined(state.program); @@ -120302,7 +121871,7 @@ var ts; // This ensures that we dont later during incremental builds considering wrong signature. // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build // But we avoid expensive full shape computation, as using file version as shape is enough for correctness. - ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap, !host.disableUseFileVersionAsSignature); + ts.BuilderState.updateShapeSignature(state, program, sourceFile, cancellationToken, computeHash, getCanonicalFileName, !host.disableUseFileVersionAsSignature); // If not dts emit, nothing more to do if (ts.getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, 0 /* BuilderFileEmit.DtsOnly */); @@ -120323,41 +121892,25 @@ var ts; return !state.semanticDiagnosticsFromOldState.size; } function isChangedSignature(state, path) { - var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path); - var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; + var oldSignature = ts.Debug.checkDefined(state.oldSignatures).get(path) || undefined; + var newSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; return newSignature !== oldSignature; } - function forEachKeyOfExportedModulesMap(state, filePath, fn) { - // Go through exported modules from cache first - var keys = state.currentAffectedFilesExportedModulesMap.getKeys(filePath); - var result = keys && ts.forEachKey(keys, fn); - if (result) - return result; - // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - keys = state.exportedModulesMap.getKeys(filePath); - return keys && ts.forEachKey(keys, function (exportedFromPath) { - var _a; - // If the cache had an updated value, skip - return !state.currentAffectedFilesExportedModulesMap.hasKey(exportedFromPath) && - !((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(exportedFromPath)) ? - fn(exportedFromPath) : - undefined; - }); - } - function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host) { var _a; if (!((_a = state.fileInfos.get(filePath)) === null || _a === void 0 ? void 0 : _a.affectsGlobalScope)) return false; // Every file needs to be handled ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, state.program, /*firstSourceFile*/ undefined) - .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, host); }); + .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, getCanonicalFileName, host); }); removeDiagnosticsOfLibraryFiles(state); return true; } /** * Iterate on referencing modules that export entities from affected file and delete diagnostics and add pending emit */ - function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a; // If there was change in signature (dts output) for the changed file, // then only we need to handle pending file emit if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) @@ -120374,9 +121927,9 @@ var ts; var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { seenFileNamesMap.set(currentPath, true); - if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host)) return; - handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, host); + handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host); if (isChangedSignature(state, currentPath)) { var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath); queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); @@ -120384,16 +121937,15 @@ var ts; } } } - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); var seenFileAndExportsOfFile = new ts.Set(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, affectedFile.resolvedPath, function (exportedFromPath) { - if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, host)) + (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; var references = state.referencedMap.getKeys(exportedFromPath); return references && ts.forEachKey(references, function (filePath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); }); } @@ -120401,23 +121953,22 @@ var ts; * handle dts and semantic diagnostics on file and iterate on anything that exports this file * return true when all work is done and we can exit handling dts emit and semantic diagnostics */ - function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) return undefined; - if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; - handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, host); - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host); // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, filePath, function (exportedFromPath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + (_a = state.exportedModulesMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); // Remove diagnostics of files that import this file (without going to exports of referencing files) - (_a = state.referencedMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (referencingFilePath) { + (_b = state.referencedMap.getKeys(filePath)) === null || _b === void 0 ? void 0 : _b.forEach(function (referencingFilePath) { return !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file handleDtsMayChangeOf(// Dont add to seen since this is not yet done with the export removal - state, referencingFilePath, cancellationToken, computeHash, host); + state, referencingFilePath, cancellationToken, computeHash, getCanonicalFileName, host); }); return undefined; } @@ -120435,12 +121986,13 @@ var ts; } else { state.seenAffectedFiles.add(affected.resolvedPath); + // Change in changeSet/affectedFilesPendingEmit, buildInfo needs to be emitted + state.buildInfoEmitPending = true; if (emitKind !== undefined) { (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind); } if (isPendingEmit) { state.affectedFilesPendingEmitIndex++; - state.buildInfoEmitPending = true; } else { state.affectedFilesIndex++; @@ -120488,25 +122040,62 @@ var ts; } return ts.filterSemanticDiagnostics(diagnostics, state.compilerOptions); } + function isProgramBundleEmitBuildInfo(info) { + return !!ts.outFile(info.options || {}); + } + ts.isProgramBundleEmitBuildInfo = isProgramBundleEmitBuildInfo; /** * Gets the program information to be emitted in buildInfo so that we can use it to create new program */ function getProgramBuildInfo(state, getCanonicalFileName) { - if (ts.outFile(state.compilerOptions)) - return undefined; + var outFilePath = ts.outFile(state.compilerOptions); + if (outFilePath && !state.compilerOptions.composite) + return; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); + // Convert the file name to Path here if we set the fileName instead to optimize multiple d.ts file emits and having to compute Canonical path + var latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : undefined; + if (outFilePath) { + var fileNames_1 = []; + var fileInfos_1 = []; + state.program.getRootFileNames().forEach(function (f) { + var sourceFile = state.program.getSourceFile(f); + if (!sourceFile) + return; + fileNames_1.push(relativeToBuildInfo(sourceFile.resolvedPath)); + fileInfos_1.push(sourceFile.version); + }); + var result_15 = { + fileNames: fileNames_1, + fileInfos: fileInfos_1, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsBundleEmitBuildInfo"), + outSignature: state.outSignature, + latestChangedDtsFile: latestChangedDtsFile, + }; + return result_15; + } var fileNames = []; var fileNameToFileId = new ts.Map(); var fileIdsList; var fileNamesToFileIdListId; + var emitSignatures; var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var _b, _c; var key = _a[0], value = _a[1]; // Ensure fileId var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); - var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + var oldSignature = (_b = state.oldSignatures) === null || _b === void 0 ? void 0 : _b.get(key); + var actualSignature = oldSignature !== undefined ? oldSignature || undefined : value.signature; + if (state.compilerOptions.composite) { + var file = state.program.getSourceFileByPath(key); + if (!ts.isJsonSourceFile(file) && ts.sourceFileMayBeEmitted(file, state.program)) { + var emitSignature = (_c = state.emitSignatures) === null || _c === void 0 ? void 0 : _c.get(key); + if (emitSignature !== actualSignature) { + (emitSignatures || (emitSignatures = [])).push(emitSignature === undefined ? fileId : [fileId, emitSignature]); + } + } + } return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? // If file version is same as signature, dont serialize signature @@ -120514,11 +122103,11 @@ var ts; // If file info only contains version and signature and both are same we can just write string value.version : actualSignature !== undefined ? // If signature is not same as version, encode signature in the fileInfo - signature === undefined ? + oldSignature === undefined ? // If we havent computed signature, use fileInfo as is value : // Serialize fileInfo with new updated signature - { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : + { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : // Signature of the FileInfo is undefined, serialize it as false { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }; }); @@ -120533,17 +122122,13 @@ var ts; if (state.exportedModulesMap) { exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var _a; - if (state.currentAffectedFilesExportedModulesMap) { - if ((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(key)) { - return undefined; - } - var newValue = state.currentAffectedFilesExportedModulesMap.getValues(key); - if (newValue) { - return [toFileId(key), toFileIdListId(newValue)]; - } - } + var oldValue = (_a = state.oldExportedModulesMap) === null || _a === void 0 ? void 0 : _a.get(key); // Not in temporary cache, use existing value - return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue === undefined) + return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue) + return [toFileId(key), toFileIdListId(oldValue)]; + return undefined; }); } var semanticDiagnosticsPerFile; @@ -120554,9 +122139,7 @@ var ts; (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ toFileId(key), - state.hasReusableDiagnostic ? - value : - convertToReusableDiagnostics(value, relativeToBuildInfo) + convertToReusableDiagnostics(value, relativeToBuildInfo) ] : toFileId(key)); } @@ -120571,16 +122154,27 @@ var ts; } } } - return { + var changeFileSet; + if (state.changedFilesSet.size) { + for (var _d = 0, _e = ts.arrayFrom(state.changedFilesSet.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { + var path = _e[_d]; + (changeFileSet || (changeFileSet = [])).push(toFileId(path)); + } + } + var result = { fileNames: fileNames, fileInfos: fileInfos, - options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsMultiFileEmitBuildInfo"), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, affectedFilesPendingEmit: affectedFilesPendingEmit, + changeFileSet: changeFileSet, + emitSignatures: emitSignatures, + latestChangedDtsFile: latestChangedDtsFile, }; + return result; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } @@ -120605,24 +122199,21 @@ var ts; } return fileIdListId; } - } - function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { - var result; - var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var name = _a[_i]; - var optionKey = name.toLowerCase(); - var optionInfo = optionsNameMap.get(optionKey); - if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || - // We need to store `strict`, even though it won't be examined directly, so that the - // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly from the buildinfo - optionKey === "strict" || - // We need to store these to determine whether `lib` files need to be rechecked. - optionKey === "skiplibcheck" || optionKey === "skipdefaultlibcheck") { - (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); + /** + * @param optionKey key of CommandLineOption to use to determine if the option should be serialized in tsbuildinfo + */ + function convertToProgramBuildInfoCompilerOptions(options, optionKey) { + var result; + var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo[optionKey]) { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfoEnsuringAbsolutePath); + } } + return result; } - return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { if (option) { @@ -120696,6 +122287,41 @@ var ts; return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; } ts.getBuilderCreationParameters = getBuilderCreationParameters; + function getTextHandlingSourceMapForSignature(text, data) { + return (data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text; + } + function computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data) { + var _a; + text = getTextHandlingSourceMapForSignature(text, data); + var sourceFileDirectory; + if ((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length) { + text += data.diagnostics.map(function (diagnostic) { + return "".concat(locationInfo(diagnostic)).concat(ts.DiagnosticCategory[diagnostic.category]).concat(diagnostic.code, ": ").concat(flattenDiagnosticMessageText(diagnostic.messageText)); + }).join("\n"); + } + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(text); + function flattenDiagnosticMessageText(diagnostic) { + return ts.isString(diagnostic) ? + diagnostic : + diagnostic === undefined ? + "" : + !diagnostic.next ? + diagnostic.messageText : + diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText).join("\n"); + } + function locationInfo(diagnostic) { + if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) + return "(".concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + if (sourceFileDirectory === undefined) + sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath); + return "".concat(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceFileDirectory, diagnostic.file.resolvedPath, getCanonicalFileName)), "(").concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + } + } + ts.computeSignatureWithDiagnostics = computeSignatureWithDiagnostics; + function computeSignature(text, computeHash, data) { + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); + } + ts.computeSignature = computeSignature; function createBuilderProgram(kind, _a) { var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; // Return same program if underlying program doesnt change @@ -120714,7 +122340,6 @@ var ts; */ var computeHash = ts.maybeBind(host, host.createHash); var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); - var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 @@ -120723,21 +122348,13 @@ var ts; var getState = function () { return state; }; var builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics); builderProgram.getState = getState; - builderProgram.backupState = function () { - ts.Debug.assert(backupState === undefined); - backupState = cloneBuilderProgramState(state); - }; - builderProgram.restoreState = function () { - state = ts.Debug.checkDefined(backupState); - backupState = undefined; - }; + builderProgram.saveEmitState = function () { return backupBuilderProgramEmitState(state); }; + builderProgram.restoreEmitState = function (saved) { return restoreBuilderProgramEmitState(state, saved); }; + builderProgram.hasChangedEmitSignature = function () { return !!state.hasChangedEmitSignature; }; builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); }; builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; builderProgram.emit = emit; - builderProgram.releaseProgram = function () { - releaseCache(state); - backupState = undefined; - }; + builderProgram.releaseProgram = function () { return releaseCache(state); }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; } @@ -120764,7 +122381,7 @@ var ts; * in that order would be used to write the files */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); var emitKind = 1 /* BuilderFileEmit.Full */; var isPendingEmitFile = false; if (!affected) { @@ -120795,34 +122412,68 @@ var ts; return toAffectedFileEmitResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, affected !== state.program && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* BuilderFileEmit.DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile); } - function getWriteFileUpdatingSignatureCallback(writeFile) { + function getWriteFileCallback(writeFile, customTransformers) { return function (fileName, text, writeByteOrderMark, onError, sourceFiles, data) { - var _a; + var _a, _b, _c, _d, _e, _f, _g; if (ts.isDeclarationFileName(fileName)) { - ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); - var file = sourceFiles[0]; - var info = state.fileInfos.get(file.resolvedPath); - var signature = ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.get(file.resolvedPath)) || info.signature; - if (signature === file.version) { - var newSignature = (computeHash || ts.generateDjb2Hash)((data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text); - if (newSignature !== file.version) { // Update it - if (host.storeFilesChangingSignatureDuringEmit) - (state.filesChangingSignature || (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); - if (state.exportedModulesMap) - ts.BuilderState.updateExportedModules(file, file.exportedModulesFromDeclarationEmit, state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap())); - if (state.affectedFiles && state.affectedFilesIndex < state.affectedFiles.length) { - state.currentAffectedFilesSignatures.set(file.resolvedPath, newSignature); - } - else { - info.signature = newSignature; - if (state.exportedModulesMap) - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + if (!ts.outFile(state.compilerOptions)) { + ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); + var emitSignature = void 0; + if (!customTransformers) { + var file = sourceFiles[0]; + var info = state.fileInfos.get(file.resolvedPath); + if (info.signature === file.version) { + var signature = computeSignatureWithDiagnostics(file, text, computeHash, getCanonicalFileName, data); + // With d.ts diagnostics they are also part of the signature so emitSignature will be different from it since its just hash of d.ts + if (!((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length)) + emitSignature = signature; + if (signature !== file.version) { // Update it + if (host.storeFilesChangingSignatureDuringEmit) + ((_b = state.filesChangingSignature) !== null && _b !== void 0 ? _b : (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); + if (state.exportedModulesMap) + ts.BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit); + if (state.affectedFiles) { + // Keep old signature so we know what to undo if cancellation happens + var existing = (_c = state.oldSignatures) === null || _c === void 0 ? void 0 : _c.get(file.resolvedPath); + if (existing === undefined) + ((_d = state.oldSignatures) !== null && _d !== void 0 ? _d : (state.oldSignatures = new ts.Map())).set(file.resolvedPath, info.signature || false); + info.signature = signature; + } + else { + // These are directly commited + info.signature = signature; + (_e = state.oldExportedModulesMap) === null || _e === void 0 ? void 0 : _e.clear(); + } + } } } + // Store d.ts emit hash so later can be compared to check if d.ts has changed. + // Currently we do this only for composite projects since these are the only projects that can be referenced by other projects + // and would need their d.ts change time in --build mode + if (state.compilerOptions.composite) { + var filePath = sourceFiles[0].resolvedPath; + var oldSignature = (_f = state.emitSignatures) === null || _f === void 0 ? void 0 : _f.get(filePath); + emitSignature !== null && emitSignature !== void 0 ? emitSignature : (emitSignature = computeSignature(text, computeHash, data)); + // Dont write dts files if they didn't change + if (emitSignature === oldSignature) + return; + ((_g = state.emitSignatures) !== null && _g !== void 0 ? _g : (state.emitSignatures = new ts.Map())).set(filePath, emitSignature); + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; + } + } + else if (state.compilerOptions.composite) { + var newSignature = computeSignature(text, computeHash, data); + // Dont write dts files if they didn't change + if (newSignature === state.outSignature) + return; + state.outSignature = newSignature; + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; } } if (writeFile) @@ -120888,8 +122539,8 @@ var ts; } } } - return ts.Debug.checkDefined(state.program).emit(targetSourceFile, !ts.outFile(state.compilerOptions) && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + return ts.Debug.checkDefined(state.program).emit(targetSourceFile, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers); } /** @@ -120898,7 +122549,7 @@ var ts; */ function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { while (true) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); if (!affected) { // Done return undefined; @@ -120978,29 +122629,59 @@ var ts; { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; } ts.toBuilderStateFileInfo = toBuilderStateFileInfo; - function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { - var _a; + function createBuilderProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a, _b, _c, _d; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var filePaths = program.fileNames.map(toPath); - var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); - var fileInfos = new ts.Map(); - program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); - var state = { - fileInfos: fileInfos, - compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, - referencedMap: toManyToManyPathMap(program.referencedMap), - exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), - hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), - affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, - }; + var state; + var filePaths; + var filePathsSetList; + var latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : undefined; + if (isProgramBundleEmitBuildInfo(program)) { + state = { + fileInfos: new ts.Map(), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + latestChangedDtsFile: latestChangedDtsFile, + outSignature: program.outSignature, + }; + } + else { + filePaths = (_a = program.fileNames) === null || _a === void 0 ? void 0 : _a.map(toPath); + filePathsSetList = (_b = program.fileIdsList) === null || _b === void 0 ? void 0 : _b.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); + var fileInfos_2 = new ts.Map(); + var emitSignatures_1 = ((_c = program.options) === null || _c === void 0 ? void 0 : _c.composite) && !ts.outFile(program.options) ? new ts.Map() : undefined; + program.fileInfos.forEach(function (fileInfo, index) { + var path = toFilePath(index + 1); + var stateFileInfo = toBuilderStateFileInfo(fileInfo); + fileInfos_2.set(path, stateFileInfo); + if (emitSignatures_1 && stateFileInfo.signature) + emitSignatures_1.set(path, stateFileInfo.signature); + }); + (_d = program.emitSignatures) === null || _d === void 0 ? void 0 : _d.forEach(function (value) { + if (ts.isNumber(value)) + emitSignatures_1.delete(toFilePath(value)); + else + emitSignatures_1.set(toFilePath(value[0]), value[1]); + }); + state = { + fileInfos: fileInfos_2, + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toManyToManyPathMap(program.referencedMap), + exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), + hasReusableDiagnostic: true, + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, + changedFilesSet: new ts.Set(ts.map(program.changeFileSet, toFilePath)), + latestChangedDtsFile: latestChangedDtsFile, + emitSignatures: (emitSignatures_1 === null || emitSignatures_1 === void 0 ? void 0 : emitSignatures_1.size) ? emitSignatures_1 : undefined, + }; + } return { getState: function () { return state; }, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: ts.notImplemented, getProgramOrUndefined: ts.returnUndefined, releaseProgram: ts.noop, @@ -121020,6 +122701,7 @@ var ts; getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented, emitBuildInfo: ts.notImplemented, close: ts.noop, + hasChangedEmitSignature: ts.returnFalse, }; function toPath(path) { return ts.toPath(path, buildInfoDirectory, getCanonicalFileName); @@ -121045,12 +122727,24 @@ var ts; return map; } } - ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; + ts.createBuilderProgramUsingProgramBuildInfo = createBuilderProgramUsingProgramBuildInfo; + function getBuildInfoFileVersionMap(program, buildInfoPath, host) { + var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var fileInfos = new ts.Map(); + program.fileInfos.forEach(function (fileInfo, index) { + var path = ts.toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName); + var version = ts.isString(fileInfo) ? fileInfo : fileInfo.version; // eslint-disable-line @typescript-eslint/no-unnecessary-type-assertion + fileInfos.set(path, version); + }); + return fileInfos; + } + ts.getBuildInfoFileVersionMap = getBuildInfoFileVersionMap; function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { return { getState: ts.notImplemented, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: getProgram, getProgramOrUndefined: function () { return getState().program; }, releaseProgram: function () { return getState().program = undefined; }, @@ -121110,7 +122804,7 @@ var ts; * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" * @param dirPath */ - function canWatchDirectory(dirPath) { + function canWatchDirectoryOrFile(dirPath) { var rootLength = ts.getRootLength(dirPath); if (dirPath.length === rootLength) { // Ignore "/", "c:/" @@ -121147,15 +122841,19 @@ var ts; } return true; } - ts.canWatchDirectory = canWatchDirectory; + ts.canWatchDirectoryOrFile = canWatchDirectoryOrFile; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var resolutionsWithFailedLookups = []; + var resolutionsWithOnlyAffectingLocations = []; var resolvedFileToResolution = ts.createMultiMap(); + var impliedFormatPackageJsons = new ts.Map(); var hasChangedAutomaticTypeDirectiveNames = false; + var affectingPathChecksForFile; + var affectingPathChecks; var failedLookupChecks; var startsWithPathChecks; var isInDirectoryChecks; @@ -121182,6 +122880,7 @@ var ts; var failedLookupDefaultExtensions = [".ts" /* Extension.Ts */, ".tsx" /* Extension.Tsx */, ".js" /* Extension.Js */, ".jsx" /* Extension.Jsx */, ".json" /* Extension.Json */]; var customFailedLookupPaths = new ts.Map(); var directoryWatchesOfFailedLookups = new ts.Map(); + var fileWatchesOfAffectingLocations = new ts.Map(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0; @@ -121193,7 +122892,7 @@ var ts; finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + startCachingPerDirectoryResolution: startCachingPerDirectoryResolution, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -121224,6 +122923,7 @@ var ts; } function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + ts.clearMap(fileWatchesOfAffectingLocations, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); @@ -121231,12 +122931,15 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; + resolutionsWithOnlyAffectingLocations.length = 0; failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; - // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update - // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - clearPerDirectoryResolutions(); + affectingPathChecks = undefined; + affectingPathChecksForFile = undefined; + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); + impliedFormatPackageJsons.clear(); hasChangedAutomaticTypeDirectiveNames = false; } function startRecordingFilesWithChangedResolutions() { @@ -121268,25 +122971,60 @@ var ts; return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } - function clearPerDirectoryResolutions() { - moduleResolutionCache.clear(); - typeReferenceDirectiveResolutionCache.clear(); + function startCachingPerDirectoryResolution() { + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } - function finishCachingPerDirectoryResolution() { + function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = undefined; - clearPerDirectoryResolutions(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + // Update file watches + if (newProgram !== oldProgram) { + newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFiles().forEach(function (newFile) { + var _a, _b, _c; + var expected = ts.isExternalOrCommonJsModule(newFile) ? (_b = (_a = newFile.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0 : 0; + var existing = (_c = impliedFormatPackageJsons.get(newFile.path)) !== null && _c !== void 0 ? _c : ts.emptyArray; + for (var i = existing.length; i < expected; i++) { + createFileWatcherOfAffectingLocation(newFile.packageJsonLocations[i], /*forResolution*/ false); + } + if (existing.length > expected) { + for (var i = expected; i < existing.length; i++) { + fileWatchesOfAffectingLocations.get(existing[i]).files--; + } + } + if (expected) + impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations); + else + impliedFormatPackageJsons.delete(newFile.path); + }); + impliedFormatPackageJsons.forEach(function (existing, path) { + if (!(newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFileByPath(path))) { + existing.forEach(function (location) { return fileWatchesOfAffectingLocations.get(location).files--; }); + impliedFormatPackageJsons.delete(path); + } + }); + } directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); + fileWatchesOfAffectingLocations.forEach(function (watcher, path) { + if (watcher.files === 0 && watcher.resolutions === 0) { + fileWatchesOfAffectingLocations.delete(path); + watcher.watcher.close(); + } + }); hasChangedAutomaticTypeDirectiveNames = false; } function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference, _containingSourceFile, mode) { - var _a; + var _a, _b; var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { @@ -121297,11 +123035,12 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _c = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _c.resolvedModule, failedLookupLocations = _c.failedLookupLocations, affectingLocations = _c.affectingLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = primaryResult.affectingLocations).push.apply(_b, affectingLocations); return primaryResult; } } @@ -121506,7 +123245,7 @@ var ts; } // If the directory is node_modules use it to watch, always watch it recursively if (ts.isNodeModulesDirectory(dirPath)) { - return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + return canWatchDirectoryOrFile(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -121524,7 +123263,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + return canWatchDirectoryOrFile(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -121552,10 +123291,11 @@ var ts; } function watchFailedLookupLocationOfResolution(resolution) { ts.Debug.assert(!!resolution.refCount); - var failedLookupLocations = resolution.failedLookupLocations; - if (!failedLookupLocations.length) + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (!failedLookupLocations.length && !affectingLocations.length) return; - resolutionsWithFailedLookups.push(resolution); + if (failedLookupLocations.length) + resolutionsWithFailedLookups.push(resolution); var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; @@ -121582,12 +123322,87 @@ var ts; // This is always non recursive setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } + watchAffectingLocationsOfResolution(resolution, !failedLookupLocations.length); + } + function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { + ts.Debug.assert(!!resolution.refCount); + var affectingLocations = resolution.affectingLocations; + if (!affectingLocations.length) + return; + if (addToResolutionsWithOnlyAffectingLocations) + resolutionsWithOnlyAffectingLocations.push(resolution); + // Watch package json + for (var _i = 0, affectingLocations_1 = affectingLocations; _i < affectingLocations_1.length; _i++) { + var affectingLocation = affectingLocations_1[_i]; + createFileWatcherOfAffectingLocation(affectingLocation, /*forResolution*/ true); + } + } + function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) { + var fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation); + if (fileWatcher) { + if (forResolution) + fileWatcher.resolutions++; + else + fileWatcher.files++; + return; + } + var locationToWatch = affectingLocation; + if (resolutionHost.realpath) { + locationToWatch = resolutionHost.realpath(affectingLocation); + if (affectingLocation !== locationToWatch) { + var fileWatcher_1 = fileWatchesOfAffectingLocations.get(locationToWatch); + if (fileWatcher_1) { + if (forResolution) + fileWatcher_1.resolutions++; + else + fileWatcher_1.files++; + fileWatcher_1.paths.add(affectingLocation); + fileWatchesOfAffectingLocations.set(affectingLocation, fileWatcher_1); + return; + } + } + } + var paths = new ts.Set(); + paths.add(locationToWatch); + var actualWatcher = canWatchDirectoryOrFile(resolutionHost.toPath(locationToWatch)) ? + resolutionHost.watchAffectingFileLocation(locationToWatch, function (fileName, eventKind) { + cachedDirectoryStructureHost === null || cachedDirectoryStructureHost === void 0 ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + paths.forEach(function (path) { + if (watcher.resolutions) + (affectingPathChecks !== null && affectingPathChecks !== void 0 ? affectingPathChecks : (affectingPathChecks = new ts.Set())).add(path); + if (watcher.files) + (affectingPathChecksForFile !== null && affectingPathChecksForFile !== void 0 ? affectingPathChecksForFile : (affectingPathChecksForFile = new ts.Set())).add(path); + packageJsonMap === null || packageJsonMap === void 0 ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); + }); + resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); + }) : ts.noopFileWatcher; + var watcher = { + watcher: actualWatcher !== ts.noopFileWatcher ? { + close: function () { + actualWatcher.close(); + // Ensure when watching symlinked package.json, we can close the actual file watcher only once + actualWatcher = ts.noopFileWatcher; + } + } : actualWatcher, + resolutions: forResolution ? 1 : 0, + files: forResolution ? 0 : 1, + paths: paths, + }; + fileWatchesOfAffectingLocations.set(locationToWatch, watcher); + if (affectingLocation !== locationToWatch) { + fileWatchesOfAffectingLocations.set(affectingLocation, watcher); + paths.add(affectingLocation); + } } function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { var program = resolutionHost.getCurrentProgram(); if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) { resolutions.forEach(watchFailedLookupLocationOfResolution); } + else { + resolutions.forEach(function (resolution) { return watchAffectingLocationsOfResolution(resolution, /*addToResolutionWithOnlyAffectingLocations*/ true); }); + } } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); @@ -121609,38 +123424,44 @@ var ts; if (resolved && resolved.resolvedFileName) { resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution); } - if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { - // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups - return; - } - var failedLookupLocations = resolution.failedLookupLocations; - var removeAtRoot = false; - for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { - var failedLookupLocation = failedLookupLocations_2[_i]; - var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (toWatch) { - var dirPath = toWatch.dirPath; - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - if (dirPath === rootPath) { - removeAtRoot = true; - } - else { - removeDirectoryWatcher(dirPath); - } } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + else if (affectingLocations.length) { + ts.unorderedRemoveItem(resolutionsWithOnlyAffectingLocations, resolution); } - if (removeAtRoot) { - removeDirectoryWatcher(rootPath); + for (var _a = 0, affectingLocations_2 = affectingLocations; _a < affectingLocations_2.length; _a++) { + var affectingLocation = affectingLocations_2[_a]; + var watcher = fileWatchesOfAffectingLocations.get(affectingLocation); + watcher.resolutions--; } } function removeDirectoryWatcher(dirPath) { @@ -121694,7 +123515,7 @@ var ts; resolution.isInvalidated = invalidated = true; for (var _a = 0, _b = ts.Debug.checkDefined(resolution.files); _a < _b.length; _a++) { var containingFilePath = _b[_a]; - (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); // When its a file with inferred types resolution, invalidate type reference directive resolution hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile); } @@ -121719,7 +123540,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = new ts.Set())).add(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -121737,7 +123558,7 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { @@ -121749,7 +123570,7 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); // If the invalidated file is from a node_modules package, invalidate everything else // in the package since we might not get notifications for other files in the package. // This hardens our logic against unreliable file watchers. @@ -121761,22 +123582,46 @@ var ts; resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { - return false; + var _a; + var invalidated = false; + if (affectingPathChecksForFile) { + (_a = resolutionHost.getCurrentProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFiles().forEach(function (f) { + if (ts.some(f.packageJsonLocations, function (location) { return affectingPathChecksForFile.has(location); })) { + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(f.path); + invalidated = true; + } + }); + affectingPathChecksForFile = undefined; + } + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks && !affectingPathChecks) { + return invalidated; + } + invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach(function (_value, path) { return isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : undefined; }); } - var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; + invalidated = invalidateResolutions(resolutionsWithOnlyAffectingLocations, canInvalidatedFailedLookupResolutionWithAffectingLocation) || invalidated; + affectingPathChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { - return resolution.failedLookupLocations.some(function (location) { - var locationPath = resolutionHost.toPath(location); - return ts.contains(failedLookupChecks, locationPath) || - ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || - (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); - }); + if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) + return true; + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) + return false; + return resolution.failedLookupLocations.some(function (location) { return isInvalidatedFailedLookup(resolutionHost.toPath(location)); }); + } + function isInvalidatedFailedLookup(locationPath) { + return (failedLookupChecks === null || failedLookupChecks === void 0 ? void 0 : failedLookupChecks.has(locationPath)) || + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + ts.firstDefinedIterator((isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath) ? true : undefined; }); + } + function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) { + return !!affectingPathChecks && resolution.affectingLocations.some(function (location) { return affectingPathChecks.has(location); }); } function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); @@ -121842,7 +123687,7 @@ var ts; function directoryExistsForTypeRootWatch(nodeTypesDirectory) { var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); var dirPath = resolutionHost.toPath(dir); - return dirPath === rootPath || canWatchDirectory(dirPath); + return dirPath === rootPath || canWatchDirectoryOrFile(dirPath); } } ts.createResolutionCache = createResolutionCache; @@ -121953,7 +123798,7 @@ var ts; var info = getInfo(importingSourceFileName, host); var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences, options); return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode); }) || - getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences); + getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences, options) { if (options === void 0) { options = {}; } @@ -122036,7 +123881,7 @@ var ts; return nodeModulesSpecifiers; } if (!specifier && !modulePath.isRedirect) { - var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences); + var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); if (ts.pathIsBareSpecifier(local)) { pathsSpecifiers = ts.append(pathsSpecifiers, local); } @@ -122064,7 +123909,7 @@ var ts; var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); return { getCanonicalFileName: getCanonicalFileName, importingSourceFileName: importingSourceFileName, sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, _a) { + function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, _a) { var ending = _a.ending, relativePreference = _a.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var sourceDirectory = info.sourceDirectory, getCanonicalFileName = info.getCanonicalFileName; @@ -122078,9 +123923,8 @@ var ts; if (!relativeToBaseUrl) { return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); - var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths; + var fromPaths = paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, getAllowedEndings(ending, compilerOptions, importMode), host, compilerOptions); + var nonRelative = fromPaths === undefined && baseUrl !== undefined ? removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) : fromPaths; if (!nonRelative) { return relativePath; } @@ -122166,9 +124010,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -122188,10 +124032,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_17 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_17) + return result_17; } }); }); @@ -122233,7 +124077,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_32 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -122257,9 +124101,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_10 = _loop_32(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_10 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -122315,28 +124159,102 @@ var ts; return ambientModuleDeclare.name.text; } } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + function getAllowedEndings(preferredEnding, compilerOptions, importMode) { + if (ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && importMode === ts.ModuleKind.ESNext) { + return [2 /* Ending.JsExtension */]; + } + switch (preferredEnding) { + case 2 /* Ending.JsExtension */: return [2 /* Ending.JsExtension */, 0 /* Ending.Minimal */, 1 /* Ending.Index */]; + case 1 /* Ending.Index */: return [1 /* Ending.Index */, 0 /* Ending.Minimal */, 2 /* Ending.JsExtension */]; + case 0 /* Ending.Minimal */: return [0 /* Ending.Minimal */, 1 /* Ending.Index */, 2 /* Ending.JsExtension */]; + default: ts.Debug.assertNever(preferredEnding); + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(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, + // meaning a '.ts' or '.d.ts' extension is allowed to resolve. This is distinct from the case where a '*' substitution + // causes a module specifier to have an extension, i.e. the extension comes from the module specifier in a JS/TS file + // and matches the '*'. For example: + // + // Module Specifier | Path Mapping (key: [pattern]) | Interpolation | Resolution Action + // ---------------------->------------------------------->--------------------->--------------------------------------------------------------- + // import "@app/foo" -> "@app/*": ["./src/app/*.ts"] -> "./src/app/foo.ts" -> tryFile("./src/app/foo.ts") || [continue resolution algorithm] + // import "@app/foo.ts" -> "@app/*": ["./src/app/*"] -> "./src/app/foo.ts" -> [continue resolution algorithm] + // + // (https://github.com/microsoft/TypeScript/blob/ad4ded80e1d58f0bf36ac16bea71bc10d9f09895/src/compiler/moduleNameResolver.ts#L2509-L2516) + // + // The interpolation produced by both scenarios is identical, but only in the former, where the extension is encoded in + // the path mapping rather than in the module specifier, will we prioritize a file lookup on the interpolation result. + // (In fact, currently, the latter scenario will necessarily fail since no resolution mode recognizes '.ts' as a valid + // extension for a module specifier.) + // + // Here, this means we need to be careful about whether we generate a match from the target filename (typically with a + // .ts extension) or the possible relative module specifiers representing that file: + // + // Filename | Relative Module Specifier Candidates | Path Mapping | Filename Result | Module Specifier Results + // --------------------<----------------------------------------------<------------------------------<-------------------||---------------------------- + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*.d.ts"] <- @app/haha || (none) + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*"] <- (none) || @app/haha, @app/haha.js + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*.d.ts"] <- @app/foo/index || (none) + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*"] <- (none) || @app/foo, @app/foo/index, @app/foo/index.js + // dist/wow.js.js <- dist/wow.js, dist/wow.js.js <- "@app/*": ["./dist/*.js"] <- @app/wow.js || @app/wow, @app/wow.js + // + // The "Filename Result" can be generated only if `pattern` has an extension. Care must be taken that the list of + // relative module specifiers to run the interpolation (a) is actually valid for the module resolution mode, (b) takes + // into account the existence of other files (e.g. 'dist/wow.js' cannot refer to 'dist/wow.js.js' if 'dist/wow.js' + // exists) and (c) that they are ordered by preference. The last row shows that the filename result and module + // specifier results are not mutually exclusive. Note that the filename result is a higher priority in module + // resolution, but as long criteria (b) above is met, I don't think its result needs to be the highest priority result + // in module specifier generation. I have included it last, as it's difficult to tell exactly where it should be + // sorted among the others for a particular value of `importModuleSpecifierEnding`. + var candidates = allowedEndings.map(function (ending) { return ({ + ending: ending, + value: removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) + }); }); + if (ts.tryGetExtensionFromPath(pattern)) { + candidates.push({ ending: undefined, value: relativeToBaseUrl }); + } if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix) || - !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); - return key.replace("*", matchedStar); + var prefix = pattern.substring(0, indexOfStar); + var suffix = pattern.substring(indexOfStar + 1); + for (var _b = 0, candidates_3 = candidates; _b < candidates_3.length; _b++) { + var _c = candidates_3[_b], ending = _c.ending, value = _c.value; + if (value.length >= prefix.length + suffix.length && + ts.startsWith(value, prefix) && + ts.endsWith(value, suffix) && + validateEnding({ ending: ending, value: value })) { + var matchedStar = value.substring(prefix.length, value.length - suffix.length); + return { value: key.replace("*", matchedStar) }; + } } } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; + else if (ts.some(candidates, function (c) { return c.ending !== 0 /* Ending.Minimal */ && pattern === c.value; }) || + ts.some(candidates, function (c) { return c.ending === 0 /* Ending.Minimal */ && pattern === c.value && validateEnding(c); })) { + return { value: key }; } + }; + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } + function validateEnding(_a) { + var ending = _a.ending, value = _a.value; + // Optimization: `removeExtensionAndIndexPostFix` can query the file system (a good bit) if `ending` is `Minimal`, the basename + // is 'index', and a `host` is provided. To avoid that until it's unavoidable, we ran the function with no `host` above. Only + // here, after we've checked that the minimal ending is indeed a match (via the length and prefix/suffix checks / `some` calls), + // do we check that the host-validated result is consistent with the answer we got before. If it's not, it falls back to the + // `Ending.Index` result, which should already be in the list of candidates if `Minimal` was. (Note: the assumption here is + // that every module resolution mode that supports dropping extensions also supports dropping `/index`. Like literally + // everything else in this file, this logic needs to be updated if that's not true in some future module resolution mode.) + return ending !== 0 /* Ending.Minimal */ || value === removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions, host); + } } var MatchingMode; (function (MatchingMode) { @@ -122432,10 +124350,10 @@ var ts; return undefined; } // Simplify the full file path to something that can be resolved by Node. + var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var moduleSpecifier = path; var isPackageRootPath = false; if (!packageNameOnly) { - var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var packageRootIndex = parts.packageRootIndex; var moduleFileName = void 0; while (true) { @@ -122484,15 +124402,13 @@ var ts; var packageRootPath = path.substring(0, packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); var moduleFileToTry = path; + var maybeBlockedByTypesVersions = false; var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) { var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); + var importMode = overrideMode || importingSourceFile.impliedNodeFormat; if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { - // `conditions` *could* be made to go against `importingSourceFile.impliedNodeFormat` if something wanted to generate - // an ImportEqualsDeclaration in an ESM-implied file or an ImportCall in a CJS-implied file. But since this function is - // usually called to conjure an import out of thin air, we don't have an existing usage to call `getModeForUsageAtIndex` - // with, so for now we just stick with the mode of the file. - var conditions = ["node", overrideMode || importingSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext ? "import" : "require", "types"]; + var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"]; var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, ts.getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions) : undefined; @@ -122511,16 +124427,26 @@ var ts; : undefined; if (versionPaths) { var subModuleName = path.slice(packageRootPath.length + 1); - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Ending.Minimal */, options), versionPaths.paths); - if (fromPaths !== undefined) { + var fromPaths = tryGetModuleNameFromPaths(subModuleName, versionPaths.paths, getAllowedEndings(preferences.ending, options, importMode), host, options); + if (fromPaths === undefined) { + maybeBlockedByTypesVersions = true; + } + else { moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths); } } // If the file is the main module, it can be imported by the package name var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; - if (ts.isString(mainFileRelative)) { + if (ts.isString(mainFileRelative) && !(maybeBlockedByTypesVersions && ts.matchPatternOrExact(ts.tryParsePatterns(versionPaths.paths), mainFileRelative))) { + // The 'main' file is also subject to mapping through typesVersions, and we couldn't come up with a path + // explicitly through typesVersions, so if it matches a key in typesVersions now, it's not reachable. + // (The only way this can happen is if some file in a package that's not resolvable from outside the + // package got pulled into the program anyway, e.g. transitively through a file that *is* reachable. It + // happens very easily in fourslash tests though, since every test file listed gets included. See + // importNameCodeFix_typesVersions.ts for an example.) var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + // ^ An arbitrary removal of file extension for this comparison is almost certainly wrong return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry }; } } @@ -122815,23 +124741,46 @@ var ts; var file = _c[_i]; write("".concat(toFileName(file, relativeFileName))); (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write(" ".concat(fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText)); }); - (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); + (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); } } ts.explainFiles = explainFiles; - function explainIfFileIsRedirect(file, fileNameConvertor) { + function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { + var _a; var result; if (file.path !== file.resolvedPath) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); } if (file.redirectInfo) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); } + if (ts.isExternalOrCommonJsModule(file)) { + switch (file.impliedNodeFormat) { + case ts.ModuleKind.ESNext: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + break; + case ts.ModuleKind.CommonJS: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, file.packageJsonScope.packageJsonContent.type ? + ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : + ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + else if ((_a = file.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found)); + } + break; + } + } return result; } - ts.explainIfFileIsRedirect = explainIfFileIsRedirect; + ts.explainIfFileIsRedirectAndImpliedFormat = explainIfFileIsRedirectAndImpliedFormat; function getMatchedFileSpec(program, fileName) { var _a; var configFile = program.getCompilerOptions().configFile; @@ -122848,6 +124797,9 @@ var ts; var configFile = program.getCompilerOptions().configFile; if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedIncludeSpecs)) return undefined; + // Return true if its default include spec + if (configFile.configFileSpecs.isDefaultIncludeSpec) + return true; var isJsonFile = ts.fileExtensionIs(fileName, ".json" /* Extension.Json */); var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); var useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); @@ -122913,11 +124865,13 @@ var ts; if (matchedByFiles) return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Part_of_files_list_in_tsconfig_json); var matchedByInclude = getMatchedIncludeSpec(program, fileName); - return matchedByInclude ? + return ts.isString(matchedByInclude) ? ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) : - // Could be additional files specified as roots - ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation); + // Could be additional files specified as roots or matched by default include + ts.chainDiagnosticMessages(/*details*/ undefined, matchedByInclude ? + ts.Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : + ts.Diagnostics.Root_file_specified_for_compilation); case ts.FileIncludeKind.SourceFromProjectReference: case ts.FileIncludeKind.OutputFromProjectReference: var isOutput = reason.kind === ts.FileIncludeKind.OutputFromProjectReference; @@ -123036,11 +124990,19 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", + AffectingFileLocation: "File location affecting resolution", TypeRoots: "Type roots", ConfigFileOfReferencedProject: "Config file of referened project", ExtendedConfigOfReferencedProject: "Extended config file of referenced project", WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", PackageJson: "package.json file", + ClosedScriptInfo: "Closed Script info", + ConfigFileForInferredRoot: "Config file for the inferred project root", + NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache", + MissingSourceMapFile: "Missing source map file", + NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root", + MissingGeneratedFile: "Missing generated file", + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -123149,6 +125111,7 @@ var ts; createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, storeFilesChangingSignatureDuringEmit: system.storeFilesChangingSignatureDuringEmit, + now: ts.maybeBind(system, system.now), }; } ts.createProgramHost = createProgramHost; @@ -123216,20 +125179,27 @@ var ts; var ts; (function (ts) { function readBuilderProgram(compilerOptions, host) { - if (ts.outFile(compilerOptions)) - return undefined; var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions); if (!buildInfoPath) return undefined; - var content = host.readFile(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); + var buildInfo; + if (host.getBuildInfo) { + // host provides buildinfo, get it from there. This allows host to cache it + buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); + if (!buildInfo) + return undefined; + } + else { + var content = host.readFile(buildInfoPath); + if (!content) + return undefined; + buildInfo = ts.getBuildInfo(content); + } if (buildInfo.version !== ts.version) return undefined; if (!buildInfo.program) return undefined; - return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); + return ts.createBuilderProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); } ts.readBuilderProgram = readBuilderProgram; function createIncrementalCompilerHost(options, system) { @@ -123282,14 +125252,12 @@ var ts; var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc var missingFilesMap; // Map of file watchers for the missing files - var packageJsonMap; // map of watchers for package json files used in module resolution var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations var parsedConfigs; // Parsed commandline and watching cached for referenced projects var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation - var changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution var reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files @@ -123346,6 +125314,7 @@ var ts; compilerHost.getCompilationSettings = function () { return compilerOptions; }; compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect); compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); }; + compilerHost.watchAffectingFileLocation = function (file, cb) { return watchFile(file, cb, ts.PollingInterval.High, watchOptions, ts.WatchType.AffectingFileLocation); }; compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); }; compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations; @@ -123379,6 +125348,9 @@ var ts; return host.resolveTypeReferenceDirectives.apply(host, args); }) : (function (typeDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference, containingFileMode); }); + compilerHost.getModuleResolutionCache = host.resolveModuleNames ? + ts.maybeBind(host, host.getModuleResolutionCache) : + (function () { return resolutionCache.getModuleResolutionCache(); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); @@ -123428,10 +125400,6 @@ var ts; }); parsedConfigs = undefined; } - if (packageJsonMap) { - ts.clearMap(packageJsonMap, ts.closeFileWatcher); - packageJsonMap = undefined; - } } function getCurrentBuilderProgram() { return builderProgram; @@ -123445,12 +125413,12 @@ var ts; var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); - if (program && (changesAffectResolution || ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions))) { + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { resolutionCache.clear(); } } // All resolutions are invalid if user provided resolutions - var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution); + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { @@ -123466,7 +125434,6 @@ var ts; } createNewProgram(hasInvalidatedResolution); } - changesAffectResolution = false; // reset for next sync reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); @@ -123486,16 +125453,11 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + var oldProgram = getCurrentProgram(); builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); - // map package json cache entries to their realpaths so we don't try to watch across symlinks - var packageCacheEntries = ts.map(resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [compilerHost.realpath ? toPath(compilerHost.realpath(path)) : path, data]; - }); - resolutionCache.finishCachingPerDirectoryResolution(); + resolutionCache.finishCachingPerDirectoryResolution(builderProgram.getProgram(), oldProgram); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath); - ts.updatePackageJsonWatch(packageCacheEntries, packageJsonMap || (packageJsonMap = new ts.Map()), watchPackageJsonLookupPath); if (needsUpdateInTypeRootWatch) { resolutionCache.updateTypeRootsWatch(); } @@ -123575,9 +125537,6 @@ var ts; sourceFilesCache.set(path, false); } } - if (sourceFile) { - sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); - } return sourceFile; } return hostSourceFile.sourceFile; @@ -123692,6 +125651,7 @@ var ts; } function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; rootFileNames = ts.getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions); if (ts.updateErrorForNoInputFiles(rootFileNames, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; @@ -123800,21 +125760,6 @@ var ts; ts.noopFileWatcher : watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } - function watchPackageJsonLookupPath(packageJsonPath) { - // If the package.json is pulled into the compilation itself (eg, via json imports), don't add a second watcher here - return sourceFilesCache.has(packageJsonPath) ? - ts.noopFileWatcher : - watchFilePath(packageJsonPath, packageJsonPath, onPackageJsonChange, ts.PollingInterval.High, watchOptions, ts.WatchType.PackageJson); - } - function onPackageJsonChange(fileName, eventKind, path) { - updateCachedSystemWithFile(fileName, path, eventKind); - // package.json changes invalidate module resolution and can change the set of loaded files - // so if we witness a change to one, we have to do a full reload - reloadLevel = ts.ConfigFileProgramReloadLevel.Full; - changesAffectResolution = true; - // Update the program - scheduleProgramUpdate(); - } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { @@ -123972,14 +125917,17 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream"; - UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate"; - UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream"; - UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["OutOfDateBuildInfo"] = 7] = "OutOfDateBuildInfo"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 8] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 9] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 10] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 11] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["UpToDateWithInputFileText"] = 12] = "UpToDateWithInputFileText"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 13] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ForceBuild"] = 14] = "ForceBuild"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); function resolveConfigFileProjectName(project) { if (ts.fileExtensionIs(project, ".json" /* Extension.Json */)) { @@ -124024,9 +125972,12 @@ var ts; function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); }); } - function newer(date1, date2) { - return date2 > date1 ? date2 : date1; + /*@internal*/ + /** Helper to use now method instead of current date for testing purposes to get consistent baselines */ + function getCurrentTime(host) { + return host.now ? host.now() : new Date(); } + ts.getCurrentTime = getCurrentTime; /*@internal*/ function isCircularBuildOrder(buildOrder) { return !!buildOrder && !!buildOrder.buildOrder; @@ -124101,6 +126052,7 @@ var ts; compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); }; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); + compilerHost.getModuleResolutionCache = ts.maybeBind(host, host.getModuleResolutionCache); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { @@ -124116,6 +126068,7 @@ var ts; return ts.loadWithTypeDirectiveCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader_4); }; } + compilerHost.getBuildInfo = function (fileName, configFilePath) { return getBuildInfo(state, fileName, toResolvedConfigFilePath(state, configFilePath), /*modifiedTime*/ undefined); }; var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -124132,8 +126085,9 @@ var ts; resolvedConfigFilePaths: new ts.Map(), configFileCache: new ts.Map(), projectStatus: new ts.Map(), - buildInfoChecked: new ts.Map(), extendedConfigCache: new ts.Map(), + buildInfoCache: new ts.Map(), + outputTimeStamps: new ts.Map(), builderPrograms: new ts.Map(), diagnostics: new ts.Map(), projectPendingBuild: new ts.Map(), @@ -124149,7 +126103,6 @@ var ts; allProjectBuildPending: true, needsSummary: true, watchAllProjectsPending: watch, - currentInvalidatedProject: undefined, // Watch state watch: watch, allWatchedWildcardDirectories: new ts.Map(), @@ -124157,6 +126110,7 @@ var ts; allWatchedConfigFiles: new ts.Map(), allWatchedExtendedConfigFiles: new ts.Map(), allWatchedPackageJsonFiles: new ts.Map(), + filesWatched: new ts.Map(), lastCachedPackageJsonLookups: new ts.Map(), timerToBuildInvalidatedProject: undefined, reportFileChangeDetected: false, @@ -124263,11 +126217,12 @@ var ts; // Config file cache ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete); - ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.buildInfoCache, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.outputTimeStamps, currentProjects, noopOnDelete); // Remove watches for the program no longer in the solution if (state.watch) { ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher }); @@ -124382,7 +126337,6 @@ var ts; })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {})); function doneInvalidatedProject(state, projectPath) { state.projectPendingBuild.delete(projectPath); - state.currentInvalidatedProject = undefined; return state.diagnostics.has(projectPath) ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; @@ -124558,21 +126512,21 @@ var ts; } function emit(writeFileCallback, cancellationToken, customTransformers) { var _a; - var _b, _c; + var _b, _c, _d; ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.Emit); // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly - program.backupState(); + var saved = program.saveEmitState(); var declDiagnostics; var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; var outputFiles = []; var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, /*write*/ undefined, - /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, + /*reportSummary*/ undefined, function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark, buildInfo: data === null || data === void 0 ? void 0 : data.buildInfo }); }, cancellationToken, /*emitOnlyDts*/ false, customTransformers || ((_c = (_b = state.host).getCustomTransformers) === null || _c === void 0 ? void 0 : _c.call(_b, project))).emitResult; // Don't emit .d.ts if there are decl file errors if (declDiagnostics) { - program.restoreState(); + program.restoreEmitState(saved); (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step); return { emitSkipped: true, @@ -124581,38 +126535,38 @@ var ts; } // Actual Emit var host = state.host, compilerHost = state.compilerHost; - var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; - var newestDeclarationFileContentChangedTime = minimumDate; - var anyDtsChanged = false; + var resultFlags = ((_d = program.hasChangedEmitSignature) === null || _d === void 0 ? void 0 : _d.call(program)) ? BuildResultFlags.None : BuildResultFlags.DeclarationOutputUnchanged; var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var options = program.getCompilerOptions(); + var isIncremental = ts.isIncrementalCompilation(options); + var outputTimeStampMap; + var now; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; - var priorChangeTime; - if (!anyDtsChanged && ts.isDeclarationFileName(name)) { - // Check for unchanged .d.ts files - if (host.fileExists(name) && state.readFileWithCache(name) === text) { - priorChangeTime = host.getModifiedTime(name); - } - else { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - anyDtsChanged = true; - } - } + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; + var path = toPath(state, name); emittedOutputs.set(toPath(state, name), name); + if (buildInfo) + setBuildInfo(state, buildInfo, projectPath, options, resultFlags); ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); - if (priorChangeTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + if (!isIncremental && state.watch) { + (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); } }); - finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); + finishEmit(emitterDiagnostics, emittedOutputs, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); return emitResult; } function emitBuildInfo(writeFileCallback, cancellationToken) { ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.EmitBuildInfo); - var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken); + var emitResult = program.emitBuildInfo(function (name, text, writeByteOrderMark, onError, sourceFiles, data) { + if (data === null || data === void 0 ? void 0 : data.buildInfo) + setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), BuildResultFlags.DeclarationOutputUnchanged); + if (writeFileCallback) + writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); + else + state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); + }, cancellationToken); if (emitResult.diagnostics.length) { reportErrors(state, emitResult.diagnostics); state.diagnostics.set(projectPath, __spreadArray(__spreadArray([], state.diagnostics.get(projectPath), true), emitResult.diagnostics, true)); @@ -124625,7 +126579,7 @@ var ts; step = BuildStep.QueueReferencingProjects; return emitResult; } - function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) { + function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) { var _a; var emitDiagnostics = emitterDiagnostics.getDiagnostics(); if (emitDiagnostics.length) { @@ -124636,13 +126590,10 @@ var ts; emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); }); } // Update time stamps for rest of the outputs - var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); + updateOutputTimestampsWorker(state, config, projectPath, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); state.diagnostics.delete(projectPath); state.projectStatus.set(projectPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ? - maximumDate : - newestDeclarationFileContentChangedTime, oldestOutputFileName: oldestOutputFileName }); afterProgramDone(state, program, config); @@ -124677,13 +126628,21 @@ var ts; ts.Debug.assert(!!outputFiles.length); var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; + var existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var _b, _c; + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; emittedOutputs.set(toPath(state, name), name); + if (buildInfo) { + if (((_b = buildInfo.program) === null || _b === void 0 ? void 0 : _b.outSignature) !== ((_c = existingBuildInfo.program) === null || _c === void 0 ? void 0 : _c.outSignature)) { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + } + setBuildInfo(state, buildInfo, projectPath, config.options, resultFlags); + } ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); }); - var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged); + var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, outputFiles[0].name, resultFlags); return { emitSkipped: false, diagnostics: emitDiagnostics }; } function executeSteps(till, cancellationToken, writeFile, customTransformers) { @@ -124733,17 +126692,11 @@ var ts; !!ts.getConfigFileParsingDiagnostics(config).length || !ts.isIncrementalCompilation(config.options); } - function getNextInvalidatedProject(state, buildOrder, reportQueue) { + function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { if (!state.projectPendingBuild.size) return undefined; if (isCircularBuildOrder(buildOrder)) return undefined; - if (state.currentInvalidatedProject) { - // Only if same buildOrder the currentInvalidated project can be sent again - return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ? - state.currentInvalidatedProject : - undefined; - } var options = state.options, projectPendingBuild = state.projectPendingBuild; for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { var project = buildOrder[projectIndex]; @@ -124776,9 +126729,9 @@ var ts; watchPackageJsonFiles(state, project, projectPath, config); } var status = getUpToDateStatus(state, config, projectPath); - verboseReportProjectStatus(state, project, status); if (!options.force) { if (status.type === ts.UpToDateStatusType.UpToDate) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Up to date, skip @@ -124788,12 +126741,20 @@ var ts; } continue; } - if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) { + if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes || status.type === ts.UpToDateStatusType.UpToDateWithInputFileText) { reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); - return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder); + return { + kind: InvalidatedProjectKind.UpdateOutputFileStamps, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config + }; } } if (status.type === ts.UpToDateStatusType.UpstreamBlocked) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); if (options.verbose) { @@ -124804,17 +126765,37 @@ var ts; continue; } if (status.type === ts.UpToDateStatusType.ContainerOnly) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Do nothing continue; } - return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ? - InvalidatedProjectKind.Build : - InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder); + return { + kind: needsBuild(state, status, config) ? + InvalidatedProjectKind.Build : + InvalidatedProjectKind.UpdateBundle, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config, + }; } return undefined; } + function createInvalidatedProjectWithInfo(state, info, buildOrder) { + verboseReportProjectStatus(state, info.project, info.status); + return info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps ? + createBuildOrUpdateInvalidedProject(info.kind, state, info.project, info.projectPath, info.projectIndex, info.config, buildOrder) : + createUpdateOutputFileStampsProject(state, info.project, info.projectPath, info.config, buildOrder); + } + function getNextInvalidatedProject(state, buildOrder, reportQueue) { + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); + if (!info) + return info; + return createInvalidatedProjectWithInfo(state, info, buildOrder); + } function listEmittedFile(_a, proj, file) { var write = _a.write; if (write && proj.options.listEmittedFiles) { @@ -124832,7 +126813,7 @@ var ts; } function afterProgramDone(state, program, config) { if (program) { - if (program && state.write) + if (state.write) ts.listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); @@ -124845,7 +126826,8 @@ var ts; state.projectCompilerOptions = state.baseCompilerOptions; } function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) { - var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions()); + // Since buildinfo has changeset and diagnostics when doing multi file emit, only --out cannot emit buildinfo if it has errors + var canEmitBuildInfo = program && !ts.outFile(program.getCompilerOptions()); reportAndStoreErrors(state, resolvedPath, diagnostics); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: "".concat(errorType, " errors") }); if (canEmitBuildInfo) @@ -124853,9 +126835,107 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } + function isFileWatcherWithModifiedTime(value) { + return !!value.watcher; + } + function getModifiedTime(state, fileName) { + var path = toPath(state, fileName); + var existing = state.filesWatched.get(path); + if (state.watch && !!existing) { + if (!isFileWatcherWithModifiedTime(existing)) + return existing; + if (existing.modifiedTime) + return existing.modifiedTime; + } + // In watch mode we store the modified times in the cache + // This is either Date | FileWatcherWithModifiedTime because we query modified times first and + // then after complete compilation of the project, watch the files so we dont want to loose these modified times. + var result = ts.getModifiedTime(state.host, fileName); + if (state.watch) { + if (existing) + existing.modifiedTime = result; + else + state.filesWatched.set(path, result); + } + return result; + } + function watchFile(state, file, callback, pollingInterval, options, watchType, project) { + var path = toPath(state, file); + var existing = state.filesWatched.get(path); + if (existing && isFileWatcherWithModifiedTime(existing)) { + existing.callbacks.push(callback); + } + else { + var watcher = state.watchFile(file, function (fileName, eventKind, modifiedTime) { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + existing.modifiedTime = modifiedTime; + existing.callbacks.forEach(function (cb) { return cb(fileName, eventKind, modifiedTime); }); + }, pollingInterval, options, watchType, project); + state.filesWatched.set(path, { callbacks: [callback], watcher: watcher, modifiedTime: existing }); + } + return { + close: function () { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + if (existing.callbacks.length === 1) { + state.filesWatched.delete(path); + ts.closeFileWatcherOf(existing); + } + else { + ts.unorderedRemoveItem(existing.callbacks, callback); + } + } + }; + } + function getOutputTimeStampMap(state, resolvedConfigFilePath) { + // Output timestamps are stored only in watch mode + if (!state.watch) + return undefined; + var result = state.outputTimeStamps.get(resolvedConfigFilePath); + if (!result) + state.outputTimeStamps.set(resolvedConfigFilePath, result = new ts.Map()); + return result; + } + function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) { + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(options); + var existing = getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath); + var modifiedTime = getCurrentTime(state.host); + if (existing) { + existing.buildInfo = buildInfo; + existing.modifiedTime = modifiedTime; + if (!(resultFlags & BuildResultFlags.DeclarationOutputUnchanged)) + existing.latestChangedDtsTime = modifiedTime; + } + else { + state.buildInfoCache.set(resolvedConfigPath, { + path: toPath(state, buildInfoPath), + buildInfo: buildInfo, + modifiedTime: modifiedTime, + latestChangedDtsTime: resultFlags & BuildResultFlags.DeclarationOutputUnchanged ? undefined : modifiedTime, + }); + } + } + function getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + return (existing === null || existing === void 0 ? void 0 : existing.path) === path ? existing : undefined; + } + function getBuildInfo(state, buildInfoPath, resolvedConfigPath, modifiedTime) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + if (existing !== undefined && existing.path === path) { + return existing.buildInfo || undefined; + } + var value = state.readFileWithCache(buildInfoPath); + var buildInfo = value ? ts.getBuildInfo(value) : undefined; + ts.Debug.assert(modifiedTime || !buildInfo); + state.buildInfoCache.set(resolvedConfigPath, { path: path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || ts.missingFileModifiedTime }); + return buildInfo; + } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = ts.getModifiedTime(state.host, configFile); + var tsconfigTime = getModifiedTime(state, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -124865,88 +126945,24 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { - var force = !!state.options.force; - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - var host = state.host; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: ts.UpToDateStatusType.Unbuildable, - reason: "".concat(inputFile, " does not exist") - }; - } - if (!force) { - var inputTime = ts.getModifiedTime(host, inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - } + var _a, _b; // Container if no files are specified in the project if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) { return { type: ts.UpToDateStatusType.ContainerOnly }; } - // Collect the expected outputs of this project - var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - if (!force) { - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = ts.getModifiedTime(host, output); - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (ts.isDeclarationFileName(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; + // Fast check to see if reference projects are upto date and error free + var referenceStatuses; + var force = !!state.options.force; if (project.projectReferences) { state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream }); - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); + for (var _i = 0, _c = project.projectReferences; _i < _c.length; _i++) { + var ref = _c[_i]; var resolvedRef = ts.resolveProjectReferencePath(ref); var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef); - var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath); + var resolvedConfig = parseConfigFile(state, resolvedRef, resolvedRefPath); + var refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath); // Its a circular reference ignore the status of this project if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream || refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project @@ -124968,75 +126984,192 @@ var ts; upstreamProjectName: ref.path }; } - // Check oldest output file name only if there is no missing output file name - // (a check we will have skipped if this is a forced build) - if (!force && !missingOutputFileName) { - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + if (!force) + (referenceStatuses || (referenceStatuses = [])).push({ ref: ref, refStatus: refStatus, resolvedRefPath: resolvedRefPath, resolvedConfig: resolvedConfig }); + } + } + if (force) + return { type: ts.UpToDateStatusType.ForceBuild }; + // Check buildinfo first + var host = state.host; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); + var oldestOutputFileName; + var oldestOutputFileTime = maximumDate; + var buildInfoTime; + var buildInfoProgram; + var buildInfoVersionMap; + if (buildInfoPath) { + var buildInfoCacheEntry_1 = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath); + buildInfoTime = (buildInfoCacheEntry_1 === null || buildInfoCacheEntry_1 === void 0 ? void 0 : buildInfoCacheEntry_1.modifiedTime) || ts.getModifiedTime(host, buildInfoPath); + if (buildInfoTime === ts.missingFileModifiedTime) { + if (!buildInfoCacheEntry_1) { + state.buildInfoCache.set(resolvedPath, { + path: toPath(state, buildInfoPath), + buildInfo: false, + modifiedTime: buildInfoTime + }); + } + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: buildInfoPath + }; + } + var buildInfo = ts.Debug.checkDefined(getBuildInfo(state, buildInfoPath, resolvedPath, buildInfoTime)); + if ((buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + return { + type: ts.UpToDateStatusType.TsVersionOutputOfDate, + version: buildInfo.version + }; + } + if (buildInfo.program) { + // If there are pending changes that are not emitted, project is out of date + 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))) { return { - type: ts.UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path + type: ts.UpToDateStatusType.OutOfDateBuildInfo, + buildInfoFile: buildInfoPath }; } + buildInfoProgram = buildInfo.program; } + oldestOutputFileTime = buildInfoTime; + oldestOutputFileName = buildInfoPath; } - if (missingOutputFileName !== undefined) { - return { - type: ts.UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; + // Check input files + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + /** True if input file has changed timestamp but text is not changed, we can then do only timestamp updates on output to make it look up-to-date later */ + var pseudoInputUpToDate = false; + // Get timestamps of input files + for (var _d = 0, _e = project.fileNames; _d < _e.length; _d++) { + var inputFile = _e[_d]; + var inputTime = getModifiedTime(state, inputFile); + if (inputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.Unbuildable, + reason: "".concat(inputFile, " does not exist") + }; + } + // If an buildInfo is older than the newest input, we can stop checking + if (buildInfoTime && buildInfoTime < inputTime) { + var version_3 = void 0; + var currentVersion = void 0; + if (buildInfoProgram) { + // Read files and see if they are same, read is anyways cached + if (!buildInfoVersionMap) + buildInfoVersionMap = ts.getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + version_3 = buildInfoVersionMap.get(toPath(state, inputFile)); + var text = version_3 ? state.readFileWithCache(inputFile) : undefined; + currentVersion = text && (host.createHash || ts.generateDjb2Hash)(text); + if (version_3 && version_3 === currentVersion) + pseudoInputUpToDate = true; + } + if (!version_3 || version_3 !== currentVersion) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: buildInfoPath, + newerInputFileName: inputFile + }; + } + } + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - if (isOutOfDateWithInputs) { - return { - type: ts.UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; + // Now see if all outputs are newer than the newest input + // Dont check output timestamps if we have buildinfo telling us output is uptodate + if (!buildInfoPath) { + // Collect the expected outputs of this project + var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, resolvedPath); + for (var _f = 0, outputs_1 = outputs; _f < outputs_1.length; _f++) { + var output = outputs_1[_f]; + var path = toPath(state, output); + // Output is missing; can stop checking + var outputTime = outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.get(path); + if (!outputTime) { + outputTime = ts.getModifiedTime(state.host, output); + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.set(path, outputTime); + } + if (outputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: output + }; + } + // If an output is older than the newest input, we can stop checking + if (outputTime < newestInputFileTime) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: output, + newerInputFileName: newestInputFileName + }; + } + // No need to get newestDeclarationFileContentChangedTime since thats needed only for composite projects + // And composite projects are the only ones that can be referenced + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + } } - else { - // Check tsconfig time - var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); - if (configStatus) - return configStatus; - // Check extended config time - var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); - if (extendedConfigStatus) - return extendedConfigStatus; - // Check package file time - var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { - var path = _a[0]; - return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); - }); - if (dependentPackageFileStatus) - return dependentPackageFileStatus; - } - if (!force && !state.buildInfoChecked.has(resolvedPath)) { - state.buildInfoChecked.set(resolvedPath, true); - var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); - if (buildInfoPath) { - var value = state.readFileWithCache(buildInfoPath); - var buildInfo = value && ts.getBuildInfo(value); - if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + var seenRefs = buildInfoPath ? new ts.Set() : undefined; + var buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath); + seenRefs === null || seenRefs === void 0 ? void 0 : seenRefs.add(resolvedPath); + /** Inputs are up-to-date, just need either timestamp update or bundle prepend manipulation to make it look up-to-date */ + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (referenceStatuses) { + for (var _g = 0, referenceStatuses_1 = referenceStatuses; _g < referenceStatuses_1.length; _g++) { + var _h = referenceStatuses_1[_g], ref = _h.ref, refStatus = _h.refStatus, resolvedConfig = _h.resolvedConfig, resolvedRefPath = _h.resolvedRefPath; + usesPrepend = usesPrepend || !!(ref.prepend); + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // Check if tsbuildinfo path is shared, then we need to rebuild + if (buildInfoCacheEntry && hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath)) { return { - type: ts.UpToDateStatusType.TsVersionOutputOfDate, - version: buildInfo.version + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: buildInfoPath, + newerProjectName: ref.path }; } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + var newestDeclarationFileContentChangedTime = getLatestChangedDtsTime(state, resolvedConfig.options, resolvedRefPath); + if (newestDeclarationFileContentChangedTime && newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + // Check package file time + var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { + var path = _a[0]; + return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); + }); + if (dependentPackageFileStatus) + return dependentPackageFileStatus; if (usesPrepend && pseudoUpToDate) { return { type: ts.UpToDateStatusType.OutOfDateWithPrepend, @@ -125046,15 +127179,36 @@ var ts; } // Up to date return { - type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + type: pseudoUpToDate ? + ts.UpToDateStatusType.UpToDateWithUpstreamTypes : + pseudoInputUpToDate ? + ts.UpToDateStatusType.UpToDateWithInputFileText : + ts.UpToDateStatusType.UpToDate, newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, oldestOutputFileName: oldestOutputFileName }; } + function hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath) { + if (seenRefs.has(resolvedRefPath)) + return false; + seenRefs.add(resolvedRefPath); + var refBuildInfo = state.buildInfoCache.get(resolvedRefPath); + if (refBuildInfo.path === buildInfoCacheEntry.path) + return true; + if (resolvedConfig.projectReferences) { + // Check references + for (var _i = 0, _a = resolvedConfig.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRef = ts.resolveProjectReferencePath(ref); + var resolvedRefPath_1 = toResolvedConfigFilePath(state, resolvedRef); + var resolvedConfig_1 = parseConfigFile(state, resolvedRef, resolvedRefPath_1); + if (hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig_1, resolvedRefPath_1)) + return true; + } + } + return false; + } function getUpToDateStatus(state, project, resolvedPath) { if (project === undefined) { return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; @@ -125067,39 +127221,71 @@ var ts; state.projectStatus.set(resolvedPath, actual); return actual; } - function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) { if (proj.options.noEmit) - return priorNewestUpdateTime; + return; + var now; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(proj.options); + if (buildInfoPath) { + // For incremental projects, only buildinfo needs to be upto date with timestamp check + // as we dont check output files for up-to-date ness + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(toPath(state, buildInfoPath)))) { + if (!!state.options.verbose) + reportStatus(state, verboseMessage, proj.options.configFilePath); + state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); + getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; + } + state.outputTimeStamps.delete(projectPath); + return; + } var host = state.host; var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, projectPath); + var modifiedOutputs = outputTimeStampMap ? new ts.Set() : undefined; if (!skipOutputs || outputs.length !== skipOutputs.size) { var reportVerbose = !!state.options.verbose; - var now = host.now ? host.now() : new Date(); for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { var file = outputs_2[_i]; - if (skipOutputs && skipOutputs.has(toPath(state, file))) { + var path = toPath(state, file); + if (skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(path)) continue; - } if (reportVerbose) { reportVerbose = false; reportStatus(state, verboseMessage, proj.options.configFilePath); } - if (ts.isDeclarationFileName(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); + host.setModifiedTime(file, now || (now = getCurrentTime(state.host))); + // Store output timestamps in a map because non incremental build will need to check them to determine up-to-dateness + if (outputTimeStampMap) { + outputTimeStampMap.set(path, now); + modifiedOutputs.add(path); } - host.setModifiedTime(file, now); } } - return priorNewestUpdateTime; + // Clear out timestamps not in output list any more + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.forEach(function (_value, key) { + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) + outputTimeStampMap.delete(key); + }); + } + function getLatestChangedDtsTime(state, options, resolvedConfigPath) { + if (!options.composite) + return undefined; + var entry = ts.Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); + if (entry.latestChangedDtsTime !== undefined) + return entry.latestChangedDtsTime || undefined; + var latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? + state.host.getModifiedTime(ts.getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, ts.getDirectoryPath(entry.path))) : + undefined; + entry.latestChangedDtsTime = latestChangedDtsTime || false; + return latestChangedDtsTime; } function updateOutputTimestamps(state, proj, resolvedPath) { if (state.options.dry) { return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath); } - var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); + updateOutputTimestampsWorker(state, proj, resolvedPath, ts.Diagnostics.Updating_output_timestamps_of_project_0); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: priorNewestUpdateTime, oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames()) }); } @@ -125145,6 +127331,7 @@ var ts; break; } // falls through + case ts.UpToDateStatusType.UpToDateWithInputFileText: case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: case ts.UpToDateStatusType.OutOfDateWithPrepend: if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { @@ -125255,9 +127442,9 @@ var ts; function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) { state.reportFileChangeDetected = true; invalidateProject(state, resolvedPath, reloadLevel); - scheduleBuildInvalidatedProject(state); + scheduleBuildInvalidatedProject(state, 250, /*changeDetected*/ true); } - function scheduleBuildInvalidatedProject(state) { + function scheduleBuildInvalidatedProject(state, time, changeDetected) { var hostWithWatch = state.hostWithWatch; if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; @@ -125265,25 +127452,38 @@ var ts; if (state.timerToBuildInvalidatedProject) { hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject); } - state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state); + state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, state, changeDetected); } - function buildNextInvalidatedProject(state) { + function buildNextInvalidatedProject(state, changeDetected) { state.timerToBuildInvalidatedProject = undefined; if (state.reportFileChangeDetected) { state.reportFileChangeDetected = false; state.projectErrorsReported.clear(); reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation); } + var projectsBuilt = 0; var buildOrder = getBuildOrder(state); var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false); if (invalidatedProject) { invalidatedProject.done(); - if (state.projectPendingBuild.size) { - // Schedule next project for build - if (state.watch && !state.timerToBuildInvalidatedProject) { - scheduleBuildInvalidatedProject(state); + projectsBuilt++; + while (state.projectPendingBuild.size) { + // If already scheduled, skip + if (state.timerToBuildInvalidatedProject) + return; + // Before scheduling check if the next project needs build + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, /*reportQueue*/ false); + if (!info) + break; // Nothing to build any more + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps && (changeDetected || projectsBuilt === 5)) { + // Schedule next project for build + scheduleBuildInvalidatedProject(state, 100, /*changeDetected*/ false); + return; } - return; + var project = createInvalidatedProjectWithInfo(state, info, buildOrder); + project.done(); + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps) + projectsBuilt++; } } disableCache(state); @@ -125292,12 +127492,10 @@ var ts; function watchConfigFile(state, resolved, resolvedPath, parsed) { if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; - state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(resolved, function () { - invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); - }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); + state.allWatchedConfigFiles.set(resolvedPath, watchFile(state, resolved, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(state, extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -125329,7 +127527,7 @@ var ts; if (!state.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), { - createNewValue: function (_path, input) { return state.watchFile(input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, + createNewValue: function (_path, input) { return watchFile(state, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -125337,7 +127535,7 @@ var ts; if (!state.watch || !state.lastCachedPackageJsonLookups) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), new ts.Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), { - createNewValue: function (path, _input) { return state.watchFile(path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, + createNewValue: function (path, _input) { return watchFile(state, path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -125387,8 +127585,6 @@ var ts; return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath); }, invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); }, - buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); }, - getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); }, close: function () { return stopWatching(state); }, }; } @@ -125469,19 +127665,18 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { - if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { - return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); - } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); case ts.UpToDateStatusType.OutOfDateWithUpstream: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.OutputMissing: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName)); + case ts.UpToDateStatusType.OutOfDateBuildInfo: + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), relName(state, status.buildInfoFile)); case ts.UpToDateStatusType.UpToDate: if (status.newestInputFileTime !== undefined) { - return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); } // Don't report anything for "up to date because it was already built" -- too verbose break; @@ -125489,6 +127684,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName)); + case ts.UpToDateStatusType.UpToDateWithInputFileText: + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, relName(state, configFileName)); case ts.UpToDateStatusType.UpstreamOutOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName)); case ts.UpToDateStatusType.UpstreamBlocked: @@ -125499,6 +127696,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason); case ts.UpToDateStatusType.TsVersionOutputOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, ts.version); + case ts.UpToDateStatusType.ForceBuild: + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); case ts.UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects // falls through @@ -125665,7 +127864,7 @@ var ts; * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ - function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry, compilerOptions) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } @@ -125683,12 +127882,14 @@ var ts; addInferredTypings(typeAcquisition.include, "Explicitly included types"); var exclude = typeAcquisition.exclude || []; // Directories to search for package.json, bower.json and other typing information - var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); - possibleSearchDirs.add(projectRootPath); - possibleSearchDirs.forEach(function (searchDir) { - getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); - getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); - }); + if (!compilerOptions.types) { + var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); + possibleSearchDirs.add(projectRootPath); + possibleSearchDirs.forEach(function (searchDir) { + getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); + getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); + }); + } if (!typeAcquisition.disableFilenameBasedTypeAcquisition) { getTypingNamesFromSourceFileNames(fileNames); } @@ -127051,6 +129252,8 @@ var ts; case 256 /* SyntaxKind.FunctionDeclaration */: case 213 /* SyntaxKind.FunctionExpression */: return getAdjustedLocationForFunction(node); + case 171 /* SyntaxKind.Constructor */: + return node; } } if (ts.isNamedDeclaration(node)) { @@ -127139,7 +129342,7 @@ var ts; // // NOTE: If the node is a modifier, we don't adjust its location if it is the `default` modifier as that is handled // specially by `getSymbolAtLocation`. - if (ts.isModifier(node) && (forRename || node.kind !== 88 /* SyntaxKind.DefaultKeyword */) ? ts.contains(parent.modifiers, node) : + if (ts.isModifier(node) && (forRename || node.kind !== 88 /* SyntaxKind.DefaultKeyword */) ? ts.canHaveModifiers(parent) && ts.contains(parent.modifiers, node) : node.kind === 84 /* SyntaxKind.ClassKeyword */ ? ts.isClassDeclaration(parent) || ts.isClassExpression(node) : node.kind === 98 /* SyntaxKind.FunctionKeyword */ ? ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(node) : node.kind === 118 /* SyntaxKind.InterfaceKeyword */ ? ts.isInterfaceDeclaration(parent) : @@ -127378,12 +129581,18 @@ var ts; // flag causes us to return the first node whose end position matches the position and which produces and acceptable token // kind. Meanwhile, if includePrecedingTokenAtEndPosition is unset, we look for the first node whose start is <= the // position and whose end is greater than the position. + // There are more sophisticated end tests later, but this one is very fast + // and allows us to skip a bunch of work + var end = children[middle].getEnd(); + if (end < position) { + return -1 /* Comparison.LessThan */; + } var start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { return 1 /* Comparison.GreaterThan */; } // first element whose start position is before the input and whose end position is after or equal to the input - if (nodeContainsPosition(children[middle])) { + if (nodeContainsPosition(children[middle], start, end)) { if (children[middle - 1]) { // we want the _first_ element that contains the position, so left-recur if the prior node also contains the position if (nodeContainsPosition(children[middle - 1])) { @@ -127415,13 +129624,16 @@ var ts; case "continue-outer": continue outer; } } - function nodeContainsPosition(node) { - var start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true); + function nodeContainsPosition(node, start, end) { + end !== null && end !== void 0 ? end : (end = node.getEnd()); + if (end < position) { + return false; + } + start !== null && start !== void 0 ? start : (start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true)); if (start > position) { // If this child begins after position, then all subsequent children will as well. return false; } - var end = node.getEnd(); if (position < end || (position === end && (node.kind === 1 /* SyntaxKind.EndOfFileToken */ || includeEndPosition))) { return true; } @@ -128119,7 +130331,6 @@ var ts; ts.makeImportIfNecessary = makeImportIfNecessary; function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) { return ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? ts.factory.createNamedImports(namedImports) : undefined) : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier, @@ -128209,7 +130420,7 @@ var ts; node.getEnd() <= ts.textSpanEnd(span); } function findModifier(node, kind) { - return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + return ts.canHaveModifiers(node) ? ts.find(node.modifiers, function (m) { return m.kind === kind; }) : undefined; } ts.findModifier = findModifier; function insertImports(changes, sourceFile, imports, blankLineBetween) { @@ -128288,6 +130499,41 @@ var ts; return true; } ts.isTextWhiteSpaceLike = isTextWhiteSpaceLike; + function getMappedLocation(location, sourceMapper, fileExists) { + var mapsTo = sourceMapper.tryGetSourcePosition(location); + return mapsTo && (!fileExists || fileExists(ts.normalizePath(mapsTo.fileName)) ? mapsTo : undefined); + } + ts.getMappedLocation = getMappedLocation; + function getMappedDocumentSpan(documentSpan, sourceMapper, fileExists) { + var fileName = documentSpan.fileName, textSpan = documentSpan.textSpan; + var newPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start }, sourceMapper, fileExists); + if (!newPosition) + return undefined; + var newEndPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start + textSpan.length }, sourceMapper, fileExists); + var newLength = newEndPosition + ? newEndPosition.pos - newPosition.pos + : textSpan.length; // This shouldn't happen + return { + fileName: newPosition.fileName, + textSpan: { + start: newPosition.pos, + length: newLength, + }, + originalFileName: documentSpan.fileName, + originalTextSpan: documentSpan.textSpan, + contextSpan: getMappedContextSpan(documentSpan, sourceMapper, fileExists), + originalContextSpan: documentSpan.contextSpan + }; + } + ts.getMappedDocumentSpan = getMappedDocumentSpan; + function getMappedContextSpan(documentSpan, sourceMapper, fileExists) { + var contextSpanStart = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, sourceMapper, fileExists); + var contextSpanEnd = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length }, sourceMapper, fileExists); + return contextSpanStart && contextSpanEnd ? + { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : + undefined; + } + ts.getMappedContextSpan = getMappedContextSpan; // #endregion // Display-part writer helpers // #region @@ -128781,7 +131027,7 @@ var ts; for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { var change = textChanges_1[_b]; var span = change.span, newText = change.newText; - var index = indexInTextChange(newText, name); + var index = indexInTextChange(newText, ts.escapeString(name)); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. @@ -129749,32 +131995,41 @@ var ts; || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } - function forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, cb) { + function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { var _a, _b; - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var excludePatterns = preferences.autoImportFileExcludePatterns && ts.mapDefined(preferences.autoImportFileExcludePatterns, function (spec) { + // The client is expected to send rooted path specs since we don't know + // what directory a relative path is relative to. + var pattern = ts.getPatternFromSpec(spec, "", "exclude"); + return pattern ? ts.getRegexFromPattern(pattern, useCaseSensitiveFileNames) : undefined; + }); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); var autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)); if (autoImportProvider) { var start = ts.timestamp(); - forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); + forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: ".concat(ts.timestamp() - start)); } } ts.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModule(checker, allSourceFiles, cb) { - for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { - var ambient = _a[_i]; - if (!ts.stringContains(ambient.name, "*")) { + function forEachExternalModule(checker, allSourceFiles, excludePatterns, cb) { + var _a; + var isExcluded = function (fileName) { return excludePatterns === null || excludePatterns === void 0 ? void 0 : excludePatterns.some(function (p) { return p.test(fileName); }); }; + for (var _i = 0, _b = checker.getAmbientModules(); _i < _b.length; _i++) { + var ambient = _b[_i]; + if (!ts.stringContains(ambient.name, "*") && !(excludePatterns && ((_a = ambient.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return isExcluded(d.getSourceFile().fileName); })))) { cb(ambient, /*sourceFile*/ undefined); } } - for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { - var sourceFile = allSourceFiles_1[_b]; - if (ts.isExternalOrCommonJsModule(sourceFile)) { + for (var _c = 0, allSourceFiles_1 = allSourceFiles; _c < allSourceFiles_1.length; _c++) { + var sourceFile = allSourceFiles_1[_c]; + if (ts.isExternalOrCommonJsModule(sourceFile) && !isExcluded(sourceFile.fileName)) { cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } } } - function getExportInfoMap(importingFile, host, program, cancellationToken) { + function getExportInfoMap(importingFile, host, program, preferences, cancellationToken) { var _a, _b, _c, _d, _e; var start = ts.timestamp(); // Pulling the AutoImportProvider project will trigger its updateGraph if pending, @@ -129794,7 +132049,7 @@ var ts; var compilerOptions = program.getCompilerOptions(); var moduleCount = 0; try { - forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { + forEachExternalModuleToImportFrom(program, host, preferences, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { if (++moduleCount % 100 === 0) cancellationToken === null || cancellationToken === void 0 ? void 0 : cancellationToken.throwIfCancellationRequested(); var seenExports = new ts.Map(); @@ -131135,6 +133390,26 @@ var ts; (function (Completions) { var StringCompletions; (function (StringCompletions) { + var _a; + var kindPrecedence = (_a = {}, + _a["directory" /* ScriptElementKind.directory */] = 0, + _a["script" /* ScriptElementKind.scriptElement */] = 1, + _a["external module name" /* ScriptElementKind.externalModuleName */] = 2, + _a); + function createNameAndKindSet() { + var map = new ts.Map(); + function add(value) { + var existing = map.get(value.name); + if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value.kind]) { + map.set(value.name, value); + } + } + return { + add: add, + has: map.has.bind(map), + values: map.values.bind(map), + }; + } function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); @@ -131238,11 +133513,11 @@ var ts; var parent = walkUpParentheses(node.parent); switch (parent.kind) { case 196 /* SyntaxKind.LiteralType */: { - var grandParent = walkUpParentheses(parent.parent); - switch (grandParent.kind) { + var grandParent_1 = walkUpParentheses(parent.parent); + switch (grandParent_1.kind) { + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: case 178 /* SyntaxKind.TypeReference */: { - var typeReference_1 = grandParent; - var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === typeReference_1; }); + var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === grandParent_1; }); if (typeArgument) { return { kind: 2 /* StringLiteralCompletionKind.Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), isNewIdentifier: false }; } @@ -131255,7 +133530,7 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - var _a = grandParent, indexType = _a.indexType, objectType = _a.objectType; + var _a = grandParent_1, indexType = _a.indexType, objectType = _a.objectType; if (!ts.rangeContainsPosition(indexType, position)) { return undefined; } @@ -131263,11 +133538,11 @@ var ts; case 200 /* SyntaxKind.ImportType */: return { kind: 0 /* StringLiteralCompletionKind.Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; case 187 /* SyntaxKind.UnionType */: { - if (!ts.isTypeReferenceNode(grandParent.parent)) { + if (!ts.isTypeReferenceNode(grandParent_1.parent)) { return undefined; } - var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent); - var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(grandParent_1, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent_1)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); return { kind: 2 /* StringLiteralCompletionKind.Types */, types: types, isNewIdentifier: false }; } default: @@ -131416,11 +133691,12 @@ var ts; } function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { var literalValue = ts.normalizeSlashes(node.text); + var mode = ts.isStringLiteralLike(node) ? ts.getModeForUsageLocation(sourceFile, node) : undefined; var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, getIncludeExtensionOption()) - : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, compilerOptions, host, getIncludeExtensionOption(), typeChecker); function getIncludeExtensionOption() { var mode = ts.isStringLiteralLike(node) ? ts.getModeForUsageLocation(sourceFile, node) : undefined; return preferences.importModuleSpecifierEnding === "js" || mode === ts.ModuleKind.ESNext ? 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */ : 0 /* IncludeExtensionsOption.Exclude */; @@ -131436,7 +133712,7 @@ var ts; return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + return ts.arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath).values()); } } function isEmitResolutionKindUsingNodeModules(compilerOptions) { @@ -131472,7 +133748,7 @@ var ts; var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); - return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); + return ts.flatMap(baseDirectories, function (baseDirectory) { return ts.arrayFrom(getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude).values()); }); } var IncludeExtensionsOption; (function (IncludeExtensionsOption) { @@ -131483,9 +133759,9 @@ var ts; /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { - var extensions = _a.extensions, includeExtensionsOption = _a.includeExtensionsOption; - if (result === void 0) { result = []; } + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensionOptions, host, exclude, result) { + var _a; + if (result === void 0) { result = createNameAndKindSet(); } if (fragment === undefined) { fragment = ""; } @@ -131501,92 +133777,124 @@ var ts; fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths var absolutePath = ts.resolvePath(scriptPath, fragment); var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); + // check for a version redirect + var packageJsonPath = ts.findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionPaths = (_a = ts.getPackageJsonTypesVersionsPaths(typesVersions)) === null || _a === void 0 ? void 0 : _a.paths; + if (versionPaths) { + var packageDirectory = ts.getDirectoryPath(packageJsonPath); + var pathInPackage = absolutePath.slice(ts.ensureTrailingDirectorySeparator(packageDirectory).length); + if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, host, versionPaths)) { + // A true result means one of the `versionPaths` was matched, which will block relative resolution + // to files and folders from here. All reachable paths given the pattern match are already added. + return result; + } + } + } + } var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (!ts.tryDirectoryExists(host, baseDirectory)) return result; // Enumerate the available files if possible - var files = ts.tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + var files = ts.tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensionsOption === includeExtensionsOption.Exclude) so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - var foundFiles = new ts.Map(); // maps file to its extension for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { var filePath = files_1[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* Comparison.EqualTo */) { continue; } - var foundFileName = void 0; - var outputExtension = ts.moduleSpecifiers.tryGetJSExtensionForFile(filePath, host.getCompilationSettings()); - if (includeExtensionsOption === 0 /* IncludeExtensionsOption.Exclude */ && !ts.fileExtensionIsOneOf(filePath, [".json" /* Extension.Json */, ".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */])) { - foundFileName = ts.removeFileExtension(ts.getBaseFileName(filePath)); - foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); - } - else if ((ts.fileExtensionIsOneOf(filePath, [".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */]) || includeExtensionsOption === 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */) && outputExtension) { - foundFileName = ts.changeExtension(ts.getBaseFileName(filePath), outputExtension); - foundFiles.set(foundFileName, outputExtension); - } - else { - foundFileName = ts.getBaseFileName(filePath); - foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); - } + var _b = getFilenameWithExtensionOption(ts.getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions.includeExtensionsOption), name = _b.name, extension = _b.extension; + result.add(nameAndKind(name, "script" /* ScriptElementKind.scriptElement */, extension)); } - foundFiles.forEach(function (ext, foundFile) { - result.push(nameAndKind(foundFile, "script" /* ScriptElementKind.scriptElement */, ext)); - }); } // If possible, get folder completion as well var directories = ts.tryGetDirectories(host, baseDirectory); if (directories) { - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var directory = directories_1[_b]; + for (var _c = 0, directories_1 = directories; _c < directories_1.length; _c++) { + var directory = directories_1[_c]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); if (directoryName !== "@types") { - result.push(directoryResult(directoryName)); - } - } - } - // check for a version redirect - var packageJsonPath = ts.findPackageJson(baseDirectory, host); - if (packageJsonPath) { - var packageJson = ts.readJson(packageJsonPath, host); - var typesVersions = packageJson.typesVersions; - if (typeof typesVersions === "object") { - var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); - var versionPaths = versionResult && versionResult.paths; - var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); - if (versionPaths) { - addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + result.add(directoryResult(directoryName)); } } } return result; } - function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { - for (var path in paths) { - if (!ts.hasProperty(paths, path)) + function getFilenameWithExtensionOption(name, compilerOptions, includeExtensionsOption) { + var outputExtension = ts.moduleSpecifiers.tryGetJSExtensionForFile(name, compilerOptions); + if (includeExtensionsOption === 0 /* IncludeExtensionsOption.Exclude */ && !ts.fileExtensionIsOneOf(name, [".json" /* Extension.Json */, ".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */])) { + return { name: ts.removeFileExtension(name), extension: ts.tryGetExtensionFromPath(name) }; + } + else if ((ts.fileExtensionIsOneOf(name, [".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */]) || includeExtensionsOption === 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */) && outputExtension) { + return { name: ts.changeExtension(name, outputExtension), extension: outputExtension }; + } + else { + return { name: name, extension: ts.tryGetExtensionFromPath(name) }; + } + } + /** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */ + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, host, paths) { + var getPatternsForKey = function (key) { return paths[key]; }; + var comparePaths = function (a, b) { + var patternA = ts.tryParsePattern(a); + var patternB = ts.tryParsePattern(b); + var lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length; + var lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length; + return ts.compareValues(lengthB, lengthA); + }; + return addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, ts.getOwnKeys(paths), getPatternsForKey, comparePaths); + } + /** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */ + function addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, keys, getPatternsForKey, comparePaths) { + var pathResults = []; + var matchedPath; + for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { + var key = keys_1[_i]; + if (key === ".") continue; - var patterns = paths[path]; + var keyWithoutLeadingDotSlash = key.replace(/^\.\//, ""); // remove leading "./" + var patterns = getPatternsForKey(key); if (patterns) { - var _loop_3 = function (name, kind, extension) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind, extension)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_3(name, kind, extension); + var pathPattern = ts.tryParsePattern(keyWithoutLeadingDotSlash); + if (!pathPattern) + continue; + var isMatch = typeof pathPattern === "object" && ts.isPatternMatch(pathPattern, fragment); + var isLongestMatch = isMatch && (matchedPath === undefined || comparePaths(key, matchedPath) === -1 /* Comparison.LessThan */); + if (isLongestMatch) { + // If this is a higher priority match than anything we've seen so far, previous results from matches are invalid, e.g. + // for `import {} from "some-package/|"` with a typesVersions: + // { + // "bar/*": ["bar/*"], // <-- 1. We add 'bar', but 'bar/*' doesn't match yet. + // "*": ["dist/*"], // <-- 2. We match here and add files from dist. 'bar' is still ok because it didn't come from a match. + // "foo/*": ["foo/*"] // <-- 3. We matched '*' earlier and added results from dist, but if 'foo/*' also matched, + // } results in dist would not be visible. 'bar' still stands because it didn't come from a match. + // This is especially important if `dist/foo` is a folder, because if we fail to clear results + // added by the '*' match, after typing `"some-package/foo/|"` we would get file results from both + // ./dist/foo and ./foo, when only the latter will actually be resolvable. + // See pathCompletionsTypesVersionsWildcard6.ts. + matchedPath = key; + pathResults = pathResults.filter(function (r) { return !r.matchedPattern; }); + } + if (typeof pathPattern === "string" || matchedPath === undefined || comparePaths(key, matchedPath) !== 1 /* Comparison.GreaterThan */) { + pathResults.push({ + matchedPattern: isMatch, + results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host) + .map(function (_a) { + var name = _a.name, kind = _a.kind, extension = _a.extension; + return nameAndKind(name, kind, extension); + }), + }); } } } + pathResults.forEach(function (pathResult) { return pathResult.results.forEach(function (r) { return result.add(r); }); }); + return matchedPath !== undefined; } /** * Check all of the declared modules and those in node modules. Possible sources of modules: @@ -131595,22 +133903,22 @@ var ts; * Modules from node_modules (i.e. those listed in package.json) * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions */ - function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, compilerOptions, host, includeExtensionsOption, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; - var result = []; - var extensionOptions = getExtensionOptions(compilerOptions); + var result = createNameAndKindSet(); + var extensionOptions = getExtensionOptions(compilerOptions, includeExtensionsOption); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); if (paths) { - addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, host, paths); } } var fragmentDirectory = getFragmentDirectory(fragment); for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { var ambientName = _a[_i]; - result.push(nameAndKind(ambientName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); + result.add(nameAndKind(ambientName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (isEmitResolutionKindUsingNodeModules(compilerOptions)) { @@ -131618,15 +133926,13 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_4 = function (moduleName) { - if (!result.some(function (entry) { return entry.name === moduleName; })) { - foundGlobal = true; - result.push(nameAndKind(moduleName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); - } - }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_4(moduleName); + var moduleResult = nameAndKind(moduleName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined); + if (!result.has(moduleResult.name)) { + foundGlobal = true; + result.add(moduleResult); + } } } if (!foundGlobal) { @@ -131652,39 +133958,19 @@ var ts; } packagePath = ts.combinePaths(packagePath, subName); } - var packageFile = ts.combinePaths(ancestor, "node_modules", packagePath, "package.json"); + var packageDirectory = ts.combinePaths(ancestor, "node_modules", packagePath); + var packageFile = ts.combinePaths(packageDirectory, "package.json"); if (ts.tryFileExists(host, packageFile)) { var packageJson = ts.readJson(packageFile, host); - var exports = packageJson.exports; - if (exports) { - if (typeof exports !== "object" || exports === null) { // eslint-disable-line no-null/no-null + var exports_1 = packageJson.exports; + if (exports_1) { + if (typeof exports_1 !== "object" || exports_1 === null) { // eslint-disable-line no-null/no-null return; // null exports or entrypoint only, no sub-modules available } - var keys = ts.getOwnKeys(exports); - var fragmentSubpath_1 = components.join("/"); - var processedKeys = ts.mapDefined(keys, function (k) { - if (k === ".") - return undefined; - if (!ts.startsWith(k, "./")) - return undefined; - var subpath = k.substring(2); - if (!ts.startsWith(subpath, fragmentSubpath_1)) - return undefined; - // subpath is a valid export (barring conditions, which we don't currently check here) - if (!ts.stringContains(subpath, "*")) { - return subpath; - } - // pattern export - only return everything up to the `*`, so the user can autocomplete, then - // keep filling in the pattern (we could speculatively return a list of options by hitting disk, - // but conditions will make that somewhat awkward, as each condition may have a different set of possible - // options for the `*`. - return subpath.slice(0, subpath.indexOf("*")); - }); - ts.forEach(processedKeys, function (k) { - if (k) { - result.push(nameAndKind(k, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); - } - }); + var keys = ts.getOwnKeys(exports_1); + var fragmentSubpath = components.join("/") + (components.length && ts.hasTrailingDirectorySeparator(fragment) ? "/" : ""); + var conditions_1 = mode === ts.ModuleKind.ESNext ? ["node", "import", "types"] : ["node", "require", "types"]; + addCompletionEntriesFromPathsOrExports(result, fragmentSubpath, packageDirectory, extensionOptions, host, keys, function (key) { return ts.singleElementArray(getPatternFromFirstMatchingCondition(exports_1[key], conditions_1)); }, ts.comparePatternKeys); return; } } @@ -131694,26 +133980,44 @@ var ts; ts.forEachAncestorDirectory(scriptPath, ancestorLookup); } } - return result; + return ts.arrayFrom(result.values()); + } + function getPatternFromFirstMatchingCondition(target, conditions) { + if (typeof target === "string") { + return target; + } + if (target && typeof target === "object" && !ts.isArray(target)) { + for (var condition in target) { + if (condition === "default" || conditions.indexOf(condition) > -1 || ts.isApplicableVersionedTypesKey(conditions, condition)) { + var pattern = target[condition]; + return getPatternFromFirstMatchingCondition(pattern, conditions); + } + } + } } function getFragmentDirectory(fragment) { return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; } - function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; + return !ts.stringContains(path, "*") ? justPathMappingName(path, "script" /* ScriptElementKind.scriptElement */) : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); - return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { - return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); - }); - function justPathMappingName(name) { - return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; + if (remainingFragment === undefined) { + var starIsFullPathComponent = path[path.length - 2] === "/"; + return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* ScriptElementKind.directory */) : ts.flatMap(patterns, function (pattern) { var _a; return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)) === null || _a === void 0 ? void 0 : _a.map(function (_a) { + var name = _a.name, rest = __rest(_a, ["name"]); + return (__assign({ name: pathPrefix + name }, rest)); + }); }); + } + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host); }); + function justPathMappingName(name, kind) { + return ts.startsWith(name, fragment) ? [{ name: ts.removeTrailingDirectorySeparator(name), kind: kind, extension: undefined }] : ts.emptyArray; } } - function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, host) { if (!host.readDirectory) { return undefined; } @@ -131732,21 +134036,33 @@ var ts; var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". - var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var baseDirectory = ts.normalizePath(ts.combinePaths(packageDirectory, expandedPrefixDirectory)); var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { - var extension = ts.tryGetExtensionFromPath(match); - var name = trimPrefixAndSuffix(match); - return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* ScriptElementKind.scriptElement */, extension); - }); - var directories = ts.mapDefined(ts.tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { - var name = trimPrefixAndSuffix(dir); - return name === undefined ? undefined : directoryResult(name); + // If we have a suffix, then we read the directory all the way down to avoid returning completions for + // directories that don't contain files that would match the suffix. A previous comment here was concerned + // about the case where `normalizedSuffix` includes a `?` character, which should be interpreted literally, + // but will match any single character as part of the `include` pattern in `tryReadDirectory`. This is not + // a problem, because (in the extremely unusual circumstance where the suffix has a `?` in it) a `?` + // interpreted as "any character" can only return *too many* results as compared to the literal + // interpretation, so we can filter those superfluous results out via `trimPrefixAndSuffix` as we've always + // done. + var includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*"; + var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var trimmedWithPattern = trimPrefixAndSuffix(match); + if (trimmedWithPattern) { + if (containsSlash(trimmedWithPattern)) { + return directoryResult(ts.getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); + } + var _a = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions.includeExtensionsOption), name = _a.name, extension = _a.extension; + return nameAndKind(name, "script" /* ScriptElementKind.scriptElement */, extension); + } }); + // If we had a suffix, we already recursively searched for all possible files that could match + // it and returned the directories leading to those files. Otherwise, assume any directory could + // have something valid to import. + var directories = normalizedSuffix + ? ts.emptyArray + : ts.mapDefined(ts.tryGetDirectories(host, baseDirectory), function (dir) { return dir === "node_modules" ? undefined : directoryResult(dir); }); return __spreadArray(__spreadArray([], matches, true), directories, true); function trimPrefixAndSuffix(path) { var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); @@ -131789,10 +134105,10 @@ var ts; var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, 1 /* IncludeExtensionsOption.Include */), host, sourceFile.path) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) : ts.Debug.fail(); - return addReplacementSpans(toComplete, range.pos + prefix.length, names); + return addReplacementSpans(toComplete, range.pos + prefix.length, ts.arrayFrom(names.values())); } function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { - if (result === void 0) { result = []; } + if (result === void 0) { result = createNameAndKindSet(); } // Check for typings specified in compiler options var seen = new ts.Map(); var typeRoots = ts.tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; @@ -131817,7 +134133,7 @@ var ts; continue; if (fragmentDirectory === undefined) { if (!seen.has(packageName)) { - result.push(nameAndKind(packageName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); + result.add(nameAndKind(packageName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); seen.set(packageName, true); } } @@ -132013,10 +134329,9 @@ var ts; GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; })(GlobalsSearch || (GlobalsSearch = {})); - function resolvingModuleSpecifiers(logPrefix, host, program, sourceFile, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { + function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { var _a, _b, _c; var start = ts.timestamp(); - var packageJsonImportFilter = ts.createPackageJsonImportFilter(sourceFile, preferences, host); // Under `--moduleResolution nodenext`, we have to resolve module specifiers up front, because // package.json exports can mean we *can't* resolve a module specifier (that doesn't include a // relative path into node_modules), and we want to filter those completions out entirely. @@ -132041,7 +134356,7 @@ var ts; return result; function tryResolve(exportInfo, symbolName, isFromAmbientModule) { if (isFromAmbientModule) { - var result_1 = ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, sourceFile, program, host, preferences); + var result_1 = resolver.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite); if (result_1) { ambientCount++; } @@ -132050,7 +134365,7 @@ var ts; var shouldResolveModuleSpecifier = needsFullResolution || preferences.allowIncompleteCompletions && resolvedCount < Completions.moduleSpecifierResolutionLimit; var shouldGetModuleSpecifierFromCache = !shouldResolveModuleSpecifier && preferences.allowIncompleteCompletions && cacheAttemptCount < Completions.moduleSpecifierResolutionCacheAttemptLimit; var result = (shouldResolveModuleSpecifier || shouldGetModuleSpecifierFromCache) - ? ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, sourceFile, program, host, preferences, packageJsonImportFilter, shouldGetModuleSpecifierFromCache) + ? resolver.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, shouldGetModuleSpecifierFromCache) : undefined; if (!shouldResolveModuleSpecifier && !shouldGetModuleSpecifierFromCache || shouldGetModuleSpecifierFromCache && !result) { skippedAny = true; @@ -132154,8 +134469,8 @@ var ts; if (!previousResponse) return undefined; var lowerCaseTokenText = location.text.toLowerCase(); - var exportMap = ts.getExportInfoMap(file, host, program, cancellationToken); - var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, program, file, location.getStart(), preferences, + var exportMap = ts.getExportInfoMap(file, host, program, preferences, cancellationToken); + var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, ts.codefix.createImportSpecifierResolver(file, program, host, preferences), program, location.getStart(), preferences, /*isForImportStatementCompletion*/ false, ts.isValidTypeOnlyAliasUseSite(location), function (context) { var entries = ts.mapDefined(previousResponse.entries, function (entry) { var _a; @@ -132239,37 +134554,36 @@ var ts; } } var entries = ts.createSortedArray(); - if (isUncheckedFile(sourceFile, compilerOptions)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); - getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); - } - else { - if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* KeywordCompletionFilters.None */) { - return undefined; - } - getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); + var isChecked = isCheckedFile(sourceFile, compilerOptions); + if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* KeywordCompletionFilters.None */) { + return undefined; } + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); if (keywordFilters !== 0 /* KeywordCompletionFilters.None */) { - var entryNames_1 = new ts.Set(entries.map(function (e) { return e.name; })); for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; - if (isTypeOnlyLocation && ts.isTypeKeyword(ts.stringToToken(keywordEntry.name)) || !entryNames_1.has(keywordEntry.name)) { + if (isTypeOnlyLocation && ts.isTypeKeyword(ts.stringToToken(keywordEntry.name)) || !uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } } - var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); for (var _b = 0, _c = getContextualKeywords(contextToken, position); _b < _c.length; _b++) { var keywordEntry = _c[_b]; - if (!entryNames.has(keywordEntry.name)) { + if (!uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } for (var _d = 0, literals_1 = literals; _d < literals_1.length; _d++) { var literal = literals_1[_d]; - ts.insertSorted(entries, createCompletionEntryForLiteral(sourceFile, preferences, literal), compareCompletionEntries, /*allowDuplicates*/ true); + var literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal); + uniqueNames.add(literalEntry.name); + ts.insertSorted(entries, literalEntry, compareCompletionEntries, /*allowDuplicates*/ true); + } + if (!isChecked) { + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); } return { flags: completionData.flags, @@ -132281,8 +134595,8 @@ var ts; entries: entries, }; } - function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + function isCheckedFile(sourceFile, compilerOptions) { + return !ts.isSourceFileJS(sourceFile) || !!ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -132651,7 +134965,7 @@ var ts; span = ts.createTextSpanFromNode(contextToken); } if (ts.isPropertyDeclaration(contextToken.parent)) { - modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers); + modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers) & 125951 /* ModifierFlags.Modifier */; span = ts.createTextSpanFromNode(contextToken.parent); } return { modifiers: modifiers, span: span }; @@ -132711,7 +135025,7 @@ var ts; var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var quotePreference = ts.getQuotePreference(sourceFile, preferences); - var builderFlags = quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : undefined; + var builderFlags = 33554432 /* NodeBuilderFlags.OmitThisParameter */ | (quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : 0 /* NodeBuilderFlags.None */); switch (declaration.kind) { case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: @@ -132750,12 +135064,10 @@ var ts; } var parameters = typeNode.parameters.map(function (typedParam) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typedParam.dotDotDotToken, typedParam.name, typedParam.questionToken, /*type*/ undefined, typedParam.initializer); }); return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, @@ -133242,7 +135554,7 @@ var ts; } function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) { var typeChecker = program.getTypeChecker(); - var inUncheckedFile = isUncheckedFile(sourceFile, compilerOptions); + var inCheckedFile = isCheckedFile(sourceFile, compilerOptions); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -133486,6 +135798,7 @@ var ts; var hasUnresolvedAutoImports = false; // This also gets mutated in nested-functions after the return var symbols = []; + var importSpecifierResolver; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; var seenPropertySymbols = new ts.Map(); @@ -133657,15 +135970,7 @@ var ts; isNewIdentifierLocation = true; } var propertyAccess = node.kind === 200 /* SyntaxKind.ImportType */ ? node : node.parent; - if (inUncheckedFile) { - // In javascript files, for union types, we don't just get the members that - // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part - // of the individual types to a higher status since we know what they are. - symbols.push.apply(symbols, ts.filter(getPropertiesForCompletion(type, typeChecker), function (s) { return typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s); })); - } - else { + if (inCheckedFile) { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) { @@ -133673,6 +135978,14 @@ var ts; } } } + else { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + symbols.push.apply(symbols, ts.filter(getPropertiesForCompletion(type, typeChecker), function (s) { return typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s); })); + } if (insertAwait && preferences.includeCompletionsWithInsertText) { var promiseType = typeChecker.getPromisedTypeOfPromise(type); if (promiseType) { @@ -133707,14 +136020,14 @@ var ts; } else { var fileName = ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? (_a = ts.getSourceFileOfModule(moduleSymbol)) === null || _a === void 0 ? void 0 : _a.fileName : undefined; - var moduleSpecifier = (ts.codefix.getModuleSpecifierForBestExportInfo([{ + var moduleSpecifier = ((importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo([{ exportKind: 0 /* ExportKind.Named */, moduleFileName: fileName, isFromPackageJson: false, moduleSymbol: moduleSymbol, symbol: firstAccessibleSymbol, targetFlags: ts.skipAlias(firstAccessibleSymbol, typeChecker).flags, - }], firstAccessibleSymbol.name, position, ts.isValidTypeOnlyAliasUseSite(location), sourceFile, program, host, preferences) || {}).moduleSpecifier; + }], firstAccessibleSymbol.name, position, ts.isValidTypeOnlyAliasUseSite(location)) || {}).moduleSpecifier; if (moduleSpecifier) { var origin = { kind: getNullableSymbolOriginInfoKind(6 /* SymbolOriginInfoKind.SymbolMemberExport */), @@ -133864,7 +136177,7 @@ var ts; } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 305 /* SyntaxKind.SourceFile */) { - var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); + var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false, ts.isClassLike(scopeNode.parent) ? scopeNode : undefined); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { var symbol = _a[_i]; @@ -133967,10 +136280,10 @@ var ts; previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); - var exportInfo = ts.getExportInfoMap(sourceFile, host, program, cancellationToken); + var exportInfo = ts.getExportInfoMap(sourceFile, host, program, preferences, cancellationToken); var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); - resolvingModuleSpecifiers("collectAutoImports", host, program, sourceFile, position, preferences, !!importCompletionNode, ts.isValidTypeOnlyAliasUseSite(location), function (context) { + resolvingModuleSpecifiers("collectAutoImports", host, importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences)), program, position, preferences, !!importCompletionNode, ts.isValidTypeOnlyAliasUseSite(location), function (context) { exportInfo.search(sourceFile.path, /*preferCapitalized*/ isRightOfOpenTag, function (symbolName, targetFlags) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) @@ -135067,6 +137380,7 @@ var ts; return kind === 131 /* SyntaxKind.AsyncKeyword */ || kind === 132 /* SyntaxKind.AwaitKeyword */ || kind === 127 /* SyntaxKind.AsKeyword */ + || kind === 152 /* SyntaxKind.TypeKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { @@ -135166,6 +137480,10 @@ var ts; } break; case 79 /* SyntaxKind.Identifier */: { + var originalKeywordKind = location.originalKeywordKind; + if (originalKeywordKind && ts.isKeyword(originalKeywordKind)) { + return undefined; + } // class c { public prop = c| } if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) { return undefined; @@ -135953,60 +138271,64 @@ var ts; } return settingsOrHost; } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings)); - return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions); } - function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind, languageVersionOrOptions); } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings)); - return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions); } - function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { + return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind, languageVersionOrOptions); } function getDocumentRegistryEntry(bucketEntry, scriptKind) { var entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(ts.Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:".concat(scriptKind, " and sourceFile.scriptKind: ").concat(entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind, ", !entry: ").concat(!entry)); return entry; } - function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version, acquiring, scriptKind) { + function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version, acquiring, scriptKind, languageVersionOrOptions) { var _a, _b, _c, _d; scriptKind = ts.ensureScriptKind(fileName, scriptKind); var compilationSettings = getCompilationSettings(compilationSettingsOrHost); var host = compilationSettingsOrHost === compilationSettings ? undefined : compilationSettingsOrHost; var scriptTarget = scriptKind === 6 /* ScriptKind.JSON */ ? 100 /* ScriptTarget.JSON */ : ts.getEmitScriptTarget(compilationSettings); - var sourceFileOptions = { - languageVersion: scriptTarget, - impliedNodeFormat: host && ts.getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getModuleResolutionCache) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(compilationSettings) - }; + var sourceFileOptions = typeof languageVersionOrOptions === "object" ? + languageVersionOrOptions : + { + languageVersion: scriptTarget, + impliedNodeFormat: host && ts.getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getModuleResolutionCache) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), + setExternalModuleIndicator: ts.getSetExternalModuleIndicator(compilationSettings) + }; + sourceFileOptions.languageVersion = scriptTarget; var oldBucketCount = buckets.size; - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var keyWithMode = getDocumentRegistryBucketKeyWithMode(key, sourceFileOptions.impliedNodeFormat); + var bucket = ts.getOrUpdate(buckets, keyWithMode, function () { return new ts.Map(); }); if (ts.tracing) { if (buckets.size > oldBucketCount) { // It is interesting, but not definitively problematic if a build requires multiple document registry buckets - // perhaps they are for two projects that don't have any overlap. // Bonus: these events can help us interpret the more interesting event below. - ts.tracing.instant("session" /* tracing.Phase.Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: key }); + ts.tracing.instant("session" /* tracing.Phase.Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: keyWithMode }); } // It is fairly suspicious to have one path in two buckets - you'd expect dependencies to have similar configurations. // If this occurs unexpectedly, the fix is likely to synchronize the project settings. // Skip .d.ts files to reduce noise (should also cover most of node_modules). var otherBucketKey = !ts.isDeclarationFileName(path) && - ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== key && bucket.has(path) && bucketKey; }); + ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== keyWithMode && bucket.has(path) && bucketKey; }); if (otherBucketKey) { - ts.tracing.instant("session" /* tracing.Phase.Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: key }); + ts.tracing.instant("session" /* tracing.Phase.Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: keyWithMode }); } } var bucketEntry = bucket.get(path); var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { - var sourceFile = externalCache.getDocument(key, path); + var sourceFile = externalCache.getDocument(keyWithMode, path); if (sourceFile) { ts.Debug.assert(acquiring); entry = { @@ -136020,7 +138342,7 @@ var ts; // Have never seen this file with these settings. Create a new source file for it. var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, sourceFileOptions, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { - externalCache.setDocument(key, path, sourceFile); + externalCache.setDocument(keyWithMode, path, sourceFile); } entry = { sourceFile: sourceFile, @@ -136035,7 +138357,7 @@ var ts; if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 if (externalCache) { - externalCache.setDocument(key, path, entry.sourceFile); + externalCache.setDocument(keyWithMode, path, entry.sourceFile); } } // If we're acquiring, then this is the first time this LS is asking for this document. @@ -136064,13 +138386,13 @@ var ts; } } } - function releaseDocument(fileName, compilationSettings, scriptKind) { + function releaseDocument(fileName, compilationSettings, scriptKind, impliedNodeFormat) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key, scriptKind); + return releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat); } - function releaseDocumentWithKey(path, key, scriptKind) { - var bucket = ts.Debug.checkDefined(buckets.get(key)); + function releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat) { + var bucket = ts.Debug.checkDefined(buckets.get(getDocumentRegistryBucketKeyWithMode(key, impliedNodeFormat))); var bucketEntry = bucket.get(path); var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; @@ -136118,7 +138440,7 @@ var ts; } var str = "{"; for (var key in value) { - if (ts.hasOwnProperty.call(value, key)) { // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier + if (ts.hasProperty(value, key)) { str += "".concat(key, ": ").concat(compilerOptionValueToString(value[key])); } } @@ -136127,6 +138449,9 @@ var ts; function getKeyForCompilationSettings(settings) { return ts.sourceFileAffectingCompilerOptions.map(function (option) { return compilerOptionValueToString(ts.getCompilerOptionValue(settings, option)); }).join("|") + (settings.pathsBasePath ? "|".concat(settings.pathsBasePath) : undefined); } + function getDocumentRegistryBucketKeyWithMode(key, mode) { + return (mode ? "".concat(key, "|").concat(mode) : key); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -136259,7 +138584,7 @@ var ts; return ts.findAncestor(node, function (node) { if (stopAtAmbientModule && isAmbientModuleDeclaration(node)) return "quit"; - return ts.some(node.modifiers, function (mod) { return mod.kind === 93 /* SyntaxKind.ExportKeyword */; }); + return ts.canHaveModifiers(node) && ts.some(node.modifiers, ts.isExportModifier); }); } function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { @@ -136683,7 +139008,7 @@ var ts; ts.Debug.assert(parent.name === node); return true; case 203 /* SyntaxKind.BindingElement */: - return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent); + return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent.parent.parent); default: return false; } @@ -136942,18 +139267,18 @@ var ts; || node.kind === 106 /* SyntaxKind.SuperKeyword */) { referenceEntries = entries && __spreadArray([], entries, true); } - else { - var queue = entries && __spreadArray([], entries, true); + else if (entries) { + var queue = ts.createQueue(entries); var seenNodes = new ts.Map(); - while (queue && queue.length) { - var entry = queue.shift(); + while (!queue.isEmpty()) { + var entry = queue.dequeue(); if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) { continue; } referenceEntries = ts.append(referenceEntries, entry); var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); if (entries_1) { - queue.push.apply(queue, entries_1); + queue.enqueue.apply(queue, entries_1); } } } @@ -137209,6 +139534,7 @@ var ts; var commonjsSource = source && ts.isBinaryExpression(source) ? source.left : undefined; return !!(source && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === source || d === commonjsSource; }))); } + FindAllReferences.isDeclarationOfSymbol = isDeclarationOfSymbol; /** * True if 'decl' provides a value, as in `function f() {}`; * false if 'decl' is just a location for a future write, as in 'let x;' @@ -137415,7 +139741,7 @@ var ts; result = references; continue; } - var _loop_5 = function (entry) { + var _loop_3 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* DefinitionKind.Symbol */) { result.push(entry); return "continue"; @@ -137447,7 +139773,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_5(entry); + _loop_3(entry); } } return result; @@ -138148,7 +140474,7 @@ var ts; // Use the parent symbol if the location is commonjs require syntax on javascript files only. if (ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 203 /* SyntaxKind.BindingElement */ - && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent)) { + && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) { referenceSymbol = referenceLocation.parent.symbol; // The parent will not have a symbol if it's an ObjectBindingPattern (when destructuring is used). In // this case, just skip it, since the bound identifiers are not an alias of the import. @@ -139028,8 +141354,8 @@ var ts; var declarations; if (symbol && symbol.declarations) { var indices = ts.indicesOf(symbol.declarations); - var keys_1 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); }); - indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_1[a].file, keys_1[b].file) || keys_1[a].pos - keys_1[b].pos; }); + var keys_2 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); }); + indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_2[a].file, keys_2[b].file) || keys_2[a].pos - keys_2[b].pos; }); var sortedDeclarations = ts.map(indices, function (i) { return symbol.declarations[i]; }); var lastDecl = void 0; for (var _i = 0, sortedDeclarations_1 = sortedDeclarations; _i < sortedDeclarations_1.length; _i++) { @@ -139299,14 +141625,16 @@ var ts; collect(node.body); } function collectCallSitesOfClassLikeDeclaration(node, collect) { - ts.forEach(node.decorators, collect); + ts.forEach(node.modifiers, collect); var heritage = ts.getClassExtendsHeritageElement(node); if (heritage) { collect(heritage.expression); } for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - ts.forEach(member.decorators, collect); + if (ts.canHaveModifiers(member)) { + ts.forEach(member.modifiers, collect); + } if (ts.isPropertyDeclaration(member)) { collect(member.initializer); } @@ -139475,7 +141803,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_6 = function (sourceFile) { + var _loop_4 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -139507,7 +141835,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_6(sourceFile); + _loop_4(sourceFile); } } function combineNormal(pathA, pathB) { @@ -140149,11 +142477,12 @@ var ts; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var jsdoc = _a[_i]; + var inheritDoc = ts.isJSDoc(jsdoc) && jsdoc.tags && ts.find(jsdoc.tags, function (t) { return t.kind === 327 /* SyntaxKind.JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc"); }); // skip comments containing @typedefs since they're not associated with particular declarations // Exceptions: // - @typedefs are themselves declarations with associated comments // - @param or @return indicate that the author thinks of it as a 'local' @typedef that's part of the function documentation - if (jsdoc.comment === undefined + if (jsdoc.comment === undefined && !inheritDoc || ts.isJSDoc(jsdoc) && declaration.kind !== 345 /* SyntaxKind.JSDocTypedefTag */ && declaration.kind !== 338 /* SyntaxKind.JSDocCallbackTag */ && jsdoc.tags @@ -140161,7 +142490,10 @@ var ts; && !jsdoc.tags.some(function (t) { return t.kind === 340 /* SyntaxKind.JSDocParameterTag */ || t.kind === 341 /* SyntaxKind.JSDocReturnTag */; })) { continue; } - var newparts = getDisplayPartsFromComment(jsdoc.comment, checker); + var newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : []; + if (inheritDoc && inheritDoc.comment) { + newparts = newparts.concat(getDisplayPartsFromComment(inheritDoc.comment, checker)); + } if (!ts.contains(parts, newparts, isIdenticalListOfDisplayParts)) { parts.push(newparts); } @@ -140395,8 +142727,12 @@ var ts; return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters, hasReturn = commentOwnerInfo.hasReturn; - var commentOwnerJSDoc = ts.hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? ts.lastOrUndefined(commentOwner.jsDoc) : undefined; - if (commentOwner.getStart(sourceFile) < position || commentOwnerJSDoc && commentOwnerJSDoc !== existingDocComment) { + var commentOwnerJsDoc = ts.hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : undefined; + var lastJsDoc = ts.lastOrUndefined(commentOwnerJsDoc); + if (commentOwner.getStart(sourceFile) < position + || lastJsDoc + && existingDocComment + && lastJsDoc !== existingDocComment) { return undefined; } var indentationStr = getIndentationStringAtPosition(sourceFile, position); @@ -140413,7 +142749,9 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var openComment = "/**"; var closeComment = " */"; - if (tags) { + // If any of the existing jsDoc has tags, ignore adding new ones. + var hasTag = (commentOwnerJsDoc || []).some(function (jsDoc) { return !!jsDoc.tags; }); + if (tags && !hasTag) { var preamble = openComment + newLine + indentationStr + " * "; var endLine = tokenStart === position ? newLine + indentationStr : ""; var result = preamble + newLine + tags + indentationStr + closeComment + endLine; @@ -140527,7 +142865,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_7 = function (sourceFile) { + var _loop_5 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -140539,7 +142877,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_7(sourceFile); + _loop_5(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -141135,7 +143473,7 @@ var ts; isPossibleConstructor(b.node) ? b.node : undefined; if (ctorFunction !== undefined) { - var ctorNode = ts.setTextRange(ts.factory.createConstructorDeclaration(/* decorators */ undefined, /* modifiers */ undefined, [], /* body */ undefined), ctorFunction); + var ctorNode = ts.setTextRange(ts.factory.createConstructorDeclaration(/* modifiers */ undefined, [], /* body */ undefined), ctorFunction); var ctor = emptyNavigationBarNode(ctorNode); ctor.indent = a.indent + 1; ctor.children = a.node === ctorFunction ? a.children : b.children; @@ -141151,7 +143489,6 @@ var ts; } } lastANode = a.node = ts.setTextRange(ts.factory.createClassDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, a.name || ts.factory.createIdentifier("__class__"), /* typeParameters */ undefined, /* heritageClauses */ undefined, []), a.node); @@ -141176,7 +143513,6 @@ var ts; if (!a.additionalNodes) a.additionalNodes = []; a.additionalNodes.push(ts.setTextRange(ts.factory.createClassDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, a.name || ts.factory.createIdentifier("__class__"), /* typeParameters */ undefined, /* heritageClauses */ undefined, []), b.node)); @@ -141685,7 +144021,7 @@ var ts; else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) { // If we’re in a declaration file, it’s safe to remove the import clause from it if (sourceFile.isDeclarationFile) { - usedImports.push(ts.factory.createImportDeclaration(importDecl.decorators, importDecl.modifiers, + usedImports.push(ts.factory.createImportDeclaration(importDecl.modifiers, /*importClause*/ undefined, moduleSpecifier, /*assertClause*/ undefined)); } @@ -141851,7 +144187,7 @@ var ts; newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(exportGroup_1, function (i) { return i.exportClause && ts.isNamedExports(i.exportClause) ? i.exportClause.elements : ts.emptyArray; })); var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); var exportDecl = exportGroup_1[0]; - coalescedExports.push(ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ? + coalescedExports.push(ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ? ts.factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : ts.factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.assertClause)); } @@ -141888,7 +144224,7 @@ var ts; } OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 + return ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, ts.factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 importDeclaration.moduleSpecifier, importDeclaration.assertClause); } function sortSpecifiers(specifiers) { @@ -142604,13 +144940,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_8 = function (start) { + var _loop_6 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_8(start); + var state_3 = _loop_6(start); if (typeof state_3 === "object") return state_3.value; } @@ -143196,10 +145532,10 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(program, sourceFile, position, options) { + function getRenameInfo(program, sourceFile, position, preferences) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, preferences); if (renameInfo) { return renameInfo; } @@ -143207,7 +145543,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, preferences) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -143235,7 +145571,12 @@ var ts; return undefined; } if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { - return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + return preferences.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + } + // Disallow rename for elements that would rename across `*/node_modules/*` packages. + var wouldRenameNodeModules = wouldRenameInOtherNodeModules(sourceFile, symbol, typeChecker, preferences); + if (wouldRenameNodeModules) { + return getRenameInfoError(wouldRenameNodeModules); } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) @@ -143249,6 +145590,49 @@ var ts; var sourceFile = declaration.getSourceFile(); return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Extension.Dts */); } + function wouldRenameInOtherNodeModules(originalFile, symbol, checker, preferences) { + if (!preferences.providePrefixAndSuffixTextForRename && symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var importSpecifier = symbol.declarations && ts.find(symbol.declarations, function (decl) { return ts.isImportSpecifier(decl); }); + if (importSpecifier && !importSpecifier.propertyName) { + symbol = checker.getAliasedSymbol(symbol); + } + } + var declarations = symbol.declarations; + if (!declarations) { + return undefined; + } + var originalPackage = getPackagePathComponents(originalFile.path); + if (originalPackage === undefined) { // original source file is not in node_modules + if (ts.some(declarations, function (declaration) { return ts.isInsideNodeModules(declaration.getSourceFile().path); })) { + return ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder; + } + else { + return undefined; + } + } + // original source file is in node_modules + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + var declPackage = getPackagePathComponents(declaration.getSourceFile().path); + if (declPackage) { + var length_2 = Math.min(originalPackage.length, declPackage.length); + for (var i = 0; i <= length_2; i++) { + if (ts.compareStringsCaseSensitive(originalPackage[i], declPackage[i]) !== 0 /* Comparison.EqualTo */) { + return ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder; + } + } + } + } + return undefined; + } + function getPackagePathComponents(filePath) { + var components = ts.getPathComponents(filePath); + var nodeModulesIdx = components.lastIndexOf("node_modules"); + if (nodeModulesIdx === -1) { + return undefined; + } + return components.slice(0, nodeModulesIdx + 2); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); @@ -143319,7 +145703,7 @@ var ts; var SmartSelectionRange; (function (SmartSelectionRange) { function getSmartSelectionRange(pos, sourceFile) { - var _a; + var _a, _b; var selectionRange = { textSpan: ts.createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd()) }; @@ -143371,6 +145755,17 @@ var ts; if (ts.hasJSDocNodes(node) && ((_a = node.jsDoc) === null || _a === void 0 ? void 0 : _a.length)) { pushSelectionRange(ts.first(node.jsDoc).getStart(), end); } + // (#39618 & #49807) + // When the node is a SyntaxList and its first child has a JSDoc comment, then the node's + // `start` (which usually is the result of calling `node.getStart()`) points to the first + // token after the JSDoc comment. So, we have to make sure we'd pushed the selection + // covering the JSDoc comment before diving further. + if (ts.isSyntaxList(node)) { + var firstChild = node.getChildren()[0]; + if (firstChild && ts.hasJSDocNodes(firstChild) && ((_b = firstChild.jsDoc) === null || _b === void 0 ? void 0 : _b.length) && firstChild.getStart() !== node.pos) { + start = Math.min(start, ts.first(firstChild.jsDoc).getStart()); + } + } pushSelectionRange(start, end); // String literals should have a stop both inside and outside their quotes. if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) { @@ -143444,6 +145839,7 @@ var ts; * other as well as of other top-level statements and declarations. */ function getSelectionChildren(node) { + var _a; // Group top-level imports if (ts.isSourceFile(node)) { return groupChildren(node.getChildAt(0).getChildren(), isImport); @@ -143459,7 +145855,7 @@ var ts; // because it allows the mapped type to become an object type with a // few keystrokes. if (ts.isMappedTypeNode(node)) { - var _a = node.getChildren(), openBraceToken = _a[0], children = _a.slice(1); + var _b = node.getChildren(), openBraceToken = _b[0], children = _b.slice(1); var closeBraceToken = ts.Debug.checkDefined(children.pop()); ts.Debug.assertEqual(openBraceToken.kind, 18 /* SyntaxKind.OpenBraceToken */); ts.Debug.assertEqual(closeBraceToken.kind, 19 /* SyntaxKind.CloseBraceToken */); @@ -143490,10 +145886,13 @@ var ts; var children = groupChildren(node.getChildren(), function (child) { return child === node.name || ts.contains(node.modifiers, child); }); - return splitChildren(children, function (_a) { + var firstJSDocChild = ((_a = children[0]) === null || _a === void 0 ? void 0 : _a.kind) === 320 /* SyntaxKind.JSDoc */ ? children[0] : undefined; + var withJSDocSeparated = firstJSDocChild ? children.slice(1) : children; + var splittedChildren = splitChildren(withJSDocSeparated, function (_a) { var kind = _a.kind; return kind === 58 /* SyntaxKind.ColonToken */; }); + return firstJSDocChild ? [firstJSDocChild, createSyntaxList(splittedChildren)] : splittedChildren; } // Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`. if (ts.isParameter(node)) { @@ -144029,7 +146428,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_9 = function (n) { + var _loop_7 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: ".concat(ts.Debug.formatSyntaxKind(n.kind), ", parent: ").concat(ts.Debug.formatSyntaxKind(n.parent.kind)); }); @@ -144039,7 +146438,7 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_4 = _loop_9(n); + var state_4 = _loop_7(n); if (typeof state_4 === "object") return state_4.value; } @@ -144238,7 +146637,7 @@ var ts; if (!ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { return; } - if (ts.isTypeNode(node)) { + if (ts.isTypeNode(node) && !ts.isExpressionWithTypeArguments(node)) { return; } if (preferences.includeInlayVariableTypeHints && ts.isVariableDeclaration(node)) { @@ -144303,7 +146702,7 @@ var ts; return type.symbol && (type.symbol.flags & 1536 /* SymbolFlags.Module */); } function visitVariableLikeDeclaration(decl) { - if (!decl.initializer || ts.isBindingPattern(decl.name)) { + if (!decl.initializer || ts.isBindingPattern(decl.name) || ts.isVariableDeclaration(decl) && !isHintableDeclaration(decl)) { return; } var effectiveTypeAnnotation = ts.getEffectiveTypeAnnotationNode(decl); @@ -144316,6 +146715,10 @@ var ts; } var typeDisplayString = printTypeInSingleLine(declarationType); if (typeDisplayString) { + var isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && ts.equateStringsCaseInsensitive(decl.name.getText(), typeDisplayString); + if (isVariableNameMatchesType) { + return; + } addTypeHints(typeDisplayString, decl.name.end); } } @@ -144427,6 +146830,9 @@ var ts; } for (var i = 0; i < node.parameters.length && i < signature.parameters.length; ++i) { var param = node.parameters[i]; + if (!isHintableDeclaration(param)) { + continue; + } var effectiveTypeAnnotation = ts.getEffectiveTypeAnnotationNode(param); if (effectiveTypeAnnotation) { continue; @@ -144468,6 +146874,13 @@ var ts; function isUndefined(name) { return name === "undefined"; } + function isHintableDeclaration(node) { + if ((ts.isParameterDeclaration(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) && node.initializer) { + var initializer = ts.skipParentheses(node.initializer); + return !(isHintableLiteral(initializer) || ts.isNewExpression(initializer) || ts.isObjectLiteralExpression(initializer) || ts.isAssertionExpression(initializer)); + } + return true; + } } InlayHints.provideInlayHints = provideInlayHints; })(InlayHints = ts.InlayHints || (ts.InlayHints = {})); @@ -145638,7 +148051,7 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_10 = function (opt) { + var _loop_8 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -145657,7 +148070,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_10(opt); + _loop_8(opt); } return options; } @@ -146607,7 +149020,7 @@ var ts; } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - !!context.contextNode.decorators && + ts.hasDecorators(context.contextNode) && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -147172,6 +149585,7 @@ var ts; var options = _a.options, getRules = _a.getRules, host = _a.host; // formatting context is used by rules provider var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); + var previousRangeTriviaEnd; var previousRange; var previousParent; var previousRangeStartLine; @@ -147182,7 +149596,7 @@ var ts; if (formattingScanner.isOnToken()) { var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; var undecoratedStartLine = startLine; - if (enclosingNode.decorators) { + if (ts.hasDecorators(enclosingNode)) { undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; } processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); @@ -147200,10 +149614,30 @@ var ts; } } if (previousRange && formattingScanner.getStartPos() >= originalRange.end) { + // Formatting edits happen by looking at pairs of contiguous tokens (see `processPair`), + // typically inserting or deleting whitespace between them. The recursive `processNode` + // logic above bails out as soon as it encounters a token that is beyond the end of the + // range we're supposed to format (or if we reach the end of the file). But this potentially + // leaves out an edit that would occur *inside* the requested range but cannot be discovered + // without looking at one token *beyond* the end of the range: consider the line `x = { }` + // with a selection from the beginning of the line to the space inside the curly braces, + // inclusive. We would expect a format-selection would delete the space (if rules apply), + // but in order to do that, we need to process the pair ["{", "}"], but we stopped processing + // just before getting there. This block handles this trailing edit. var tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : undefined; - if (tokenInfo) { + if (tokenInfo && tokenInfo.pos === previousRangeTriviaEnd) { + // We need to check that tokenInfo and previousRange are contiguous: the `originalRange` + // may have ended in the middle of a token, which means we will have stopped formatting + // on that token, leaving `previousRange` pointing to the token before it, but already + // having moved the formatting scanner (where we just got `tokenInfo`) to the next token. + // If this happens, our supposed pair [previousRange, tokenInfo] actually straddles the + // token that intersects the end of the range we're supposed to format, so the pair will + // produce bogus edits if we try to `processPair`. Recall that the point of this logic is + // to perform a trailing edit at the end of the selection range: but there can be no valid + // edit in the middle of a token where the range ended, so if we have a non-contiguous + // pair here, we're already done and we can ignore it. var parent = ((_b = ts.findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)) === null || _b === void 0 ? void 0 : _b.parent) || previousParent; processPair(tokenInfo, sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line, parent, previousRange, previousRangeStartLine, previousParent, parent, /*dynamicIndentation*/ undefined); @@ -147269,8 +149703,10 @@ var ts; } } function getFirstNonDecoratorTokenOfNode(node) { - if (node.modifiers && node.modifiers.length) { - return node.modifiers[0].kind; + if (ts.canHaveModifiers(node)) { + var modifier = ts.find(node.modifiers, ts.isModifier, ts.findIndex(node.modifiers, ts.isDecorator)); + if (modifier) + return modifier.kind; } switch (node.kind) { case 257 /* SyntaxKind.ClassDeclaration */: return 84 /* SyntaxKind.ClassKeyword */; @@ -147345,7 +149781,6 @@ var ts; case 280 /* SyntaxKind.JsxOpeningElement */: case 281 /* SyntaxKind.JsxClosingElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: return false; } break; @@ -147359,7 +149794,7 @@ var ts; // if token line equals to the line of containing node (this is a first token in the node) - use node indentation return nodeStartLine !== line // if this token is the first token following the list of decorators, we do not need to indent - && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + && !(ts.hasDecorators(node) && kind === getFirstNonDecoratorTokenOfNode(node)); } function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node @@ -147399,13 +149834,14 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { + ts.Debug.assert(!ts.nodeIsSynthesized(child)); if (ts.nodeIsMissing(child)) { return inheritedIndentation; } var childStartPos = child.getStart(sourceFile); var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; var undecoratedChildStartLine = childStartLine; - if (child.decorators) { + if (ts.hasDecorators(child)) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } // if child is a list item - try to get its indentation, only if parent is within the original range. @@ -147465,6 +149901,7 @@ var ts; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); + ts.Debug.assert(!ts.nodeIsSynthesized(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; @@ -147515,12 +149952,10 @@ var ts; var listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== 0 /* SyntaxKind.Unknown */ && formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(parent); - if (tokenInfo.token.kind === 27 /* SyntaxKind.CommaToken */ && ts.isCallLikeExpression(parent)) { - var commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - if (startLine !== commaTokenLine) { - formattingScanner.advance(); - tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; - } + if (tokenInfo.token.kind === 27 /* SyntaxKind.CommaToken */) { + // consume the comma + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one @@ -147560,6 +149995,7 @@ var ts; } } if (currentTokenInfo.trailingTrivia) { + previousRangeTriviaEnd = ts.last(currentTokenInfo.trailingTrivia).end; processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); } if (indentToken) { @@ -147630,6 +150066,7 @@ var ts; } } previousRange = range; + previousRangeTriviaEnd = range.end; previousParent = parent; previousRangeStartLine = rangeStart.line; return lineAction; @@ -147921,6 +150358,12 @@ var ts; case 169 /* SyntaxKind.MethodDeclaration */: case 168 /* SyntaxKind.MethodSignature */: case 214 /* SyntaxKind.ArrowFunction */: + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: if (node.typeParameters === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -147937,7 +150380,19 @@ var ts; return 20 /* SyntaxKind.OpenParenToken */; } break; + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 258 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.TypeAliasDeclaration */: + if (node.typeParameters === list) { + return 29 /* SyntaxKind.LessThanToken */; + } + break; case 178 /* SyntaxKind.TypeReference */: + case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 181 /* SyntaxKind.TypeQuery */: + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 200 /* SyntaxKind.ImportType */: if (node.typeArguments === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -149201,7 +151656,7 @@ var ts; return { indentation: indentation, prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter, - suffix: insertTrailingComma ? "," : "" + suffix: insertTrailingComma ? "," : ts.isInterfaceDeclaration(node) && isEmpty ? ";" : "" }; }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -149405,7 +151860,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_11 = function (sourceFile, node) { + var _loop_9 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -149418,7 +151873,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_11(sourceFile, node); + _loop_9(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -149506,14 +151961,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_12 = function (i) { + var _loop_10 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return "".concat(JSON.stringify(normalized[i].range), " and ").concat(JSON.stringify(normalized[i + 1].range)); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_12(i); + _loop_10(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -150224,7 +152679,6 @@ var ts; var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { var exportDeclaration = ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([]), /*moduleSpecifier*/ undefined); @@ -150422,7 +152876,7 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_13 = function (identifier) { + var _loop_11 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; @@ -150455,7 +152909,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_13(identifier); + _loop_11(identifier); } return initializers && { initializers: initializers, @@ -150754,8 +153208,7 @@ var ts; ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); var typeNode = ts.factory.createTypeReferenceNode(param.name, /*typeArguments*/ undefined); - var replacement = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); + var replacement = ts.factory.createParameterDeclaration(param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); changeTracker.replaceNode(sourceFile, param, replacement); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -150980,7 +153433,7 @@ var ts; var isRest = node.type.kind === 318 /* SyntaxKind.JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : node.dotDotDotToken; - return ts.factory.createParameterDeclaration(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + return ts.factory.createParameterDeclaration(node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); } function transformJSDocTypeReference(node) { var name = node.typeName; @@ -151015,12 +153468,11 @@ var ts; } function transformJSDocIndexSignature(node) { var index = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "n" : "s", /*questionToken*/ undefined, ts.factory.createTypeReferenceNode(node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "number" : "string", []), /*initializer*/ undefined); - var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*modifiers*/ undefined, [index], node.typeArguments[1])]); ts.setEmitFlags(indexSignature, 1 /* EmitFlags.SingleLine */); return indexSignature; } @@ -151162,7 +153614,7 @@ var ts; ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { - members.push(ts.factory.createPropertyDeclaration([], modifiers, symbol.name, /*questionToken*/ undefined, + members.push(ts.factory.createPropertyDeclaration(modifiers, symbol.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); return; } @@ -151198,7 +153650,7 @@ var ts; return; if (!ts.isPropertyAccessExpression(memberDeclaration)) return; - var prop = ts.factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); + var prop = ts.factory.createPropertyDeclaration(modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); members.push(prop); return; @@ -151211,7 +153663,7 @@ var ts; } function createFunctionExpressionMember(members, functionExpression, name) { var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 131 /* SyntaxKind.AsyncKeyword */)); - var method = ts.factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); @@ -151229,7 +153681,7 @@ var ts; bodyBlock = ts.factory.createBlock([ts.factory.createReturnStatement(arrowFunctionBody)]); } var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 131 /* SyntaxKind.AsyncKeyword */)); - var method = ts.factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); @@ -151243,10 +153695,10 @@ var ts; } var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { - memberElements.unshift(ts.factory.createConstructorDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, initializer.parameters, initializer.body)); } var modifiers = getModifierKindFromSource(node.parent.parent, 93 /* SyntaxKind.ExportKeyword */); - var cls = ts.factory.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + var cls = ts.factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; @@ -151254,17 +153706,17 @@ var ts; function createClassFromFunctionDeclaration(node) { var memberElements = createClassElementsFromSymbol(ctorSymbol); if (node.body) { - memberElements.unshift(ts.factory.createConstructorDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, node.parameters, node.body)); } var modifiers = getModifierKindFromSource(node, 93 /* SyntaxKind.ExportKeyword */); - var cls = ts.factory.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + var cls = ts.factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } } function getModifierKindFromSource(source, kind) { - return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + return ts.canHaveModifiers(source) ? ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }) : undefined; } function isConstructorAssignment(x) { if (!x.name) @@ -151340,12 +153792,9 @@ var ts; if (!returnStatements.length) { return; } - var pos = functionToConvert.modifiers ? functionToConvert.modifiers.end : - functionToConvert.decorators ? ts.skipTrivia(sourceFile.text, functionToConvert.decorators.end) : - functionToConvert.getStart(sourceFile); - var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; - changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, options); - var _loop_14 = function (returnStatement) { + var pos = ts.skipTrivia(sourceFile.text, ts.moveRangePastModifiers(functionToConvert).pos); + changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, { suffix: " " }); + var _loop_12 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); @@ -151367,7 +153816,7 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - var state_5 = _loop_14(returnStatement); + var state_5 = _loop_12(returnStatement); if (typeof state_5 === "object") return state_5.value; } @@ -152470,12 +154919,10 @@ var ts; } // Node helpers function functionExpressionToDeclaration(name, additionalModifiers, fn, useSitesToUnqualify) { - return ts.factory.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); + return ts.factory.createFunctionDeclaration(ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); } function classExpressionToDeclaration(name, additionalModifiers, cls, useSitesToUnqualify) { - return ts.factory.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); + return ts.factory.createClassDeclaration(ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); } function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" @@ -152490,7 +154937,6 @@ var ts; } function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { return ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, exportSpecifiers && ts.factory.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.factory.createStringLiteral(moduleSpecifier)); } @@ -152579,11 +155025,10 @@ var ts; changes.insertModifierBefore(context.sourceFile, 152 /* SyntaxKind.TypeKeyword */, exportClause); } else { - var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.decorators, exportDeclaration.modifiers, + var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, /*isTypeOnly*/ false, ts.factory.updateNamedExports(exportClause, ts.filter(exportClause.elements, function (e) { return !ts.contains(typeExportSpecifiers, e); })), exportDeclaration.moduleSpecifier, /*assertClause*/ undefined); var typeExportDeclaration = ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ true, ts.factory.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, /*assertClause*/ undefined); @@ -152647,7 +155092,6 @@ var ts; if (importClause.name && importClause.namedBindings) { changes.deleteNodeRangeExcludingEnd(context.sourceFile, importClause.name, importDeclaration.importClause.namedBindings); changes.insertNodeBefore(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ true, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, @@ -153001,6 +155445,18 @@ var ts; return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0; } } + function createImportSpecifierResolver(importingFile, program, host, preferences) { + var packageJsonImportFilter = ts.createPackageJsonImportFilter(importingFile, preferences, host); + var importMap = createExistingImportMap(program.getTypeChecker(), importingFile, program.getCompilerOptions()); + return { getModuleSpecifierForBestExportInfo: getModuleSpecifierForBestExportInfo }; + function getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, fromCacheOnly) { + var _a = getImportFixes(exportInfo, { symbolName: symbolName, position: position }, isValidTypeOnlyUseSite, + /*useRequire*/ false, program, importingFile, host, preferences, importMap, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount; + var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host); + return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount }); + } + } + codefix.createImportSpecifierResolver = createImportSpecifierResolver; // Sorted with the preferred fix coming first. var ImportFixKind; (function (ImportFixKind) { @@ -153078,7 +155534,7 @@ var ts; var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); }); - ts.forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { + ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(importingFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { @@ -153101,18 +155557,12 @@ var ts; return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, preferences, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); } } - function getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, importingFile, program, host, preferences, packageJsonImportFilter, fromCacheOnly) { - var _a = getImportFixes(exportInfo, { symbolName: symbolName, position: position }, isValidTypeOnlyUseSite, - /*useRequire*/ false, program, importingFile, host, preferences, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount; - var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter || ts.createPackageJsonImportFilter(importingFile, preferences, host), host); - return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount }); - } - codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo; function getImportFixes(exportInfos, useNamespaceInfo, /** undefined only for missing JSX namespace */ - isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, fromCacheOnly) { + isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap, fromCacheOnly) { + if (importMap === void 0) { importMap = createExistingImportMap(program.getTypeChecker(), sourceFile, program.getCompilerOptions()); } var checker = program.getTypeChecker(); - var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile, program.getCompilerOptions()); }); + var existingImports = ts.flatMap(exportInfos, importMap.getImportsForExportInfo); var useNamespace = useNamespaceInfo && tryUseExistingNamespaceImport(existingImports, useNamespaceInfo.symbolName, useNamespaceInfo.position, checker); var addToExisting = tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, program.getCompilerOptions()); if (addToExisting) { @@ -153240,21 +155690,37 @@ var ts; }; }); } - function getExistingImportDeclarations(_a, checker, importingFile, compilerOptions) { - var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, targetFlags = _a.targetFlags, symbol = _a.symbol; - // Can't use an es6 import for a type in JS. - if (!(targetFlags & 111551 /* SymbolFlags.Value */) && ts.isSourceFileJS(importingFile)) - return ts.emptyArray; - var importKind = getImportKind(importingFile, exportKind, compilerOptions); - return ts.mapDefined(importingFile.imports, function (moduleSpecifier) { + function createExistingImportMap(checker, importingFile, compilerOptions) { + var importMap; + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; var i = ts.importFromModuleSpecifier(moduleSpecifier); if (ts.isVariableDeclarationInitializedToRequire(i.parent)) { - return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind, symbol: symbol, targetFlags: targetFlags } : undefined; + var moduleSymbol = checker.resolveExternalModuleName(moduleSpecifier); + if (moduleSymbol) { + (importMap || (importMap = ts.createMultiMap())).add(ts.getSymbolId(moduleSymbol), i.parent); + } } - if (i.kind === 266 /* SyntaxKind.ImportDeclaration */ || i.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { - return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind, symbol: symbol, targetFlags: targetFlags } : undefined; + else if (i.kind === 266 /* SyntaxKind.ImportDeclaration */ || i.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol) { + (importMap || (importMap = ts.createMultiMap())).add(ts.getSymbolId(moduleSymbol), i); + } } - }); + } + return { + getImportsForExportInfo: function (_a) { + var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, targetFlags = _a.targetFlags, symbol = _a.symbol; + // Can't use an es6 import for a type in JS. + if (!(targetFlags & 111551 /* SymbolFlags.Value */) && ts.isSourceFileJS(importingFile)) + return ts.emptyArray; + var matchingDeclarations = importMap === null || importMap === void 0 ? void 0 : importMap.get(ts.getSymbolId(moduleSymbol)); + if (!matchingDeclarations) + return ts.emptyArray; + var importKind = getImportKind(importingFile, exportKind, compilerOptions); + return matchingDeclarations.map(function (declaration) { return ({ declaration: declaration, importKind: importKind, symbol: symbol, targetFlags: targetFlags }); }); + } + }; } function shouldUseRequire(sourceFile, program) { // 1. TypeScript files don't use require variable declarations @@ -153537,7 +156003,7 @@ var ts; originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol: moduleSymbol, moduleFileName: toFile === null || toFile === void 0 ? void 0 : toFile.fileName, exportKind: exportKind, targetFlags: ts.skipAlias(exportedSymbol, checker).flags, isFromPackageJson: isFromPackageJson }); } } - ts.forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { + ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); @@ -153797,10 +156263,8 @@ var ts; if (namespaceLikeImport) { var declaration = namespaceLikeImport.importKind === 3 /* ImportKind.CommonJS */ ? ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, needsTypeOnly(namespaceLikeImport), ts.factory.createIdentifier(namespaceLikeImport.name), ts.factory.createExternalModuleReference(quotedModuleSpecifier)) : ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(needsTypeOnly(namespaceLikeImport), /*name*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier, /*assertClause*/ undefined); @@ -153880,6 +156344,113 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingConstraint"; + var errorCodes = [ + // We want errors this could be attached to: + // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint + ts.Diagnostics.Type_0_is_not_comparable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + ts.Diagnostics.Property_0_is_incompatible_with_index_signature.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program, preferences = context.preferences, host = context.host; + var info = getInfo(program, sourceFile, span); + if (info === undefined) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingConstraint(t, program, preferences, host, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_extends_constraint, fixId, ts.Diagnostics.Add_extends_constraint_to_all_type_parameters)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var program = context.program, preferences = context.preferences, host = context.host; + var seen = new ts.Map(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(program, diag.file, ts.createTextSpan(diag.start, diag.length)); + if (info) { + if (ts.addToSeen(seen, ts.getNodeId(info.declaration))) { + return addMissingConstraint(changes, program, preferences, host, diag.file, info); + } + } + return undefined; + }); + })); + } + }); + function getInfo(program, sourceFile, span) { + var diag = ts.find(program.getSemanticDiagnostics(sourceFile), function (diag) { return diag.start === span.start && diag.length === span.length; }); + if (diag === undefined || diag.relatedInformation === undefined) + return; + var related = ts.find(diag.relatedInformation, function (related) { return related.code === ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code; }); + if (related === undefined || related.file === undefined || related.start === undefined || related.length === undefined) + return; + var declaration = findAncestorMatchingSpan(related.file, ts.createTextSpan(related.start, related.length)); + if (declaration === undefined) + return; + if (ts.isIdentifier(declaration) && ts.isTypeParameterDeclaration(declaration.parent)) { + declaration = declaration.parent; + } + if (ts.isTypeParameterDeclaration(declaration)) { + // should only issue fix on type parameters written using `extends` + if (ts.isMappedTypeNode(declaration.parent)) + return; + var token = ts.getTokenAtPosition(sourceFile, span.start); + var checker = program.getTypeChecker(); + var constraint = tryGetConstraintType(checker, token) || tryGetConstraintFromDiagnosticMessage(related.messageText); + return { constraint: constraint, declaration: declaration, token: token }; + } + return undefined; + } + function addMissingConstraint(changes, program, preferences, host, sourceFile, info) { + var declaration = info.declaration, constraint = info.constraint; + var checker = program.getTypeChecker(); + if (ts.isString(constraint)) { + changes.insertText(sourceFile, declaration.name.end, " extends ".concat(constraint)); + } + else { + var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions()); + var tracker = codefix.getNoopSymbolTrackerWithResolver({ program: program, host: host }); + var importAdder = codefix.createImportAdder(sourceFile, program, preferences, host); + var typeNode = codefix.typeToAutoImportableTypeNode(checker, importAdder, constraint, /*contextNode*/ undefined, scriptTarget, /*flags*/ undefined, tracker); + if (typeNode) { + changes.replaceNode(sourceFile, declaration, ts.factory.updateTypeParameterDeclaration(declaration, /*modifiers*/ undefined, declaration.name, typeNode, declaration.default)); + importAdder.writeFixes(changes); + } + } + } + function findAncestorMatchingSpan(sourceFile, span) { + var end = ts.textSpanEnd(span); + var token = ts.getTokenAtPosition(sourceFile, span.start); + while (token.end < end) { + token = token.parent; + } + return token; + } + function tryGetConstraintFromDiagnosticMessage(messageText) { + var _a = ts.flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || [], _ = _a[0], constraint = _a[1]; + return constraint; + } + function tryGetConstraintType(checker, node) { + if (ts.isTypeNode(node.parent)) { + return checker.getTypeArgumentConstraint(node.parent); + } + var contextualType = ts.isExpression(node) ? checker.getContextualType(node) : undefined; + return contextualType || checker.getTypeAtLocation(node); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -154002,10 +156573,11 @@ var ts; var staticModifier = ts.find(modifiers, ts.isStaticModifier); var abstractModifier = ts.find(modifiers, ts.isAbstractModifier); var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var lastDecorator = ts.findLast(modifiers, ts.isDecorator); var modifierPos = abstractModifier ? abstractModifier.end : staticModifier ? staticModifier.end : accessibilityModifier ? accessibilityModifier.end : - classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + lastDecorator ? ts.skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile); var options = accessibilityModifier || staticModifier || abstractModifier ? { prefix: " " } : { suffix: " " }; changeTracker.insertModifierAt(sourceFile, modifierPos, 159 /* SyntaxKind.OverrideKeyword */, options); } @@ -154015,7 +156587,7 @@ var ts; changeTracker.filterJSDocTags(sourceFile, classElement, ts.not(ts.isJSDocOverrideTag)); return; } - var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 159 /* SyntaxKind.OverrideKeyword */; }); + var overrideModifier = ts.find(classElement.modifiers, ts.isOverrideModifier); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); } @@ -154615,7 +157187,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, declaration) { var supers = ts.isTypeLiteralNode(declaration) ? undefined : codefix.getAllSupers(declaration, checker); - var _loop_15 = function (info) { + var _loop_13 = function (info) { // If some superclass added this property, don't add it again. if (supers === null || supers === void 0 ? void 0 : supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -154642,7 +157214,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_15(info); + _loop_13(info); } }); })); @@ -154694,7 +157266,7 @@ var ts; return undefined; return { kind: 4 /* InfoKind.JsxAttributes */, token: token, attributes: attributes, parentDeclaration: token.parent }; } - if (ts.isIdentifier(token) && ts.isCallExpression(parent)) { + if (ts.isIdentifier(token) && ts.isCallExpression(parent) && parent.expression === token) { return { kind: 2 /* InfoKind.Function */, token: token, call: parent, sourceFile: sourceFile, modifierFlags: 0 /* ModifierFlags.None */, parentDeclaration: sourceFile }; } if (!ts.isPropertyAccessExpression(parent)) @@ -154771,7 +157343,6 @@ var ts; } else if (ts.isPrivateIdentifier(token)) { var property = ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, tokenName, /*questionToken*/ undefined, /*type*/ undefined, @@ -154829,7 +157400,7 @@ var ts; function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) { var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var property = ts.isClassLike(node) - ? ts.factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined) + ? ts.factory.createPropertyDeclaration(modifiers, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined) : ts.factory.createPropertySignature(/*modifiers*/ undefined, tokenName, /*questionToken*/ undefined, typeNode); var lastProp = getNodeToInsertPropertyAfter(node); if (lastProp) { @@ -154854,13 +157425,11 @@ var ts; // Index signatures cannot have the static modifier. var stringTypeNode = ts.factory.createKeywordTypeNode(150 /* SyntaxKind.StringKeyword */); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); var indexSignature = ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertMemberAtStart(sourceFile, node, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. @@ -154908,7 +157477,7 @@ var ts; return !!(type && type.flags & 402653316 /* TypeFlags.StringLike */); }); var enumMember = ts.factory.createEnumMember(token, hasStringInitializer ? ts.factory.createStringLiteral(token.text) : undefined); - changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.decorators, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), { + changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude }); @@ -154917,6 +157486,7 @@ var ts; var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(256 /* SyntaxKind.FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration); changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); + importAdder.writeFixes(changes); } function addJsxAttributes(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); @@ -154925,7 +157495,7 @@ var ts; var jsxAttributesNode = info.parentDeclaration.attributes; var hasSpreadAttribute = ts.some(jsxAttributesNode.properties, ts.isJsxSpreadAttribute); var attrs = ts.map(info.attributes, function (attr) { - var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr)); + var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr), info.parentDeclaration); var name = ts.factory.createIdentifier(attr.name); var jsxAttribute = ts.factory.createJsxAttribute(name, ts.factory.createJsxExpression(/*dotDotDotToken*/ undefined, value)); // formattingScanner requires the Identifier to have a context for scanning attributes with "-" (data-foo). @@ -154935,6 +157505,7 @@ var ts; var jsxAttributes = ts.factory.createJsxAttributes(hasSpreadAttribute ? __spreadArray(__spreadArray([], attrs, true), jsxAttributesNode.properties, true) : __spreadArray(__spreadArray([], jsxAttributesNode.properties, true), attrs, true)); var options = { prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : undefined }; changes.replaceNode(context.sourceFile, jsxAttributesNode, jsxAttributes, options); + importAdder.writeFixes(changes); } function addObjectLiteralProperties(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); @@ -154942,8 +157513,8 @@ var ts; var target = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var props = ts.map(info.properties, function (prop) { - var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop)); - return ts.factory.createPropertyAssignment(ts.createPropertyNameNodeForIdentifierOrLiteral(prop.name, target, quotePreference === 0 /* QuotePreference.Single */), initializer); + var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), info.parentDeclaration); + return ts.factory.createPropertyAssignment(createPropertyNameFromSymbol(prop, target, quotePreference, checker), initializer); }); var options = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, @@ -154951,8 +157522,9 @@ var ts; indentation: info.indentation }; changes.replaceNode(context.sourceFile, info.parentDeclaration, ts.factory.createObjectLiteralExpression(__spreadArray(__spreadArray([], info.parentDeclaration.properties, true), props, true), /*multiLine*/ true), options); + importAdder.writeFixes(changes); } - function tryGetValueFromType(context, checker, importAdder, quotePreference, type) { + function tryGetValueFromType(context, checker, importAdder, quotePreference, type, enclosingDeclaration) { if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { return createUndefined(); } @@ -154989,7 +157561,7 @@ var ts; return ts.factory.createNull(); } if (type.flags & 1048576 /* TypeFlags.Union */) { - var expression = ts.firstDefined(type.types, function (t) { return tryGetValueFromType(context, checker, importAdder, quotePreference, t); }); + var expression = ts.firstDefined(type.types, function (t) { return tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration); }); return expression !== null && expression !== void 0 ? expression : createUndefined(); } if (checker.isArrayLikeType(type)) { @@ -154997,7 +157569,7 @@ var ts; } if (isObjectLiteralType(type)) { var props = ts.map(checker.getPropertiesOfType(type), function (prop) { - var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration)) : createUndefined(); + var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration), enclosingDeclaration) : createUndefined(); return ts.factory.createPropertyAssignment(prop.name, initializer); }); return ts.factory.createObjectLiteralExpression(props, /*multiLine*/ true); @@ -155009,7 +157581,7 @@ var ts; var signature = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (signature === undefined) return createUndefined(); - var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ undefined, importAdder); + var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ enclosingDeclaration, importAdder); return func !== null && func !== void 0 ? func : createUndefined(); } if (ts.getObjectFlags(type) & 1 /* ObjectFlags.Class */) { @@ -155062,6 +157634,15 @@ var ts; var declaration = ts.findAncestor(callExpression, function (n) { return ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n); }); return declaration && declaration.parent === node ? declaration : undefined; } + function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) { + if (ts.isTransientSymbol(symbol) && symbol.nameType && symbol.nameType.flags & 8192 /* TypeFlags.UniqueESSymbol */) { + var expression = checker.symbolToExpression(symbol.nameType.symbol, 111551 /* SymbolFlags.Value */, symbol.valueDeclaration, 1048576 /* NodeBuilderFlags.AllowUniqueESSymbolType */); + if (expression) { + return ts.factory.createComputedPropertyName(expression); + } + } + return ts.createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* QuotePreference.Single */); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -155987,7 +158568,12 @@ var ts; if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) { if (parameter.modifiers && parameter.modifiers.length > 0 && (!ts.isIdentifier(parameter.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) { - parameter.modifiers.forEach(function (modifier) { return changes.deleteModifier(sourceFile, modifier); }); + for (var _i = 0, _a = parameter.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isModifier(modifier)) { + changes.deleteModifier(sourceFile, modifier); + } + } } else if (!parameter.initializer && isNotProvidedArguments(parameter, checker, sourceFiles)) { changes.delete(sourceFile, parameter); @@ -157402,7 +159988,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_16 = function (i) { + var _loop_14 = function (i) { var symbol = checker.createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg".concat(i))); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -157411,7 +159997,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_16(i); + _loop_14(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* SignatureFlags.None */); @@ -157601,8 +160187,7 @@ var ts; importSymbols(importAdder, importableReference.symbols); } } - addClassElement(ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, + addClassElement(ts.factory.createPropertyDeclaration(modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; case 172 /* SyntaxKind.GetAccessor */: @@ -157622,15 +160207,13 @@ var ts; for (var _i = 0, orderedAccessors_1 = orderedAccessors; _i < orderedAccessors_1.length; _i++) { var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { - addClassElement(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createGetAccessorDeclaration(modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; - addClassElement(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createSetAccessorDeclaration(modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } } break; @@ -157644,7 +160227,7 @@ var ts; // If there is more than one overload but no implementation signature // (eg: an abstract method or interface declaration), there is a 1-1 // correspondence of declarations and signatures. - var signatures = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); + var signatures = type.isUnion() ? ts.flatMap(type.types, function (t) { return t.getCallSignatures(); }) : type.getCallSignatures(); if (!ts.some(signatures)) { break; } @@ -157725,7 +160308,7 @@ var ts; type = importableReference.typeNode; importSymbols(importAdder, importableReference.symbols); } - return ts.factory.updateParameterDeclaration(parameterDecl, parameterDecl.decorators, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, parameterDecl.questionToken, type, parameterDecl.initializer); + return ts.factory.updateParameterDeclaration(parameterDecl, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, parameterDecl.questionToken, type, parameterDecl.initializer); }); if (parameters !== newParameters) { parameters = ts.setTextRange(ts.factory.createNodeArray(newParameters, parameters.hasTrailingComma), parameters); @@ -157747,7 +160330,7 @@ var ts; return ts.factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body !== null && body !== void 0 ? body : signatureDeclaration.body); } if (ts.isMethodDeclaration(signatureDeclaration)) { - return ts.factory.updateMethodDeclaration(signatureDeclaration, /* decorators */ undefined, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); + return ts.factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); } return undefined; } @@ -157763,40 +160346,50 @@ var ts; var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined; }); - var types = isJs ? [] : ts.map(args, function (arg) { - return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker); - }); + var instanceTypes = isJs ? [] : ts.map(args, function (arg) { return checker.getTypeAtLocation(arg); }); + var _a = getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, /*flags*/ undefined, tracker), argumentTypeNodes = _a.argumentTypeNodes, argumentTypeParameters = _a.argumentTypeParameters; var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var asteriskToken = ts.isYieldExpression(parent) ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined; - var typeParameters = isJs || typeArguments === undefined - ? undefined - : ts.map(typeArguments, function (_, i) { - return ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, 84 /* CharacterCodes.T */ + typeArguments.length - 1 <= 90 /* CharacterCodes.Z */ ? String.fromCharCode(84 /* CharacterCodes.T */ + i) : "T".concat(i)); - }); - var parameters = createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, isJs); + var typeParameters = isJs ? undefined : createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments); + var parameters = createDummyParameters(args.length, names, argumentTypeNodes, /*minArgumentCount*/ undefined, isJs); var type = isJs || contextualType === undefined ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); switch (kind) { case 169 /* SyntaxKind.MethodDeclaration */: - return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers, asteriskToken, name, + return ts.factory.createMethodDeclaration(modifiers, asteriskToken, name, /*questionToken*/ undefined, typeParameters, parameters, type, createStubbedMethodBody(quotePreference)); case 168 /* SyntaxKind.MethodSignature */: return ts.factory.createMethodSignature(modifiers, name, - /*questionToken*/ undefined, typeParameters, parameters, type); + /*questionToken*/ undefined, typeParameters, parameters, type === undefined ? ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */) : type); case 256 /* SyntaxKind.FunctionDeclaration */: - return ts.factory.createFunctionDeclaration( - /*decorators*/ undefined, modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); + return ts.factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); default: ts.Debug.fail("Unexpected kind"); } } codefix.createSignatureDeclarationFromCallExpression = createSignatureDeclarationFromCallExpression; + function createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments) { + var usedNames = new ts.Set(argumentTypeParameters.map(function (pair) { return pair[0]; })); + var constraintsByName = new ts.Map(argumentTypeParameters); + if (typeArguments) { + var typeArgumentsWithNewTypes = typeArguments.filter(function (typeArgument) { return !argumentTypeParameters.some(function (pair) { var _a; return checker.getTypeAtLocation(typeArgument) === ((_a = pair[1]) === null || _a === void 0 ? void 0 : _a.argumentType); }); }); + var targetSize = usedNames.size + typeArgumentsWithNewTypes.length; + for (var i = 0; usedNames.size < targetSize; i += 1) { + usedNames.add(createTypeParameterName(i)); + } + } + return ts.map(ts.arrayFrom(usedNames.values()), function (usedName) { var _a; return ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, usedName, (_a = constraintsByName.get(usedName)) === null || _a === void 0 ? void 0 : _a.constraint); }); + } + function createTypeParameterName(index) { + return 84 /* CharacterCodes.T */ + index <= 90 /* CharacterCodes.Z */ + ? String.fromCharCode(84 /* CharacterCodes.T */ + index) + : "T".concat(index); + } function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); if (typeNode && ts.isImportTypeNode(typeNode)) { @@ -157810,16 +160403,107 @@ var ts; return ts.getSynthesizedDeepClone(typeNode); } codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode; + function typeContainsTypeParameter(type) { + if (type.isUnionOrIntersection()) { + return type.types.some(typeContainsTypeParameter); + } + return type.flags & 262144 /* TypeFlags.TypeParameter */; + } + function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, tracker) { + // Types to be used as the types of the parameters in the new function + // E.g. from this source: + // added("", 0) + // The value will look like: + // [{ typeName: { text: "string" } }, { typeName: { text: "number" }] + // And in the output function will generate: + // function added(a: string, b: number) { ... } + var argumentTypeNodes = []; + // Names of type parameters provided as arguments to the call + // E.g. from this source: + // added(value); + // The value will look like: + // [ + // ["T", { argumentType: { typeName: { text: "T" } } } ], + // ["U", { argumentType: { typeName: { text: "U" } } } ], + // ] + // And in the output function will generate: + // function added() { ... } + var argumentTypeParameters = new ts.Map(); + for (var i = 0; i < instanceTypes.length; i += 1) { + var instanceType = instanceTypes[i]; + // If the instance type contains a deep reference to an existing type parameter, + // instead of copying the full union or intersection, create a new type parameter + // E.g. from this source: + // function existing(value: T | U & string) { + // added/*1*/(value); + // We don't want to output this: + // function added(value: T | U & string) { ... } + // We instead want to output: + // function added(value: T) { ... } + if (instanceType.isUnionOrIntersection() && instanceType.types.some(typeContainsTypeParameter)) { + var synthesizedTypeParameterName = createTypeParameterName(i); + argumentTypeNodes.push(ts.factory.createTypeReferenceNode(synthesizedTypeParameterName)); + argumentTypeParameters.set(synthesizedTypeParameterName, undefined); + continue; + } + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + var widenedInstanceType = checker.getBaseTypeOfLiteralType(instanceType); + var argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, tracker); + if (!argumentTypeNode) { + continue; + } + argumentTypeNodes.push(argumentTypeNode); + var argumentTypeParameter = getFirstTypeParameterName(instanceType); + // If the instance type is a type parameter with a constraint (other than an anonymous object), + // remember that constraint for when we create the new type parameter + // E.g. from this source: + // function existing(value: T) { + // added/*1*/(value); + // We don't want to output this: + // function added(value: T) { ... } + // We instead want to output: + // function added(value: T) { ... } + var instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) + ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, tracker) + : undefined; + if (argumentTypeParameter) { + argumentTypeParameters.set(argumentTypeParameter, { argumentType: instanceType, constraint: instanceTypeConstraint }); + } + } + return { argumentTypeNodes: argumentTypeNodes, argumentTypeParameters: ts.arrayFrom(argumentTypeParameters.entries()) }; + } + codefix.getArgumentTypesAndTypeParameters = getArgumentTypesAndTypeParameters; + function isAnonymousObjectConstraintType(type) { + return (type.flags & 524288 /* TypeFlags.Object */) && type.objectFlags === 16 /* ObjectFlags.Anonymous */; + } + function getFirstTypeParameterName(type) { + var _a; + if (type.flags & (1048576 /* TypeFlags.Union */ | 2097152 /* TypeFlags.Intersection */)) { + for (var _i = 0, _b = type.types; _i < _b.length; _i++) { + var subType = _b[_i]; + var subTypeName = getFirstTypeParameterName(subType); + if (subTypeName) { + return subTypeName; + } + } + } + return type.flags & 262144 /* TypeFlags.TypeParameter */ + ? (_a = type.getSymbol()) === null || _a === void 0 ? void 0 : _a.getName() + : undefined; + } function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; + var parameterNameCounts = new ts.Map(); for (var i = 0; i < argCount; i++) { + var parameterName = (names === null || names === void 0 ? void 0 : names[i]) || "arg".concat(i); + var parameterNameCount = parameterNameCounts.get(parameterName); + parameterNameCounts.set(parameterName, (parameterNameCount || 0) + 1); var newParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - /*name*/ names && names[i] || "arg".concat(i), + /*name*/ parameterName + (parameterNameCount || ""), /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, - /*type*/ inJs ? undefined : types && types[i] || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), + /*type*/ inJs ? undefined : (types === null || types === void 0 ? void 0 : types[i]) || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -157848,7 +160532,6 @@ var ts; var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var restParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, ts.factory.createArrayTypeNode(ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */)), /*initializer*/ undefined); @@ -157864,8 +160547,7 @@ var ts; } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { - return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers, + return ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } function createStubbedMethodBody(quotePreference) { @@ -157996,6 +160678,9 @@ var ts; accessorModifiers = ts.createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); fieldModifiers = ts.createModifiers(prepareModifierFlagsForField(modifierFlags)); } + if (ts.canHaveDecorators(declaration)) { + fieldModifiers = ts.concatenate(ts.getDecorators(declaration), fieldModifiers); + } } updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); @@ -158060,7 +160745,7 @@ var ts; error: ts.getLocaleSpecificMessage(ts.Diagnostics.Name_is_not_valid) }; } - if ((ts.getEffectiveModifierFlags(declaration) | meaning) !== meaning) { + if (((ts.getEffectiveModifierFlags(declaration) & 125951 /* ModifierFlags.Modifier */) | meaning) !== meaning) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_property_with_modifier) }; @@ -158083,17 +160768,14 @@ var ts; } codefix.getAccessorConvertiblePropertyAtPosition = getAccessorConvertiblePropertyAtPosition; function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { - return ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, accessorName, + return ts.factory.createGetAccessorDeclaration(modifiers, accessorName, /*parameters*/ undefined, // TODO: GH#18217 type, ts.factory.createBlock([ ts.factory.createReturnStatement(createAccessorAccessExpression(fieldName, isStatic, container)) ], /*multiLine*/ true)); } function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { - return ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, accessorName, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createSetAccessorDeclaration(modifiers, accessorName, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.factory.createIdentifier("value"), /*questionToken*/ undefined, type)], ts.factory.createBlock([ @@ -158101,7 +160783,7 @@ var ts; ], /*multiLine*/ true)); } function updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) { - var property = ts.factory.updatePropertyDeclaration(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); + var property = ts.factory.updatePropertyDeclaration(declaration, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); changeTracker.replaceNode(file, declaration, property); } function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { @@ -158116,7 +160798,7 @@ var ts; updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - changeTracker.replaceNode(file, declaration, ts.factory.updateParameterDeclaration(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + changeTracker.replaceNode(file, declaration, ts.factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } function insertAccessor(changeTracker, file, accessor, declaration, container) { @@ -158190,7 +160872,6 @@ var ts; if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, namespace.name, ts.factory.createExternalModuleReference(node.moduleSpecifier)))); } @@ -158327,7 +161008,7 @@ var ts; } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { ts.suppressLeadingAndTrailingTrivia(propertyDeclaration); - var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* SyntaxKind.ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* SyntaxKind.ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, info) { @@ -158357,7 +161038,7 @@ var ts; } function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { ts.suppressLeadingAndTrailingTrivia(propertyDeclaration); - var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { @@ -158423,8 +161104,8 @@ var ts; function doChange(changes, sourceFile, info) { var allowSyntheticDefaults = info.allowSyntheticDefaults, defaultImportName = info.defaultImportName, namedImports = info.namedImports, statement = info.statement, required = info.required; changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults - ? ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required)) - : ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); + ? ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required)) + : ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); } function getInfo(sourceFile, program, pos) { var parent = ts.getTokenAtPosition(sourceFile, pos).parent; @@ -158562,7 +161243,7 @@ var ts; return token.parent; } function doChange(changes, sourceFile, importType) { - var newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + var newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.assertions, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); changes.replaceNode(sourceFile, importType, newTypeNode); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -158679,7 +161360,7 @@ var ts; return { indexSignature: indexSignature, container: container }; } function createTypeAliasFromInterface(declaration, type) { - return ts.factory.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + return ts.factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); } function doChange(changes, sourceFile, _a) { var indexSignature = _a.indexSignature, container = _a.container; @@ -158795,9 +161476,8 @@ var ts; return; } var importClause = ts.Debug.checkDefined(importDeclaration.importClause); - changes.replaceNode(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); + changes.replaceNode(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); changes.insertNodeAfter(context.sourceFile, importDeclaration, ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ undefined, importClause.namedBindings), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -159019,14 +161699,14 @@ var ts; if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_export_statement) }; } - var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var checker = program.getTypeChecker(); + var exportingModuleSymbol = getExportingModuleSymbol(exportNode, checker); var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ModifierFlags.ExportDefault */ : 0 /* ModifierFlags.None */); var wasDefault = !!(flags & 512 /* ModifierFlags.Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* ModifierFlags.Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* InternalSymbolName.Default */)) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.This_file_already_has_a_default_export) }; } - var checker = program.getTypeChecker(); var noSymbolError = function (id) { return (ts.isIdentifier(id) && checker.getSymbolAtLocation(id)) ? undefined : { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_named_export) }; @@ -159078,7 +161758,7 @@ var ts; if (ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) { var exp = exportNode.expression; var spec = makeExportSpecifier(exp.text, exp.text); - changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); + changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); } else { changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 88 /* SyntaxKind.DefaultKeyword */), "Should find a default keyword in modifier list")); @@ -159118,6 +161798,8 @@ var ts; var checker = program.getTypeChecker(); var exportSymbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + if (exportName === ref) + return; var importingSourceFile = ref.getSourceFile(); if (wasDefault) { changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); @@ -159166,7 +161848,7 @@ var ts; } case 200 /* SyntaxKind.ImportType */: var importTypeNode = parent; - changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); + changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); break; default: ts.Debug.failBadSyntaxKind(parent); @@ -159210,6 +161892,17 @@ var ts; function makeExportSpecifier(propertyName, name) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, propertyName === name ? undefined : ts.factory.createIdentifier(propertyName), ts.factory.createIdentifier(name)); } + function getExportingModuleSymbol(node, checker) { + var parent = node.parent; + if (ts.isSourceFile(parent)) { + return parent.symbol; + } + var symbol = parent.parent.symbol; + if (symbol.valueDeclaration && ts.isExternalModuleAugmentation(symbol.valueDeclaration)) { + return checker.getMergedSymbol(symbol); + } + return symbol; + } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ @@ -159384,7 +162077,7 @@ var ts; // Imports that need to be kept as named imports in the refactored code, to avoid changing the semantics. // More specifically, those are named imports that appear in named exports in the original code, e.g. `a` in `import { a } from "m"; export { a }`. var neededNamedImports = new ts.Set(); - var _loop_17 = function (element) { + var _loop_15 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -159401,7 +162094,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_17(element); + _loop_15(element); } changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? ts.factory.createIdentifier(namespaceImportName) @@ -159422,7 +162115,7 @@ var ts; return externalModule !== exportEquals; } function updateImport(old, defaultImportName, elements) { - return ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); + return ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); @@ -159736,7 +162429,7 @@ var ts; break; } case 169 /* SyntaxKind.MethodDeclaration */: { - updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } case 174 /* SyntaxKind.CallSignature */: { @@ -159744,7 +162437,7 @@ var ts; break; } case 171 /* SyntaxKind.Constructor */: { - updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); + updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); break; } case 175 /* SyntaxKind.ConstructSignature */: { @@ -159752,7 +162445,7 @@ var ts; break; } case 256 /* SyntaxKind.FunctionDeclaration */: { - updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } default: return ts.Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); @@ -159772,7 +162465,6 @@ var ts; } return ts.factory.createNodeArray([ ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), "args", /*questionToken*/ undefined, ts.factory.createUnionTypeNode(ts.map(signatureDeclarations, convertSignatureParametersToTuple))) ]); @@ -159819,6 +162511,9 @@ var ts; if (!containingDecl) { return; } + if (ts.isFunctionLikeDeclaration(containingDecl) && containingDecl.body && ts.rangeContainsPosition(containingDecl.body, startPosition)) { + return; + } var checker = program.getTypeChecker(); var signatureSymbol = containingDecl.symbol; if (!signatureSymbol) { @@ -159839,7 +162534,7 @@ var ts; return; } var signatureDecls = decls; - if (ts.some(signatureDecls, function (d) { return !!d.typeParameters || ts.some(d.parameters, function (p) { return !!p.decorators || !!p.modifiers || !ts.isIdentifier(p.name); }); })) { + if (ts.some(signatureDecls, function (d) { return !!d.typeParameters || ts.some(d.parameters, function (p) { return !!p.modifiers || !ts.isIdentifier(p.name); }); })) { return; } var signatures = ts.mapDefined(signatureDecls, function (d) { return checker.getSignatureFromDeclaration(d); }); @@ -160169,11 +162864,11 @@ var ts; } } else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { - var declarations_5 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; + var declarations_6 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, declarations_4 = declarations_5; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + for (var _i = 0, declarations_5 = declarations_6; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; if (declaration.initializer) { numInitializers++; lastInitializer = declaration.initializer; @@ -160332,7 +163027,7 @@ var ts; var savedPermittedJumps = permittedJumps; switch (node.kind) { case 239 /* SyntaxKind.IfStatement */: - permittedJumps = 0 /* PermittedJumps.None */; + permittedJumps &= ~4 /* PermittedJumps.Return */; break; case 252 /* SyntaxKind.TryStatement */: // forbid all jumps inside try blocks @@ -160624,7 +163319,6 @@ var ts; typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NodeBuilderFlags.NoTruncation */); } var paramDecl = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ name, @@ -160664,22 +163358,19 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { modifiers.push(ts.factory.createModifier(131 /* SyntaxKind.AsyncKeyword */)); } - newFunction = ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, + newFunction = ts.factory.createMethodDeclaration(modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { if (callThis) { parameters.unshift(ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ "this", /*questionToken*/ undefined, checker.typeToTypeNode(checker.getTypeAtLocation(range.thisNode), scope, 1 /* NodeBuilderFlags.NoTruncation */), /*initializer*/ undefined)); } - newFunction = ts.factory.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + newFunction = ts.factory.createFunctionDeclaration(range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; @@ -160861,8 +163552,7 @@ var ts; modifiers.push(ts.factory.createModifier(124 /* SyntaxKind.StaticKeyword */)); } modifiers.push(ts.factory.createModifier(145 /* SyntaxKind.ReadonlyKeyword */)); - var newVariable = ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, localNameText, + var newVariable = ts.factory.createPropertyDeclaration(modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.factory.createPropertyAccessExpression(rangeFacts & RangeFacts.InStaticRegion ? ts.factory.createIdentifier(scope.name.getText()) // TODO: GH#18217 @@ -160957,7 +163647,7 @@ var ts; var paramType = checker.getTypeAtLocation(p); if (paramType === checker.getAnyType()) hasAny = true; - parameters.push(ts.factory.updateParameterDeclaration(p, p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NodeBuilderFlags.NoTruncation */), p.initializer)); + parameters.push(ts.factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NodeBuilderFlags.NoTruncation */), p.initializer)); } } // If a parameter was inferred as any we skip adding function parameters at all. @@ -160967,7 +163657,7 @@ var ts; return { variableType: variableType, initializer: initializer }; variableType = undefined; if (ts.isArrowFunction(initializer)) { - initializer = ts.factory.updateArrowFunction(initializer, node.modifiers, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.equalsGreaterThanToken, initializer.body); + initializer = ts.factory.updateArrowFunction(initializer, ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.equalsGreaterThanToken, initializer.body); } else { if (functionSignature && !!functionSignature.thisParameter) { @@ -160977,13 +163667,12 @@ var ts; if ((!firstParameter || (ts.isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this"))) { var thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); parameters.splice(0, 0, ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, checker.typeToTypeNode(thisType, scope, 1 /* NodeBuilderFlags.NoTruncation */))); } } - initializer = ts.factory.updateFunctionExpression(initializer, node.modifiers, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.body); + initializer = ts.factory.updateFunctionExpression(initializer, ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.body); } return { variableType: variableType, initializer: initializer }; } @@ -161299,7 +163988,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_18 = function (i) { + var _loop_16 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -161342,7 +164031,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_18(i); + _loop_16(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -161778,7 +164467,6 @@ var ts; function doTypeAliasChange(changes, file, name, info) { var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters; var newTypeNode = ts.factory.createTypeAliasDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters.map(function (id) { return ts.factory.updateTypeParameterDeclaration(id, id.modifiers, id.name, id.constraint, /* defaultType */ undefined); }), selection); changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true); changes.replaceNode(file, selection, ts.factory.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.factory.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.ExcludeWhitespace }); @@ -161787,7 +164475,6 @@ var ts; var _a; var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters, typeElements = info.typeElements; var newTypeNode = ts.factory.createInterfaceDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters, /* heritageClauses */ undefined, typeElements); ts.setTextRange(newTypeNode, (_a = typeElements[0]) === null || _a === void 0 ? void 0 : _a.parent); @@ -161951,7 +164638,7 @@ var ts; var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); var extension = ts.extensionFromPath(oldFile.fileName); - var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.oldFileImportsFromNewFile, usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); @@ -162045,10 +164732,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_19 = function (sourceFile) { + var _loop_17 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_20 = function (statement) { + var _loop_18 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -162070,12 +164757,12 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_20(statement); + _loop_18(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_19(sourceFile); + _loop_17(sourceFile); } } function getNamespaceLikeImport(node) { @@ -162118,10 +164805,10 @@ var ts; switch (node.kind) { case 266 /* SyntaxKind.ImportDeclaration */: return ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, + /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, /*assertClause*/ undefined); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); + return ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); case 254 /* SyntaxKind.VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: @@ -162315,8 +165002,8 @@ var ts; newModuleName = "".concat(moduleName, ".").concat(i); } } - function getNewModuleName(movedSymbols) { - return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + function getNewModuleName(importsFromNewFile, movedSymbols) { + return importsFromNewFile.forEachEntry(ts.symbolNameNoDefault) || movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; } function getUsageInfo(oldFile, toMove, checker) { var movedSymbols = new SymbolSet(); @@ -162409,7 +165096,7 @@ var ts; var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); return defaultImport || namedBindings - ? ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) + ? ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) : undefined; } case 265 /* SyntaxKind.ImportEqualsDeclaration */: @@ -162574,24 +165261,25 @@ var ts; return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); } function addEs6Export(d) { - var modifiers = ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], d.modifiers); + var modifiers = ts.canHaveModifiers(d) ? ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], ts.getModifiers(d)) : undefined; switch (d.kind) { case 256 /* SyntaxKind.FunctionDeclaration */: - return ts.factory.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + return ts.factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); case 257 /* SyntaxKind.ClassDeclaration */: - return ts.factory.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + var decorators = ts.canHaveDecorators(d) ? ts.getDecorators(d) : undefined; + return ts.factory.updateClassDeclaration(d, ts.concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); case 237 /* SyntaxKind.VariableStatement */: return ts.factory.updateVariableStatement(d, modifiers, d.declarationList); case 261 /* SyntaxKind.ModuleDeclaration */: - return ts.factory.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + return ts.factory.updateModuleDeclaration(d, modifiers, d.name, d.body); case 260 /* SyntaxKind.EnumDeclaration */: - return ts.factory.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + return ts.factory.updateEnumDeclaration(d, modifiers, d.name, d.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return ts.factory.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + return ts.factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); case 258 /* SyntaxKind.InterfaceDeclaration */: - return ts.factory.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + return ts.factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.isTypeOnly, d.name, d.moduleReference); + return ts.factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); case 238 /* SyntaxKind.ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: @@ -163088,7 +165776,7 @@ var ts; if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false; } - return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name); + return !parameterDeclaration.modifiers && ts.isIdentifier(parameterDeclaration.name); } function isValidVariableDeclaration(node) { return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113 @@ -163147,14 +165835,12 @@ var ts; objectInitializer = ts.factory.createObjectLiteralExpression(); } var objectParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, objectParameterName, /*questionToken*/ undefined, objectParameterType, objectInitializer); if (hasThisParameter(functionDeclaration.parameters)) { var thisParameter = functionDeclaration.parameters[0]; var newThisParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, thisParameter.type); @@ -163439,7 +166125,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText, rawHeadText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_21 = function (i) { + var _loop_19 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], rawSubsequentText = _c[2], stringIndexes = _c[3]; @@ -163468,7 +166154,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_21(i); + _loop_19(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -163675,7 +166361,7 @@ var ts; ts.suppressLeadingTrivia(statement); var modifiersFlags = (ts.getCombinedModifierFlags(variableDeclaration) & 1 /* ModifierFlags.Export */) | ts.getEffectiveModifierFlags(func); var modifiers = ts.factory.createModifiersFromModifierFlags(modifiersFlags); - var newNode = ts.factory.createFunctionDeclaration(func.decorators, ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + var newNode = ts.factory.createFunctionDeclaration(ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, statement, newNode); }); } @@ -164080,20 +166766,25 @@ var ts; return this.documentationComment; }; SymbolObject.prototype.getContextualDocumentationComment = function (context, checker) { - switch (context === null || context === void 0 ? void 0 : context.kind) { - case 172 /* SyntaxKind.GetAccessor */: + if (context) { + if (ts.isGetAccessor(context)) { if (!this.contextualGetAccessorDocumentationComment) { this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } - return this.contextualGetAccessorDocumentationComment; - case 173 /* SyntaxKind.SetAccessor */: + if (ts.length(this.contextualGetAccessorDocumentationComment)) { + return this.contextualGetAccessorDocumentationComment; + } + } + if (ts.isSetAccessor(context)) { if (!this.contextualSetAccessorDocumentationComment) { this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); } - return this.contextualSetAccessorDocumentationComment; - default: - return this.getDocumentationComment(checker); + if (ts.length(this.contextualSetAccessorDocumentationComment)) { + return this.contextualSetAccessorDocumentationComment; + } + } } + return this.getDocumentationComment(checker); }; SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { @@ -164102,20 +166793,25 @@ var ts; return this.tags; }; SymbolObject.prototype.getContextualJsDocTags = function (context, checker) { - switch (context === null || context === void 0 ? void 0 : context.kind) { - case 172 /* SyntaxKind.GetAccessor */: + if (context) { + if (ts.isGetAccessor(context)) { if (!this.contextualGetAccessorTags) { this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isGetAccessor), checker); } - return this.contextualGetAccessorTags; - case 173 /* SyntaxKind.SetAccessor */: + if (ts.length(this.contextualGetAccessorTags)) { + return this.contextualGetAccessorTags; + } + } + if (ts.isSetAccessor(context)) { if (!this.contextualSetAccessorTags) { this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isSetAccessor), checker); } - return this.contextualSetAccessorTags; - default: - return this.getJsDocTags(checker); + if (ts.length(this.contextualSetAccessorTags)) { + return this.contextualSetAccessorTags; + } + } } + return this.getJsDocTags(checker); }; return SymbolObject; }()); @@ -164296,7 +166992,7 @@ var ts; * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. */ function hasJSDocInheritDocTag(node) { - return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc"; }); } function getJsDocTagsOfDeclarations(declarations, checker) { if (!declarations) @@ -164304,7 +167000,7 @@ var ts; var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations, checker); if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) { var seenSymbols_1 = new ts.Set(); - var _loop_22 = function (declaration) { + var _loop_20 = function (declaration) { var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; if (!seenSymbols_1.has(symbol)) { @@ -164319,9 +167015,9 @@ var ts; tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); } }; - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - _loop_22(declaration); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + _loop_20(declaration); } } return tags; @@ -164332,7 +167028,7 @@ var ts; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { var seenSymbols_2 = new ts.Set(); - var _loop_23 = function (declaration) { + var _loop_21 = function (declaration) { var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { if (!seenSymbols_2.has(symbol)) { seenSymbols_2.add(symbol); @@ -164346,22 +167042,23 @@ var ts; if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); }; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - _loop_23(declaration); + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + _loop_21(declaration); } } return doc; } function findBaseOfDeclaration(checker, declaration, cb) { var _a; - if (ts.hasStaticModifier(declaration)) - return; var classOrInterfaceDeclaration = ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.kind) === 171 /* SyntaxKind.Constructor */ ? declaration.parent.parent : declaration.parent; if (!classOrInterfaceDeclaration) return; + var isStaticMember = ts.hasStaticModifier(declaration); return ts.firstDefined(ts.getAllSuperTypeNodes(classOrInterfaceDeclaration), function (superTypeNode) { - var symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name); + var baseType = checker.getTypeAtLocation(superTypeNode); + var type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType; + var symbol = checker.getPropertyOfType(type, declaration.symbol.name); return symbol ? cb(symbol) : undefined; }); } @@ -164604,70 +167301,6 @@ var ts; return ts.codefix.getSupportedErrorCodes(); } ts.getSupportedCodeFixes = getSupportedCodeFixes; - // Cache host information about script Should be refreshed - // at each language service public entry point, since we don't know when - // the set of scripts handled by the host changes. - var HostCache = /** @class */ (function () { - function HostCache(host, getCanonicalFileName) { - this.host = host; - // script id => script index - this.currentDirectory = host.getCurrentDirectory(); - this.fileNameToEntry = new ts.Map(); - // Initialize the list with the root file names - var rootFileNames = host.getScriptFileNames(); - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* tracing.Phase.Session */, "initializeHostCache", { count: rootFileNames.length }); - for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { - var fileName = rootFileNames_1[_i]; - this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); - } - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); - } - HostCache.prototype.createEntry = function (fileName, path) { - var entry; - var scriptSnapshot = this.host.getScriptSnapshot(fileName); - if (scriptSnapshot) { - entry = { - hostFileName: fileName, - version: this.host.getScriptVersion(fileName), - scriptSnapshot: scriptSnapshot, - scriptKind: ts.getScriptKind(fileName, this.host) - }; - } - else { - entry = fileName; - } - this.fileNameToEntry.set(path, entry); - return entry; - }; - HostCache.prototype.getEntryByPath = function (path) { - return this.fileNameToEntry.get(path); - }; - HostCache.prototype.getHostFileInformation = function (path) { - var entry = this.fileNameToEntry.get(path); - return !ts.isString(entry) ? entry : undefined; - }; - HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - var info = this.getEntryByPath(path) || this.createEntry(fileName, path); - return ts.isString(info) ? undefined : info; // TODO: GH#18217 - }; - HostCache.prototype.getRootFileNames = function () { - var names = []; - this.fileNameToEntry.forEach(function (entry) { - if (ts.isString(entry)) { - names.push(entry); - } - else { - names.push(entry.hostFileName); - } - }); - return names; - }; - HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getHostFileInformation(path); - return (file && file.scriptSnapshot); // TODO: GH#18217 - }; - return HostCache; - }()); var SyntaxTreeCache = /** @class */ (function () { function SyntaxTreeCache(host) { this.host = host; @@ -164929,32 +167562,16 @@ var ts; program = undefined; // TODO: GH#18217 lastTypesRootVersion = typeRootsVersion; } + // This array is retained by the program and will be used to determine if the program is up to date, + // so we need to make a copy in case the host mutates the underlying array - otherwise it would look + // like every program always has the host's current list of root files. + var rootFileNames = host.getScriptFileNames().slice(); // Get a fresh cache of the host information - var hostCache = new HostCache(host, getCanonicalFileName); - var rootFileNames = hostCache.getRootFileNames(); var newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; var hasChangedAutomaticTypeDirectiveNames = ts.maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); var projectReferences = (_b = host.getProjectReferences) === null || _b === void 0 ? void 0 : _b.call(host); var parsedCommandLines; - var parseConfigHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - fileExists: fileExists, - readFile: readFile, - readDirectory: readDirectory, - trace: ts.maybeBind(host, host.trace), - getCurrentDirectory: function () { return currentDirectory; }, - onUnRecoverableConfigFileDiagnostic: ts.noop, - }; - // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { - return; - } - // IMPORTANT - It is critical from this moment onward that we do not check - // cancellation tokens. We are about to mutate source files from a previous program - // instance. If we cancel midway through, we may end up in an inconsistent state where - // the program points to old source files that have been invalidated because of - // incremental parsing. // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -164966,8 +167583,8 @@ var ts; getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, - fileExists: fileExists, - readFile: readFile, + fileExists: function (fileName) { return host.fileExists(fileName); }, + readFile: function (fileName) { return host.readFile && host.readFile(fileName); }, getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache), realpath: ts.maybeBind(host, host.realpath), directoryExists: function (directoryName) { @@ -164976,19 +167593,56 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, - readDirectory: readDirectory, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, onReleaseParsedCommandLine: onReleaseParsedCommandLine, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, - trace: parseConfigHost.trace, + trace: ts.maybeBind(host, host.trace), resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), getModuleResolutionCache: ts.maybeBind(host, host.getModuleResolutionCache), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine: getParsedCommandLine, }; + var originalGetSourceFile = compilerHost.getSourceFile; + var getSourceFileWithCache = ts.changeCompilerHostLikeToUseCache(compilerHost, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args, false)); + }).getSourceFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; (_c = host.setCompilerHost) === null || _c === void 0 ? void 0 : _c.call(host, compilerHost); + var parseConfigHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, + readFile: function (fileName) { return compilerHost.readFile(fileName); }, + readDirectory: function () { + var _a; + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return (_a = compilerHost).readDirectory.apply(_a, args); + }, + trace: compilerHost.trace, + getCurrentDirectory: compilerHost.getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: ts.noop, + }; + // If the program is already up-to-date, we can reuse it + if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, function (fileName) { return compilerHost.fileExists(fileName); }, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + return; + } + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, @@ -164998,9 +167652,9 @@ var ts; projectReferences: projectReferences }; program = ts.createProgram(options); - // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. - // It needs to be cleared to allow all collected snapshots to be released - hostCache = undefined; + // 'getOrCreateSourceFile' depends on caching but should be used past this point. + // After this point, the cache needs to be cleared to allow all collected snapshots to be released + compilerHost = undefined; parsedCommandLines = undefined; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during @@ -165040,44 +167694,26 @@ var ts; onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); } } - function fileExists(fileName) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - return entry ? - !ts.isString(entry) : - (!!host.fileExists && host.fileExists(fileName)); - } - function readFile(fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - if (entry) { - return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); - } - return host.readFile && host.readFile(fileName); - } - function readDirectory(path, extensions, exclude, include, depth) { - ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(path, extensions, exclude, include, depth); - } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } - function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { - return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); + function getOrCreateSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersionOrOptions, onError, shouldCreateNewSourceFile); } - function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { - ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); + function getOrCreateSourceFileByPath(fileName, path, languageVersionOrOptions, _onError, shouldCreateNewSourceFile) { + ts.Debug.assert(compilerHost, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. - var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); - if (!hostFileInformation) { + var scriptSnapshot = host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { return undefined; } + var scriptKind = ts.getScriptKind(fileName, host); + var scriptVersion = host.getScriptVersion(fileName); // Check if the language version has changed since we last created a program; if they are the same, // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. @@ -165109,18 +167745,18 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { - return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } else { // Release old source file and fall through to aquire new file with new script kind - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } } // We didn't already have the file. Fall through and acquire it from the registry. } // Could not find this file in the old program, create a new SourceFile for it. - return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } } // TODO: GH#18217 frequently asserted as defined @@ -165136,6 +167772,61 @@ var ts; var _a; return (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); } + function updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans) { + var checker = program.getTypeChecker(); + var symbol = getSymbolForProgram(); + if (!symbol) + return false; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + var refNode = getNodeForSpan(ref); + ts.Debug.assertIsDefined(refNode); + if (knownSymbolSpans.has(ref) || ts.FindAllReferences.isDeclarationOfSymbol(refNode, symbol)) { + knownSymbolSpans.add(ref); + ref.isDefinition = true; + var mappedSpan = ts.getMappedDocumentSpan(ref, sourceMapper, ts.maybeBind(host, host.fileExists)); + if (mappedSpan) { + knownSymbolSpans.add(mappedSpan); + } + } + else { + ref.isDefinition = false; + } + } + } + return true; + function getSymbolForProgram() { + for (var _i = 0, referencedSymbols_2 = referencedSymbols; _i < referencedSymbols_2.length; _i++) { + var referencedSymbol = referencedSymbols_2[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + if (knownSymbolSpans.has(ref)) { + var refNode = getNodeForSpan(ref); + ts.Debug.assertIsDefined(refNode); + return checker.getSymbolAtLocation(refNode); + } + var mappedSpan = ts.getMappedDocumentSpan(ref, sourceMapper, ts.maybeBind(host, host.fileExists)); + if (mappedSpan && knownSymbolSpans.has(mappedSpan)) { + var refNode = getNodeForSpan(mappedSpan); + if (refNode) { + return checker.getSymbolAtLocation(refNode); + } + } + } + } + return undefined; + } + function getNodeForSpan(docSpan) { + var sourceFile = program.getSourceFile(docSpan.fileName); + if (!sourceFile) + return undefined; + var rawNode = ts.getTouchingPropertyName(sourceFile, docSpan.textSpan.start); + var adjustedNode = ts.FindAllReferences.Core.getAdjustedNode(rawNode, { use: 1 /* FindAllReferences.FindReferencesUse.References */ }); + return adjustedNode; + } + } function cleanupSemanticCache() { program = undefined; // TODO: GH#18217 } @@ -165144,7 +167835,7 @@ var ts; // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); ts.forEach(program.getSourceFiles(), function (f) { - return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind, f.impliedNodeFormat); }); program = undefined; // TODO: GH#18217 } @@ -165932,9 +168623,9 @@ var ts; return ts.stringContains(path, "/node_modules/"); } } - function getRenameInfo(fileName, position, options) { + function getRenameInfo(fileName, position, preferences) { synchronizeHostData(); - return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, preferences || {}); } function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason, kind) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; @@ -166061,7 +168752,9 @@ var ts; getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getProgram: getProgram, + getCurrentProgram: function () { return program; }, getAutoImportProvider: getAutoImportProvider, + updateIsDefinitionOfReferencedSymbols: updateIsDefinitionOfReferencedSymbols, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, toLineColumnOffset: toLineColumnOffset, @@ -166213,7 +168906,7 @@ var ts; function getDefaultLibFilePath(options) { // Check __dirname is defined and that we are on a node.js system. if (typeof __dirname !== "undefined") { - return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); + return ts.combinePaths(__dirname, ts.getDefaultLibFileName(options)); } throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); } @@ -166255,8 +168948,9 @@ var ts; // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - var start = startNode.decorators ? - ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + var lastDecorator = ts.canHaveDecorators(startNode) ? ts.findLast(startNode.modifiers, ts.isDecorator) : undefined; + var start = lastDecorator ? + ts.skipTrivia(sourceFile.text, lastDecorator.end) : startNode.getStart(sourceFile); return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } @@ -166269,8 +168963,20 @@ var ts; } return spanInNode(otherwiseOnNode); } - function spanInNodeArray(nodeArray) { - return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + function spanInNodeArray(nodeArray, node, match) { + if (nodeArray) { + var index = nodeArray.indexOf(node); + if (index >= 0) { + var start = index; + var end = index + 1; + while (start > 0 && match(nodeArray[start - 1])) + start--; + while (end < nodeArray.length && match(nodeArray[end])) + end++; + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray[start].pos), nodeArray[end - 1].end); + } + } + return textSpan(node); } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); @@ -166383,7 +169089,7 @@ var ts; // span in statement return spanInNode(node.statement); case 165 /* SyntaxKind.Decorator */: - return spanInNodeArray(parent.decorators); + return spanInNodeArray(parent.modifiers, node, ts.isDecorator); case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: return spanInBindingPattern(node); @@ -166546,7 +169252,7 @@ var ts; } // Breakpoint is possible in variableDeclaration only if there is initialization // or its declaration from 'for of' - if (variableDeclaration.initializer || + if ((ts.hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer) || ts.hasSyntacticModifier(variableDeclaration, 1 /* ModifierFlags.Export */) || parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); @@ -167286,9 +169992,9 @@ var ts; var _this = this; return this.forwardJSONCall("getImplementationAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, options); }); + return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, preferences); }); }; LanguageServiceShimObject.prototype.getSmartSelectionRange = function (fileName, position) { var _this = this; @@ -167513,7 +170219,8 @@ var ts; } return { resolvedFileName: resolvedFileName, - failedLookupLocations: result.failedLookupLocations + failedLookupLocations: result.failedLookupLocations, + affectingLocations: result.affectingLocations, }; }); }; @@ -167592,7 +170299,7 @@ var ts; if (_this.safeList === undefined) { _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); } - return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry); + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry, ts.emptyOptions); }); }; return CoreServicesShimObject; @@ -167714,23 +170421,80 @@ if (typeof process === "undefined" || process.browser) { if (typeof module !== "undefined" && module.exports) { module.exports = ts; } +// The following are deprecations for the public API. Deprecated exports are removed from the compiler itself +// and compatible implementations are added here, along with an appropriate deprecation warning using +// the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. +// +// Deprecations fall into one of three categories: +// +// - "soft" - Soft deprecations are indicated with the `@deprecated` JSDoc Tag. +// - "warn" - Warning deprecations are indicated with the `@deprecated` JSDoc Tag and a diagnostic message (assuming a compatible host). +// - "error" - Error deprecations are either indicated with the `@deprecated` JSDoc tag and will throw a `TypeError` when invoked, or removed from the API entirely. +// +// Once we have determined enough time has passed after a deprecation has been marked as `"warn"` or `"error"`, it will be removed from the public API. +/* @internal */ +var ts; +(function (ts) { + function createOverload(name, overloads, binder, deprecations) { + Object.defineProperty(call, "name", __assign(__assign({}, Object.getOwnPropertyDescriptor(call, "name")), { value: name })); + if (deprecations) { + for (var _i = 0, _a = Object.keys(deprecations); _i < _a.length; _i++) { + var key = _a[_i]; + var index = +key; + if (!isNaN(index) && ts.hasProperty(overloads, "".concat(index))) { + overloads[index] = ts.Debug.deprecate(overloads[index], __assign(__assign({}, deprecations[index]), { name: name })); + } + } + } + var bind = createBinder(overloads, binder); + return call; + function call() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var index = bind(args); + var fn = index !== undefined ? overloads[index] : undefined; + if (typeof fn === "function") { + return fn.apply(void 0, args); + } + throw new TypeError("Invalid arguments"); + } + } + ts.createOverload = createOverload; + function createBinder(overloads, binder) { + return function (args) { + for (var i = 0; ts.hasProperty(overloads, "".concat(i)) && ts.hasProperty(binder, "".concat(i)); i++) { + var fn = binder[i]; + if (fn(args)) { + return i; + } + } + }; + } + // NOTE: We only use this "builder" because we don't infer correctly when calling `createOverload` directly in < TS 4.7, + // but lib is currently at TS 4.4. We can switch to directly calling `createOverload` when we update LKG in main. + function buildOverload(name) { + return { + overload: function (overloads) { return ({ + bind: function (binder) { return ({ + finish: function () { return createOverload(name, overloads, binder); }, + deprecate: function (deprecations) { return ({ + finish: function () { return createOverload(name, overloads, binder, deprecations); } + }); } + }); } + }); } + }; + } + ts.buildOverload = buildOverload; +})(ts || (ts = {})); +// DEPRECATION: Node factory top-level exports +// DEPRECATION PLAN: +// - soft: 4.0 +// - warn: 4.1 +// - error: 5.0 var ts; (function (ts) { - // The following are deprecations for the public API. Deprecated exports are removed from the compiler itself - // and compatible implementations are added here, along with an appropriate deprecation warning using - // the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. - // - // Deprecations fall into one of three categories: - // - // * "soft" - Soft deprecations are indicated with the `@deprecated` JSDoc Tag. - // * "warn" - Warning deprecations are indicated with the `@deprecated` JSDoc Tag and a diagnostic message (assuming a compatible host) - // * "error" - Error deprecations are indicated with the `@deprecated` JSDoc tag and will throw a `TypeError` when invoked. - // DEPRECATION: Node factory top-level exports - // DEPRECATION PLAN: - // - soft: 4.0 - // - warn: 4.1 - // - error: TBD - // #region Node factory top-level exports // NOTE: These exports are deprecated in favor of using a `NodeFactory` instance and exist here purely for backwards compatibility reasons. var factoryDeprecation = { since: "4.0", warnAfter: "4.1", message: "Use the appropriate method on 'ts.factory' or the 'factory' supplied by your transformation context instead." }; /** @deprecated Use `factory.createNodeArray` or the factory supplied by your transformation context instead. */ @@ -168600,13 +171364,14 @@ var ts; ts.setParent(clone, node.parent); return clone; }, { since: "4.0", warnAfter: "4.1", message: "Use an appropriate `factory.update...` method instead, use `setCommentRange` or `setSourceMapRange`, and avoid setting `parent`." }); - // #endregion Node Factory top-level exports - // DEPRECATION: Renamed node tests - // DEPRECATION PLAN: - // - soft: 4.0 - // - warn: 4.1 - // - error: TBD - // #region Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Renamed node tests +// DEPRECATION PLAN: +// - soft: 4.0 +// - warn: 4.1 +// - error: TBD +var ts; +(function (ts) { /** @deprecated Use `isTypeAssertionExpression` instead. */ ts.isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node) { return node.kind === 211 /* SyntaxKind.TypeAssertionExpression */; @@ -168615,13 +171380,14 @@ var ts; warnAfter: "4.1", message: "Use `isTypeAssertionExpression` instead." }); - // #endregion - // DEPRECATION: Renamed node tests - // DEPRECATION PLAN: - // - soft: 4.2 - // - warn: 4.3 - // - error: TBD - // #region Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Renamed node tests +// DEPRECATION PLAN: +// - soft: 4.2 +// - warn: 4.3 +// - error: 5.0 +var ts; +(function (ts) { /** * @deprecated Use `isMemberName` instead. */ @@ -168632,7 +171398,1422 @@ var ts; warnAfter: "4.3", message: "Use `isMemberName` instead." }); - // #endregion Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Overloads for createConstructorTypeNode/updateConstructorTypeNode that do not accept 'modifiers' +// DEPRECATION PLAN: +// - soft: 4.2 +// - warn: 4.3 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createConstructorTypeNode = factory.createConstructorTypeNode, updateConstructorTypeNode = factory.updateConstructorTypeNode; + factory.createConstructorTypeNode = ts.buildOverload("createConstructorTypeNode") + .overload({ + 0: function (modifiers, typeParameters, parameters, type) { + return createConstructorTypeNode(modifiers, typeParameters, parameters, type); + }, + 1: function (typeParameters, parameters, type) { + return createConstructorTypeNode(/*modifiers*/ undefined, typeParameters, parameters, type); + }, + }) + .bind({ + 0: function (args) { return args.length === 4; }, + 1: function (args) { return args.length === 3; }, + }) + .deprecate({ + 1: { since: "4.2", warnAfter: "4.3", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + factory.updateConstructorTypeNode = ts.buildOverload("updateConstructorTypeNode") + .overload({ + 0: function (node, modifiers, typeParameters, parameters, type) { + return updateConstructorTypeNode(node, modifiers, typeParameters, parameters, type); + }, + 1: function (node, typeParameters, parameters, type) { + return updateConstructorTypeNode(node, node.modifiers, typeParameters, parameters, type); + } + }) + .bind({ + 0: function (args) { return args.length === 5; }, + 1: function (args) { return args.length === 4; }, + }) + .deprecate({ + 1: { since: "4.2", warnAfter: "4.3", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Overloads to createImportTypeNode/updateImportTypeNode that do not accept `assertions` +// DEPRECATION PLAN: +// - soft: 4.6 +// - warn: 4.7 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createImportTypeNode = factory.createImportTypeNode, updateImportTypeNode = factory.updateImportTypeNode; + factory.createImportTypeNode = ts.buildOverload("createImportTypeNode") + .overload({ + 0: function (argument, assertions, qualifier, typeArguments, isTypeOf) { + return createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf); + }, + 1: function (argument, qualifier, typeArguments, isTypeOf) { + return createImportTypeNode(argument, /*assertions*/ undefined, qualifier, typeArguments, isTypeOf); + }, + }) + .bind({ + 0: function (_a) { + var assertions = _a[1], qualifier = _a[2], typeArguments = _a[3], isTypeOf = _a[4]; + return (assertions === undefined || ts.isImportTypeAssertionContainer(assertions)) && + (qualifier === undefined || !ts.isArray(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + 1: function (_a) { + var qualifier = _a[1], typeArguments = _a[2], isTypeOf = _a[3], other = _a[4]; + return (other === undefined) && + (qualifier === undefined || ts.isEntityName(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + }) + .deprecate({ + 1: { since: "4.6", warnAfter: "4.7", message: "Use the overload that accepts 'assertions'" } + }) + .finish(); + factory.updateImportTypeNode = ts.buildOverload("updateImportTypeNode") + .overload({ + 0: function (node, argument, assertions, qualifier, typeArguments, isTypeOf) { + return updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf); + }, + 1: function (node, argument, qualifier, typeArguments, isTypeOf) { + return updateImportTypeNode(node, argument, node.assertions, qualifier, typeArguments, isTypeOf); + }, + }) + .bind({ + 0: function (_a) { + var assertions = _a[2], qualifier = _a[3], typeArguments = _a[4], isTypeOf = _a[5]; + return (assertions === undefined || ts.isImportTypeAssertionContainer(assertions)) && + (qualifier === undefined || !ts.isArray(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + 1: function (_a) { + var qualifier = _a[2], typeArguments = _a[3], isTypeOf = _a[4], other = _a[5]; + return (other === undefined) && + (qualifier === undefined || ts.isEntityName(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + }). + deprecate({ + 1: { since: "4.6", warnAfter: "4.7", message: "Use the overload that accepts 'assertions'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Overloads to createTypeParameter/updateTypeParameter that does not accept `modifiers` +// DEPRECATION PLAN: +// - soft: 4.7 +// - warn: 4.8 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createTypeParameterDeclaration = factory.createTypeParameterDeclaration, updateTypeParameterDeclaration = factory.updateTypeParameterDeclaration; + factory.createTypeParameterDeclaration = ts.buildOverload("createTypeParameterDeclaration") + .overload({ + 0: function (modifiers, name, constraint, defaultType) { + return createTypeParameterDeclaration(modifiers, name, constraint, defaultType); + }, + 1: function (name, constraint, defaultType) { + return createTypeParameterDeclaration(/*modifiers*/ undefined, name, constraint, defaultType); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0]; + return (modifiers === undefined || ts.isArray(modifiers)); + }, + 1: function (_a) { + var name = _a[0]; + return (name !== undefined && !ts.isArray(name)); + }, + }) + .deprecate({ + 1: { since: "4.7", warnAfter: "4.8", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + factory.updateTypeParameterDeclaration = ts.buildOverload("updateTypeParameterDeclaration") + .overload({ + 0: function (node, modifiers, name, constraint, defaultType) { + return updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType); + }, + 1: function (node, name, constraint, defaultType) { + return updateTypeParameterDeclaration(node, node.modifiers, name, constraint, defaultType); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1]; + return (modifiers === undefined || ts.isArray(modifiers)); + }, + 1: function (_a) { + var name = _a[1]; + return (name !== undefined && !ts.isArray(name)); + }, + }) + .deprecate({ + 1: { since: "4.7", warnAfter: "4.8", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Deprecate passing `decorators` separate from `modifiers` +// DEPRECATION PLAN: +// - soft: 4.8 +// - warn: 4.9 +// - error: 5.0 +var ts; +(function (ts) { + var MUST_MERGE = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators have been combined with modifiers. Callers should switch to an overload that does not accept a 'decorators' parameter." }; + var DISALLOW_DECORATORS = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators are no longer supported for this function. Callers should switch to an overload that does not accept a 'decorators' parameter." }; + var DISALLOW_DECORATORS_AND_MODIFIERS = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators and modifiers are no longer supported for this function. Callers should switch to an overload that does not accept the 'decorators' and 'modifiers' parameters." }; + function patchNodeFactory(factory) { + var createParameterDeclaration = factory.createParameterDeclaration, updateParameterDeclaration = factory.updateParameterDeclaration, createPropertyDeclaration = factory.createPropertyDeclaration, updatePropertyDeclaration = factory.updatePropertyDeclaration, createMethodDeclaration = factory.createMethodDeclaration, updateMethodDeclaration = factory.updateMethodDeclaration, createConstructorDeclaration = factory.createConstructorDeclaration, updateConstructorDeclaration = factory.updateConstructorDeclaration, createGetAccessorDeclaration = factory.createGetAccessorDeclaration, updateGetAccessorDeclaration = factory.updateGetAccessorDeclaration, createSetAccessorDeclaration = factory.createSetAccessorDeclaration, updateSetAccessorDeclaration = factory.updateSetAccessorDeclaration, createIndexSignature = factory.createIndexSignature, updateIndexSignature = factory.updateIndexSignature, createClassStaticBlockDeclaration = factory.createClassStaticBlockDeclaration, updateClassStaticBlockDeclaration = factory.updateClassStaticBlockDeclaration, createClassExpression = factory.createClassExpression, updateClassExpression = factory.updateClassExpression, createFunctionDeclaration = factory.createFunctionDeclaration, updateFunctionDeclaration = factory.updateFunctionDeclaration, createClassDeclaration = factory.createClassDeclaration, updateClassDeclaration = factory.updateClassDeclaration, createInterfaceDeclaration = factory.createInterfaceDeclaration, updateInterfaceDeclaration = factory.updateInterfaceDeclaration, createTypeAliasDeclaration = factory.createTypeAliasDeclaration, updateTypeAliasDeclaration = factory.updateTypeAliasDeclaration, createEnumDeclaration = factory.createEnumDeclaration, updateEnumDeclaration = factory.updateEnumDeclaration, createModuleDeclaration = factory.createModuleDeclaration, updateModuleDeclaration = factory.updateModuleDeclaration, createImportEqualsDeclaration = factory.createImportEqualsDeclaration, updateImportEqualsDeclaration = factory.updateImportEqualsDeclaration, createImportDeclaration = factory.createImportDeclaration, updateImportDeclaration = factory.updateImportDeclaration, createExportAssignment = factory.createExportAssignment, updateExportAssignment = factory.updateExportAssignment, createExportDeclaration = factory.createExportDeclaration, updateExportDeclaration = factory.updateExportDeclaration; + factory.createParameterDeclaration = ts.buildOverload("createParameterDeclaration") + .overload({ + 0: function (modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer); + }, + 1: function (decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return createParameterDeclaration(ts.concatenate(decorators, modifiers), dotDotDotToken, name, questionToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var dotDotDotToken = _a[1], name = _a[2], questionToken = _a[3], type = _a[4], initializer = _a[5], other = _a[6]; + return (other === undefined) && + (dotDotDotToken === undefined || !ts.isArray(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[1], dotDotDotToken = _a[2], name = _a[3], questionToken = _a[4], type = _a[5], initializer = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (dotDotDotToken === undefined || typeof dotDotDotToken === "object" && ts.isDotDotDotToken(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateParameterDeclaration = ts.buildOverload("updateParameterDeclaration") + .overload({ + 0: function (node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer); + }, + 1: function (node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return updateParameterDeclaration(node, ts.concatenate(decorators, modifiers), dotDotDotToken, name, questionToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var dotDotDotToken = _a[2], name = _a[3], questionToken = _a[4], type = _a[5], initializer = _a[6], other = _a[7]; + return (other === undefined) && + (dotDotDotToken === undefined || !ts.isArray(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[2], dotDotDotToken = _a[3], name = _a[4], questionToken = _a[5], type = _a[6], initializer = _a[7]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (dotDotDotToken === undefined || typeof dotDotDotToken === "object" && ts.isDotDotDotToken(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createPropertyDeclaration = ts.buildOverload("createPropertyDeclaration") + .overload({ + 0: function (modifiers, name, questionOrExclamationToken, type, initializer) { + return createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer); + }, + 1: function (decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return createPropertyDeclaration(ts.concatenate(decorators, modifiers), name, questionOrExclamationToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], questionOrExclamationToken = _a[2], type = _a[3], initializer = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (questionOrExclamationToken === undefined || typeof questionOrExclamationToken === "object" && ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], questionOrExclamationToken = _a[3], type = _a[4], initializer = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionOrExclamationToken === undefined || ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updatePropertyDeclaration = ts.buildOverload("updatePropertyDeclaration") + .overload({ + 0: function (node, modifiers, name, questionOrExclamationToken, type, initializer) { + return updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer); + }, + 1: function (node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return updatePropertyDeclaration(node, ts.concatenate(decorators, modifiers), name, questionOrExclamationToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], questionOrExclamationToken = _a[3], type = _a[4], initializer = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (questionOrExclamationToken === undefined || typeof questionOrExclamationToken === "object" && ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], questionOrExclamationToken = _a[4], type = _a[5], initializer = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionOrExclamationToken === undefined || ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createMethodDeclaration = ts.buildOverload("createMethodDeclaration") + .overload({ + 0: function (modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + 1: function (decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return createMethodDeclaration(ts.concatenate(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[1], name = _a[2], questionToken = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7], other = _a[8]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || !ts.some(parameters, ts.isTypeParameterDeclaration)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], asteriskToken = _a[2], name = _a[3], questionToken = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken === "object" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || !ts.isArray(questionToken)) && + (typeParameters === undefined || !ts.some(typeParameters, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateMethodDeclaration = ts.buildOverload("updateMethodDeclaration") + .overload({ + 0: function (node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + 1: function (node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return updateMethodDeclaration(node, ts.concatenate(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[2], name = _a[3], questionToken = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8], other = _a[9]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || !ts.some(parameters, ts.isTypeParameterDeclaration)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], asteriskToken = _a[3], name = _a[4], questionToken = _a[5], typeParameters = _a[6], parameters = _a[7], type = _a[8], body = _a[9]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken === "object" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || !ts.isArray(questionToken)) && + (typeParameters === undefined || !ts.some(typeParameters, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createConstructorDeclaration = ts.buildOverload("createConstructorDeclaration") + .overload({ + 0: function (modifiers, parameters, body) { + return createConstructorDeclaration(modifiers, parameters, body); + }, + 1: function (_decorators, modifiers, parameters, body) { + return createConstructorDeclaration(modifiers, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], parameters = _a[1], body = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || !ts.some(modifiers, ts.isDecorator)) && + (parameters === undefined || !ts.some(parameters, ts.isModifier)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], parameters = _a[2], body = _a[3]; + return (decorators === undefined || !ts.some(decorators, ts.isModifier)) && + (modifiers === undefined || !ts.some(modifiers, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateConstructorDeclaration = ts.buildOverload("updateConstructorDeclaration") + .overload({ + 0: function (node, modifiers, parameters, body) { + return updateConstructorDeclaration(node, modifiers, parameters, body); + }, + 1: function (node, _decorators, modifiers, parameters, body) { + return updateConstructorDeclaration(node, modifiers, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], parameters = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || !ts.some(modifiers, ts.isDecorator)) && + (parameters === undefined || !ts.some(parameters, ts.isModifier)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], parameters = _a[3], body = _a[4]; + return (decorators === undefined || !ts.some(decorators, ts.isModifier)) && + (modifiers === undefined || !ts.some(modifiers, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createGetAccessorDeclaration = ts.buildOverload("createGetAccessorDeclaration") + .overload({ + 0: function (modifiers, name, parameters, type, body) { + return createGetAccessorDeclaration(modifiers, name, parameters, type, body); + }, + 1: function (decorators, modifiers, name, parameters, type, body) { + return createGetAccessorDeclaration(ts.concatenate(decorators, modifiers), name, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], parameters = _a[2], type = _a[3], body = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], parameters = _a[3], type = _a[4], body = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateGetAccessorDeclaration = ts.buildOverload("updateGetAccessorDeclaration") + .overload({ + 0: function (node, modifiers, name, parameters, type, body) { + return updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body); + }, + 1: function (node, decorators, modifiers, name, parameters, type, body) { + return updateGetAccessorDeclaration(node, ts.concatenate(decorators, modifiers), name, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], parameters = _a[3], type = _a[4], body = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], parameters = _a[4], type = _a[5], body = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createSetAccessorDeclaration = ts.buildOverload("createSetAccessorDeclaration") + .overload({ + 0: function (modifiers, name, parameters, body) { + return createSetAccessorDeclaration(modifiers, name, parameters, body); + }, + 1: function (decorators, modifiers, name, parameters, body) { + return createSetAccessorDeclaration(ts.concatenate(decorators, modifiers), name, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], parameters = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], parameters = _a[3], body = _a[4]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateSetAccessorDeclaration = ts.buildOverload("updateSetAccessorDeclaration") + .overload({ + 0: function (node, modifiers, name, parameters, body) { + return updateSetAccessorDeclaration(node, modifiers, name, parameters, body); + }, + 1: function (node, decorators, modifiers, name, parameters, body) { + return updateSetAccessorDeclaration(node, ts.concatenate(decorators, modifiers), name, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], parameters = _a[3], body = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], parameters = _a[4], body = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createIndexSignature = ts.buildOverload("createIndexSignature") + .overload({ + 0: function (modifiers, parameters, type) { + return createIndexSignature(modifiers, parameters, type); + }, + 1: function (_decorators, modifiers, parameters, type) { + return createIndexSignature(modifiers, parameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], parameters = _a[1], type = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], parameters = _a[2], type = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateIndexSignature = ts.buildOverload("updateIndexSignature") + .overload({ + 0: function (node, modifiers, parameters, type) { + return updateIndexSignature(node, modifiers, parameters, type); + }, + 1: function (node, _decorators, modifiers, parameters, type) { + return updateIndexSignature(node, modifiers, parameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], parameters = _a[2], type = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], parameters = _a[3], type = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createClassStaticBlockDeclaration = ts.buildOverload("createClassStaticBlockDeclaration") + .overload({ + 0: function (body) { + return createClassStaticBlockDeclaration(body); + }, + 1: function (_decorators, _modifiers, body) { + return createClassStaticBlockDeclaration(body); + }, + }) + .bind({ + 0: function (_a) { + var body = _a[0], other1 = _a[1], other2 = _a[2]; + return (other1 === undefined) && + (other2 === undefined) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], body = _a[2]; + return (decorators === undefined || ts.isArray(decorators)) && + (modifiers === undefined || ts.isArray(decorators)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS_AND_MODIFIERS + }) + .finish(); + factory.updateClassStaticBlockDeclaration = ts.buildOverload("updateClassStaticBlockDeclaration") + .overload({ + 0: function (node, body) { + return updateClassStaticBlockDeclaration(node, body); + }, + 1: function (node, _decorators, _modifiers, body) { + return updateClassStaticBlockDeclaration(node, body); + }, + }) + .bind({ + 0: function (_a) { + var body = _a[1], other1 = _a[2], other2 = _a[3]; + return (other1 === undefined) && + (other2 === undefined) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], body = _a[3]; + return (decorators === undefined || ts.isArray(decorators)) && + (modifiers === undefined || ts.isArray(decorators)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS_AND_MODIFIERS + }) + .finish(); + factory.createClassExpression = ts.buildOverload("createClassExpression") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createClassExpression(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createClassExpression(ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateClassExpression = ts.buildOverload("updateClassExpression") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassExpression(node, ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createFunctionDeclaration = ts.buildOverload("createFunctionDeclaration") + .overload({ + 0: function (modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + 1: function (_decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[1], name = _a[2], typeParameters = _a[3], parameters = _a[4], type = _a[5], body = _a[6], other = _a[7]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isIdentifier(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], asteriskToken = _a[2], name = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken !== "string" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateFunctionDeclaration = ts.buildOverload("updateFunctionDeclaration") + .overload({ + 0: function (node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + 1: function (node, _decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[2], name = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7], other = _a[8]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || ts.isIdentifier(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], asteriskToken = _a[3], name = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken !== "string" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createClassDeclaration = ts.buildOverload("createClassDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createClassDeclaration(ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function () { return true; }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateClassDeclaration = ts.buildOverload("updateClassDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createInterfaceDeclaration = ts.buildOverload("createInterfaceDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (_decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateInterfaceDeclaration = ts.buildOverload("updateInterfaceDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, _decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createTypeAliasDeclaration = ts.buildOverload("createTypeAliasDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, type) { + return createTypeAliasDeclaration(modifiers, name, typeParameters, type); + }, + 1: function (_decorators, modifiers, name, typeParameters, type) { + return createTypeAliasDeclaration(modifiers, name, typeParameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], typeParameters = _a[2], type = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], typeParameters = _a[3], type = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateTypeAliasDeclaration = ts.buildOverload("updateTypeAliasDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, type) { + return updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type); + }, + 1: function (node, _decorators, modifiers, name, typeParameters, type) { + return updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], type = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], typeParameters = _a[4], type = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createEnumDeclaration = ts.buildOverload("createEnumDeclaration") + .overload({ + 0: function (modifiers, name, members) { + return createEnumDeclaration(modifiers, name, members); + }, + 1: function (_decorators, modifiers, name, members) { + return createEnumDeclaration(modifiers, name, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], members = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], members = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateEnumDeclaration = ts.buildOverload("updateEnumDeclaration") + .overload({ + 0: function (node, modifiers, name, members) { + return updateEnumDeclaration(node, modifiers, name, members); + }, + 1: function (node, _decorators, modifiers, name, members) { + return updateEnumDeclaration(node, modifiers, name, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], members = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], members = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createModuleDeclaration = ts.buildOverload("createModuleDeclaration") + .overload({ + 0: function (modifiers, name, body, flags) { + return createModuleDeclaration(modifiers, name, body, flags); + }, + 1: function (_decorators, modifiers, name, body, flags) { + return createModuleDeclaration(modifiers, name, body, flags); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], body = _a[2], flags = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name !== undefined && !ts.isArray(name)) && + (body === undefined || ts.isModuleBody(body)) && + (flags === undefined || typeof flags === "number"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], body = _a[3], flags = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name !== undefined && ts.isModuleName(name)) && + (body === undefined || typeof body === "object") && + (flags === undefined || typeof flags === "number"); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateModuleDeclaration = ts.buildOverload("updateModuleDeclaration") + .overload({ + 0: function (node, modifiers, name, body) { + return updateModuleDeclaration(node, modifiers, name, body); + }, + 1: function (node, _decorators, modifiers, name, body) { + return updateModuleDeclaration(node, modifiers, name, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (body === undefined || ts.isModuleBody(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], body = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name !== undefined && ts.isModuleName(name)) && + (body === undefined || ts.isModuleBody(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createImportEqualsDeclaration = ts.buildOverload("createImportEqualsDeclaration") + .overload({ + 0: function (modifiers, isTypeOnly, name, moduleReference) { + return createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference); + }, + 1: function (_decorators, modifiers, isTypeOnly, name, moduleReference) { + return createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isTypeOnly = _a[1], name = _a[2], moduleReference = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name !== "boolean") && + (typeof moduleReference !== "string"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isTypeOnly = _a[2], name = _a[3], moduleReference = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name === "string" || ts.isIdentifier(name)) && + (moduleReference !== undefined && ts.isModuleReference(moduleReference)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateImportEqualsDeclaration = ts.buildOverload("updateImportEqualsDeclaration") + .overload({ + 0: function (node, modifiers, isTypeOnly, name, moduleReference) { + return updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference); + }, + 1: function (node, _decorators, modifiers, isTypeOnly, name, moduleReference) { + return updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], isTypeOnly = _a[2], name = _a[3], moduleReference = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name !== "boolean") && + (typeof moduleReference !== "string"); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], isTypeOnly = _a[3], name = _a[4], moduleReference = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name === "string" || ts.isIdentifier(name)) && + (moduleReference !== undefined && ts.isModuleReference(moduleReference)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createImportDeclaration = ts.buildOverload("createImportDeclaration") + .overload({ + 0: function (modifiers, importClause, moduleSpecifier, assertClause) { + return createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + }, + 1: function (_decorators, modifiers, importClause, moduleSpecifier, assertClause) { + return createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], importClause = _a[1], moduleSpecifier = _a[2], assertClause = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (importClause === undefined || !ts.isArray(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], importClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (importClause === undefined || ts.isImportClause(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateImportDeclaration = ts.buildOverload("updateImportDeclaration") + .overload({ + 0: function (node, modifiers, importClause, moduleSpecifier, assertClause) { + return updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause); + }, + 1: function (node, _decorators, modifiers, importClause, moduleSpecifier, assertClause) { + return updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], importClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (importClause === undefined || !ts.isArray(importClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], importClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (importClause === undefined || ts.isImportClause(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createExportAssignment = ts.buildOverload("createExportAssignment") + .overload({ + 0: function (modifiers, isExportEquals, expression) { + return createExportAssignment(modifiers, isExportEquals, expression); + }, + 1: function (_decorators, modifiers, isExportEquals, expression) { + return createExportAssignment(modifiers, isExportEquals, expression); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isExportEquals = _a[1], expression = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isExportEquals === undefined || typeof isExportEquals === "boolean") && + (typeof expression === "object"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isExportEquals = _a[2], expression = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isExportEquals === undefined || typeof isExportEquals === "boolean") && + (expression !== undefined && ts.isExpression(expression)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateExportAssignment = ts.buildOverload("updateExportAssignment") + .overload({ + 0: function (node, modifiers, expression) { + return updateExportAssignment(node, modifiers, expression); + }, + 1: function (node, _decorators, modifiers, expression) { + return updateExportAssignment(node, modifiers, expression); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], expression = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (expression !== undefined && !ts.isArray(expression)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], expression = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (expression !== undefined && ts.isExpression(expression)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createExportDeclaration = ts.buildOverload("createExportDeclaration") + .overload({ + 0: function (modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + 1: function (_decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isTypeOnly = _a[1], exportClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (typeof isTypeOnly === "boolean") && + (typeof exportClause !== "boolean") && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isTypeOnly = _a[2], exportClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (typeof isTypeOnly === "boolean") && + (exportClause === undefined || ts.isNamedExportBindings(exportClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateExportDeclaration = ts.buildOverload("updateExportDeclaration") + .overload({ + 0: function (node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + 1: function (node, _decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], isTypeOnly = _a[2], exportClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5], other = _a[6]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (typeof isTypeOnly === "boolean") && + (typeof exportClause !== "boolean") && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], isTypeOnly = _a[3], exportClause = _a[4], moduleSpecifier = _a[5], assertClause = _a[6]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (typeof isTypeOnly === "boolean") && + (exportClause === undefined || ts.isNamedExportBindings(exportClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + if (typeof console !== "undefined") { + ts.Debug.loggingHost = { + log: function (level, s) { + switch (level) { + case ts.LogLevel.Error: return console.error(s); + case ts.LogLevel.Warning: return console.warn(s); + case ts.LogLevel.Info: return console.log(s); + case ts.LogLevel.Verbose: return console.log(s); + } + } + }; + } })(ts || (ts = {})); diff --git a/tsserver/typescriptServices.d.ts b/tsserver/typescriptServices.d.ts index 75f7eaab..9309fde2 100644 --- a/tsserver/typescriptServices.d.ts +++ b/tsserver/typescriptServices.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "4.7"; + const versionMajorMinor = "4.8"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -425,6 +425,7 @@ declare namespace ts { JSDocFunctionType = 317, JSDocVariadicType = 318, JSDocNamepathType = 319, + JSDoc = 320, /** @deprecated Use SyntaxKind.JSDoc */ JSDocComment = 320, JSDocText = 321, @@ -493,7 +494,6 @@ declare namespace ts { LastJSDocNode = 347, FirstJSDocTagNode = 327, LastJSDocTagNode = 347, - JSDoc = 320 } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; @@ -554,13 +554,15 @@ declare namespace ts { Override = 16384, In = 32768, Out = 65536, + Decorator = 131072, HasComputedFlags = 536870912, AccessibilityModifier = 28, ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, TypeScriptModifier = 116958, ExportDefault = 513, - All = 125951 + All = 257023, + Modifier = 125951 } export enum JsxFlags { None = 0, @@ -573,8 +575,6 @@ declare namespace ts { export interface Node extends ReadonlyTextRange { readonly kind: SyntaxKind; readonly flags: NodeFlags; - readonly decorators?: NodeArray; - readonly modifiers?: ModifiersArray; readonly parent: Node; } export interface JSDocContainer { @@ -583,7 +583,9 @@ declare namespace ts { export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; export type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; - export type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; + export type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | EnumMember; + export type HasDecorators = ParameterDeclaration | PropertyDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ClassExpression | ClassDeclaration; + export type HasModifiers = TypeParameterDeclaration | ParameterDeclaration | ConstructorTypeNode | PropertySignature | PropertyDeclaration | MethodSignature | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | IndexSignatureDeclaration | FunctionExpression | ArrowFunction | ClassExpression | VariableStatement | FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | ExportAssignment | ExportDeclaration; export interface NodeArray extends ReadonlyArray, ReadonlyTextRange { readonly hasTrailingComma: boolean; } @@ -632,6 +634,7 @@ declare namespace ts { /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | InKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OutKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; + export type ModifierLike = Modifier | Decorator; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; @@ -691,6 +694,7 @@ declare namespace ts { export interface TypeParameterDeclaration extends NamedDeclaration { readonly kind: SyntaxKind.TypeParameter; readonly parent: DeclarationWithTypeParameterChildren | InferTypeNode; + readonly modifiers?: NodeArray; readonly name: Identifier; /** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */ readonly constraint?: TypeNode; @@ -700,9 +704,9 @@ declare namespace ts { export interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { readonly kind: SignatureDeclaration["kind"]; readonly name?: PropertyName; - readonly typeParameters?: NodeArray; + readonly typeParameters?: NodeArray | undefined; readonly parameters: NodeArray; - readonly type?: TypeNode; + readonly type?: TypeNode | undefined; } export type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; export interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { @@ -728,6 +732,7 @@ declare namespace ts { export interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.Parameter; readonly parent: SignatureDeclaration; + readonly modifiers?: NodeArray; readonly dotDotDotToken?: DotDotDotToken; readonly name: BindingName; readonly questionToken?: QuestionToken; @@ -744,14 +749,15 @@ declare namespace ts { } export interface PropertySignature extends TypeElement, JSDocContainer { readonly kind: SyntaxKind.PropertySignature; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly questionToken?: QuestionToken; readonly type?: TypeNode; - initializer?: Expression; } export interface PropertyDeclaration extends ClassElement, JSDocContainer { readonly kind: SyntaxKind.PropertyDeclaration; readonly parent: ClassLikeDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly questionToken?: QuestionToken; readonly exclamationToken?: ExclamationToken; @@ -768,16 +774,12 @@ declare namespace ts { readonly kind: SyntaxKind.PropertyAssignment; readonly parent: ObjectLiteralExpression; readonly name: PropertyName; - readonly questionToken?: QuestionToken; - readonly exclamationToken?: ExclamationToken; readonly initializer: Expression; } export interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.ShorthandPropertyAssignment; readonly parent: ObjectLiteralExpression; readonly name: Identifier; - readonly questionToken?: QuestionToken; - readonly exclamationToken?: ExclamationToken; readonly equalsToken?: EqualsToken; readonly objectAssignmentInitializer?: Expression; } @@ -812,34 +814,38 @@ declare namespace ts { */ export interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { _functionLikeDeclarationBrand: any; - readonly asteriskToken?: AsteriskToken; - readonly questionToken?: QuestionToken; - readonly exclamationToken?: ExclamationToken; - readonly body?: Block | Expression; + readonly asteriskToken?: AsteriskToken | undefined; + readonly questionToken?: QuestionToken | undefined; + readonly exclamationToken?: ExclamationToken | undefined; + readonly body?: Block | Expression | undefined; } export type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; /** @deprecated Use SignatureDeclaration */ export type FunctionLike = SignatureDeclaration; export interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { readonly kind: SyntaxKind.FunctionDeclaration; + readonly modifiers?: NodeArray; readonly name?: Identifier; readonly body?: FunctionBody; } export interface MethodSignature extends SignatureDeclarationBase, TypeElement { readonly kind: SyntaxKind.MethodSignature; readonly parent: ObjectTypeDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; } export interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.MethodDeclaration; readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly modifiers?: NodeArray | undefined; readonly name: PropertyName; - readonly body?: FunctionBody; + readonly body?: FunctionBody | undefined; } export interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { readonly kind: SyntaxKind.Constructor; readonly parent: ClassLikeDeclaration; - readonly body?: FunctionBody; + readonly modifiers?: NodeArray | undefined; + readonly body?: FunctionBody | undefined; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ export interface SemicolonClassElement extends ClassElement { @@ -849,12 +855,14 @@ declare namespace ts { export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.GetAccessor; readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly body?: FunctionBody; } export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.SetAccessor; readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; + readonly modifiers?: NodeArray; readonly name: PropertyName; readonly body?: FunctionBody; } @@ -862,6 +870,7 @@ declare namespace ts { export interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { readonly kind: SyntaxKind.IndexSignature; readonly parent: ObjectTypeDeclaration; + readonly modifiers?: NodeArray; readonly type: TypeNode; } export interface ClassStaticBlockDeclaration extends ClassElement, JSDocContainer { @@ -901,6 +910,7 @@ declare namespace ts { } export interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase { readonly kind: SyntaxKind.ConstructorType; + readonly modifiers?: NodeArray; } export interface NodeWithTypeArguments extends TypeNode { readonly typeArguments?: NodeArray; @@ -1157,11 +1167,13 @@ declare namespace ts { export type ConciseBody = FunctionBody | Expression; export interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.FunctionExpression; + readonly modifiers?: NodeArray; readonly name?: Identifier; readonly body: FunctionBody; } export interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.ArrowFunction; + readonly modifiers?: NodeArray; readonly equalsGreaterThanToken: EqualsGreaterThanToken; readonly body: ConciseBody; readonly name: never; @@ -1388,8 +1400,9 @@ declare namespace ts { readonly kind: SyntaxKind.JsxAttribute; readonly parent: JsxAttributes; readonly name: Identifier; - readonly initializer?: StringLiteral | JsxExpression; + readonly initializer?: JsxAttributeValue; } + export type JsxAttributeValue = StringLiteral | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; export interface JsxSpreadAttribute extends ObjectLiteralElement { readonly kind: SyntaxKind.JsxSpreadAttribute; readonly parent: JsxAttributes; @@ -1442,6 +1455,7 @@ declare namespace ts { } export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; + readonly modifiers?: NodeArray; readonly declarationList: VariableDeclarationList; } export interface ExpressionStatement extends Statement { @@ -1558,11 +1572,13 @@ declare namespace ts { } export interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { readonly kind: SyntaxKind.ClassDeclaration; + readonly modifiers?: NodeArray; /** May be undefined in `export default class { ... }`. */ readonly name?: Identifier; } export interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { readonly kind: SyntaxKind.ClassExpression; + readonly modifiers?: NodeArray; } export type ClassLikeDeclaration = ClassDeclaration | ClassExpression; export interface ClassElement extends NamedDeclaration { @@ -1572,10 +1588,11 @@ declare namespace ts { export interface TypeElement extends NamedDeclaration { _typeElementBrand: any; readonly name?: PropertyName; - readonly questionToken?: QuestionToken; + readonly questionToken?: QuestionToken | undefined; } export interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.InterfaceDeclaration; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly typeParameters?: NodeArray; readonly heritageClauses?: NodeArray; @@ -1589,6 +1606,7 @@ declare namespace ts { } export interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.TypeAliasDeclaration; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly typeParameters?: NodeArray; readonly type: TypeNode; @@ -1601,6 +1619,7 @@ declare namespace ts { } export interface EnumDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.EnumDeclaration; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly members: NodeArray; } @@ -1609,6 +1628,7 @@ declare namespace ts { export interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ModuleDeclaration; readonly parent: ModuleBody | SourceFile; + readonly modifiers?: NodeArray; readonly name: ModuleName; readonly body?: ModuleBody | JSDocNamespaceDeclaration; } @@ -1636,6 +1656,7 @@ declare namespace ts { export interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ImportEqualsDeclaration; readonly parent: SourceFile | ModuleBlock; + readonly modifiers?: NodeArray; readonly name: Identifier; readonly isTypeOnly: boolean; readonly moduleReference: ModuleReference; @@ -1648,6 +1669,7 @@ declare namespace ts { export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; + readonly modifiers?: NodeArray; readonly importClause?: ImportClause; /** If this is not a StringLiteral it will be a grammar error. */ readonly moduleSpecifier: Expression; @@ -1692,6 +1714,7 @@ declare namespace ts { export interface ExportDeclaration extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ExportDeclaration; readonly parent: SourceFile | ModuleBlock; + readonly modifiers?: NodeArray; readonly isTypeOnly: boolean; /** Will not be assigned in the case of `export * from "foo";` */ readonly exportClause?: NamedExportBindings; @@ -1759,6 +1782,7 @@ declare namespace ts { export interface ExportAssignment extends DeclarationStatement, JSDocContainer { readonly kind: SyntaxKind.ExportAssignment; readonly parent: SourceFile; + readonly modifiers?: NodeArray; readonly isExportEquals?: boolean; readonly expression: Expression; } @@ -2072,6 +2096,12 @@ declare namespace ts { * It is _public_ so that (pre)transformers can set this field, * since it switches the builtin `node` module transform. Generally speaking, if unset, * the field is treated as though it is `ModuleKind.CommonJS`. + * + * Note that this field is only set by the module resolution process when + * `moduleResolution` is `Node16` or `NodeNext`, which is implied by the `module` setting + * of `Node16` or `NodeNext`, respectively, but may be overriden (eg, by a `moduleResolution` + * of `node`). If so, this field will be unset and source files will be considered to be + * CommonJS-output-format by the node module transformer and type checker, regardless of extension or context. */ impliedNodeFormat?: ModuleKind.ESNext | ModuleKind.CommonJS; } @@ -2396,6 +2426,7 @@ declare namespace ts { UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, NoTypeReduction = 536870912, + OmitThisParameter = 33554432, AllowThisInObjectLiteral = 32768, AllowQualifiedNameInPlaceOfIdentifier = 65536, /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ @@ -2426,6 +2457,7 @@ declare namespace ts { UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, NoTypeReduction = 536870912, + OmitThisParameter = 33554432, AllowUniqueESSymbolType = 1048576, AddUndefined = 131072, WriteArrowStyleSignature = 262144, @@ -2434,7 +2466,7 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 814775659 + NodeBuilderFlagsMask = 848330091 } export enum SymbolFormatFlags { None = 0, @@ -3402,39 +3434,35 @@ declare namespace ts { createComputedPropertyName(expression: Expression): ComputedPropertyName; updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; createTypeParameterDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; - /** @deprecated */ - createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - /** @deprecated */ - updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - createParameterDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; - updateParameterDeclaration(node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + createParameterDeclaration(modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + updateParameterDeclaration(node: ParameterDeclaration, modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; createDecorator(expression: Expression): Decorator; updateDecorator(node: Decorator, expression: Expression): Decorator; createPropertySignature(modifiers: readonly Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature; updatePropertySignature(node: PropertySignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature; - createPropertyDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; - updatePropertyDeclaration(node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + createPropertyDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + updatePropertyDeclaration(node: PropertyDeclaration, modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; createMethodSignature(modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): MethodSignature; updateMethodSignature(node: MethodSignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): MethodSignature; - createMethodDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; - updateMethodDeclaration(node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; - createConstructorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; - updateConstructorDeclaration(node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; - createGetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - updateGetAccessorDeclaration(node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - createSetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; - updateSetAccessorDeclaration(node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + createMethodDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + updateMethodDeclaration(node: MethodDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + createConstructorDeclaration(modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + updateConstructorDeclaration(node: ConstructorDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + createGetAccessorDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + updateGetAccessorDeclaration(node: GetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + createSetAccessorDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + updateSetAccessorDeclaration(node: SetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; createCallSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; createConstructSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - createIndexSignature(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - updateIndexSignature(node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + createIndexSignature(modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + updateIndexSignature(node: IndexSignatureDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; createTemplateLiteralTypeSpan(type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan; updateTemplateLiteralTypeSpan(node: TemplateLiteralTypeSpan, type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan; - createClassStaticBlockDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; - updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; + createClassStaticBlockDeclaration(body: Block): ClassStaticBlockDeclaration; + updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, body: Block): ClassStaticBlockDeclaration; createKeywordTypeNode(kind: TKind): KeywordTypeNode; createTypePredicateNode(assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode | string, type: TypeNode | undefined): TypePredicateNode; updateTypePredicateNode(node: TypePredicateNode, assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode, type: TypeNode | undefined): TypePredicateNode; @@ -3443,11 +3471,7 @@ declare namespace ts { createFunctionTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): FunctionTypeNode; updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): FunctionTypeNode; createConstructorTypeNode(modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; - /** @deprecated */ - createConstructorTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; updateConstructorTypeNode(node: ConstructorTypeNode, modifiers: readonly Modifier[] | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; - /** @deprecated */ - updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; createTypeQueryNode(exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode; updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode; createTypeLiteralNode(members: readonly TypeElement[] | undefined): TypeLiteralNode; @@ -3470,9 +3494,7 @@ declare namespace ts { updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode; updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode; - createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; createImportTypeNode(argument: TypeNode, assertions?: ImportTypeAssertionContainer, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; - updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; @@ -3552,8 +3574,8 @@ declare namespace ts { updateYieldExpression(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression | undefined): YieldExpression; createSpreadElement(expression: Expression): SpreadElement; updateSpreadElement(node: SpreadElement, expression: Expression): SpreadElement; - createClassExpression(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; - updateClassExpression(node: ClassExpression, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + createClassExpression(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + updateClassExpression(node: ClassExpression, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; createOmittedExpression(): OmittedExpression; createExpressionWithTypeArguments(expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments; updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments; @@ -3608,28 +3630,28 @@ declare namespace ts { updateVariableDeclaration(node: VariableDeclaration, name: BindingName, exclamationToken: ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; createVariableDeclarationList(declarations: readonly VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; updateVariableDeclarationList(node: VariableDeclarationList, declarations: readonly VariableDeclaration[]): VariableDeclarationList; - createFunctionDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - updateFunctionDeclaration(node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - createClassDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; - updateClassDeclaration(node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; - createInterfaceDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; - updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; - createTypeAliasDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; - updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; - createEnumDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; - updateEnumDeclaration(node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; - createModuleDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; - updateModuleDeclaration(node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + createFunctionDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + updateFunctionDeclaration(node: FunctionDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + createClassDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + updateClassDeclaration(node: ClassDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + createInterfaceDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + updateInterfaceDeclaration(node: InterfaceDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + createTypeAliasDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + updateTypeAliasDeclaration(node: TypeAliasDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + createEnumDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + updateEnumDeclaration(node: EnumDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + createModuleDeclaration(modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + updateModuleDeclaration(node: ModuleDeclaration, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; createModuleBlock(statements: readonly Statement[]): ModuleBlock; updateModuleBlock(node: ModuleBlock, statements: readonly Statement[]): ModuleBlock; createCaseBlock(clauses: readonly CaseOrDefaultClause[]): CaseBlock; updateCaseBlock(node: CaseBlock, clauses: readonly CaseOrDefaultClause[]): CaseBlock; createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; - createImportEqualsDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - createImportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; - updateImportDeclaration(node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + createImportEqualsDeclaration(modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + updateImportEqualsDeclaration(node: ImportEqualsDeclaration, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + createImportDeclaration(modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; + updateImportDeclaration(node: ImportDeclaration, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; createAssertClause(elements: NodeArray, multiLine?: boolean): AssertClause; @@ -3646,10 +3668,10 @@ declare namespace ts { updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports; createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - createExportAssignment(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; - updateExportAssignment(node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; - createExportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; - updateExportDeclaration(node: ExportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; + createExportAssignment(modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + updateExportAssignment(node: ExportAssignment, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + createExportDeclaration(modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; + updateExportDeclaration(node: ExportDeclaration, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; createNamedExports(elements: readonly ExportSpecifier[]): NamedExports; updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports; createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; @@ -3746,8 +3768,8 @@ declare namespace ts { createJsxOpeningFragment(): JsxOpeningFragment; createJsxJsxClosingFragment(): JsxClosingFragment; updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment): JsxFragment; - createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression | undefined): JsxAttribute; - updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression | undefined): JsxAttribute; + createJsxAttribute(name: Identifier, initializer: JsxAttributeValue | undefined): JsxAttribute; + updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: JsxAttributeValue | undefined): JsxAttribute; createJsxAttributes(properties: readonly JsxAttributeLike[]): JsxAttributes; updateJsxAttributes(node: JsxAttributes, properties: readonly JsxAttributeLike[]): JsxAttributes; createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; @@ -4055,7 +4077,7 @@ declare namespace ts { NoSpaceIfEmpty = 524288, SingleElement = 1048576, SpaceAfterList = 2097152, - Modifiers = 262656, + Modifiers = 2359808, HeritageClauses = 512, SingleLineTypeLiteralMembers = 768, MultiLineTypeLiteralMembers = 32897, @@ -4119,9 +4141,12 @@ declare namespace ts { readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; readonly includeInlayFunctionParameterTypeHints?: boolean; readonly includeInlayVariableTypeHints?: boolean; + readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; readonly includeInlayPropertyDeclarationTypeHints?: boolean; readonly includeInlayFunctionLikeReturnTypeHints?: boolean; readonly includeInlayEnumMemberValueHints?: boolean; + readonly allowRenameOfImportPath?: boolean; + readonly autoImportFileExcludePatterns?: string[]; } /** Represents a bigint literal value without requiring bigint support */ export interface PseudoBigInt { @@ -4138,7 +4163,7 @@ declare namespace ts { Changed = 1, Deleted = 2 } - export type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; + export type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind, modifiedTime?: Date) => void; export type DirectoryWatcherCallback = (fileName: string) => void; export interface System { args: string[]; @@ -4349,6 +4374,8 @@ declare namespace ts { function symbolName(symbol: Symbol): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined; function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined; + function getDecorators(node: HasDecorators): readonly Decorator[] | undefined; + function getModifiers(node: HasModifiers): readonly Modifier[] | undefined; /** * Gets the JSDoc parameter tags for the node if present. * @@ -4437,6 +4464,12 @@ declare namespace ts { /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + * + * This does *not* return type parameters from a jsdoc reference to a generic type, eg + * + * type Id = (x: T) => T + * /** @type {Id} / + * function id(x) { return x } */ function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[]; function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; @@ -4482,6 +4515,7 @@ declare namespace ts { function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; + function isModifierLike(node: Node): node is ModifierLike; function isTypeElement(node: Node): node is TypeElement; function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement; function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; @@ -4510,6 +4544,8 @@ declare namespace ts { function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; function isStringLiteralLike(node: Node): node is StringLiteralLike; function isJSDocLinkLike(node: Node): node is JSDocLink | JSDocLinkCode | JSDocLinkPlain; + function hasRestParameter(s: SignatureDeclaration | JSDocSignature): boolean; + function isRestParameter(node: ParameterDeclaration | JSDocParameterTag): boolean; } declare namespace ts { const factory: NodeFactory; @@ -4720,6 +4756,7 @@ declare namespace ts { function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; function isImportDeclaration(node: Node): node is ImportDeclaration; function isImportClause(node: Node): node is ImportClause; + function isImportTypeAssertionContainer(node: Node): node is ImportTypeAssertionContainer; function isAssertClause(node: Node): node is AssertClause; function isAssertEntry(node: Node): node is AssertEntry; function isNamespaceImport(node: Node): node is NamespaceImport; @@ -4797,6 +4834,8 @@ declare namespace ts { } declare namespace ts { function setTextRange(range: T, location: TextRange | undefined): T; + function canHaveModifiers(node: Node): node is HasModifiers; + function canHaveDecorators(node: Node): node is HasDecorators; } declare namespace ts { /** @@ -5098,6 +5137,31 @@ declare namespace ts { export function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; export function formatDiagnosticsWithColorAndContext(diagnostics: readonly Diagnostic[], host: FormatDiagnosticsHost): string; export function flattenDiagnosticMessageText(diag: string | DiagnosticMessageChain | undefined, newLine: string, indent?: number): string; + /** + * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly + * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. + */ + export function getModeForFileReference(ref: FileReference | string, containingFileMode: SourceFile["impliedNodeFormat"]): ModuleKind.CommonJS | ModuleKind.ESNext | undefined; + /** + * Calculates the final resolution mode for an import at some index within a file's imports list. This is generally the explicitly + * defined mode of the import if provided, or, if not, the mode of the containing file (with some exceptions: import=require is always commonjs, dynamic import is always esm). + * If you have an actual import node, prefer using getModeForUsageLocation on the reference string node. + * @param file File to fetch the resolution mode within + * @param index Index into the file's complete resolution list to get the resolution of - this is a concatenation of the file's imports and module augmentations + */ + export function getModeForResolutionAtIndex(file: SourceFile, index: number): ModuleKind.CommonJS | ModuleKind.ESNext | undefined; + /** + * Calculates the final resolution mode for a given module reference node. This is generally the explicitly provided resolution mode, if + * one exists, or the mode of the containing source file. (Excepting import=require, which is always commonjs, and dynamic import, which is always esm). + * Notably, this function always returns `undefined` if the containing file has an `undefined` `impliedNodeFormat` - this field is only set when + * `moduleResolution` is `node16`+. + * @param file The file the import or import-like reference is contained within + * @param usage The module reference string + * @returns The final resolution mode of the import + */ + export function getModeForUsageLocation(file: { + impliedNodeFormat?: SourceFile["impliedNodeFormat"]; + }, usage: StringLiteralLike): ModuleKind.CommonJS | ModuleKind.ESNext | undefined; export function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): readonly Diagnostic[]; /** * A function for determining if a given file is esm or cjs format, assuming modern node module resolution rules, as configured by the @@ -5357,6 +5421,10 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile?: SourceFile): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: SourceFile["impliedNodeFormat"] | undefined): (ResolvedTypeReferenceDirective | undefined)[]; + /** + * Returns the module resolution cache used by a provided `resolveModuleNames` implementation so that any non-name module resolution operations (eg, package.json lookup) can reuse it + */ + getModuleResolutionCache?(): ModuleResolutionCache | undefined; } interface WatchCompilerHost extends ProgramHost, WatchHost { /** Instead of using output d.ts file from project reference, use its source file */ @@ -5871,6 +5939,8 @@ declare namespace ts { getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; + getRenameInfo(fileName: string, position: number, preferences: UserPreferences): RenameInfo; + /** @deprecated Use the signature with `UserPreferences` instead. */ getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo; findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): readonly RenameLocation[] | undefined; getSmartSelectionRange(fileName: string, position: number): SelectionRange; @@ -6250,6 +6320,7 @@ declare namespace ts { Insert = "insert", Remove = "remove" } + /** @deprecated - consider using EditorSettings instead */ interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -6267,6 +6338,7 @@ declare namespace ts { indentStyle?: IndentStyle; trimTrailingWhitespace?: boolean; } + /** @deprecated - consider using FormatCodeSettings instead */ interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; InsertSpaceAfterSemicolonInForStatements: boolean; @@ -6392,6 +6464,9 @@ declare namespace ts { canRename: false; localizedErrorMessage: string; } + /** + * @deprecated Use `UserPreferences` instead. + */ interface RenameInfoOptions { readonly allowRenameOfImportPath?: boolean; } @@ -6829,8 +6904,8 @@ declare namespace ts { * @param version Current version of the file. Only used if the file was not found * in the registry and a new one was created. */ - acquireDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; - acquireDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + acquireDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; + acquireDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; /** * Request an updated version of an already existing SourceFile with a given fileName * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile @@ -6846,8 +6921,8 @@ declare namespace ts { * @param scriptSnapshot Text of the file. * @param version Current version of the file. */ - updateDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; - updateDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; + updateDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; + updateDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey; /** * Informs the DocumentRegistry that a file is not needed any longer. @@ -6857,9 +6932,10 @@ declare namespace ts { * * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file + * @param scriptKind The script kind of the file to be released */ - /**@deprecated pass scriptKind for correctness */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /**@deprecated pass scriptKind and impliedNodeFormat for correctness */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind?: ScriptKind): void; /** * Informs the DocumentRegistry that a file is not needed any longer. * @@ -6869,12 +6945,13 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file * @param scriptKind The script kind of the file to be released + * @param impliedNodeFormat The implied source file format of the file to be released */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind, impliedNodeFormat: SourceFile["impliedNodeFormat"]): void; /** - * @deprecated pass scriptKind for correctness */ - releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; - releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; + * @deprecated pass scriptKind for and impliedNodeFormat correctness */ + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind?: ScriptKind): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind, impliedNodeFormat: SourceFile["impliedNodeFormat"]): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { @@ -6983,33 +7060,69 @@ declare namespace ts { (node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; }; /** @deprecated Use `factory.createParameterDeclaration` or the factory supplied by your transformation context instead. */ - const createParameter: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined) => ParameterDeclaration; + const createParameter: { + (modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined): ParameterDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken | undefined, type?: TypeNode | undefined, initializer?: Expression | undefined): ParameterDeclaration; + }; /** @deprecated Use `factory.updateParameterDeclaration` or the factory supplied by your transformation context instead. */ - const updateParameter: (node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) => ParameterDeclaration; + const updateParameter: { + (node: ParameterDeclaration, modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + (node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + }; /** @deprecated Use `factory.createDecorator` or the factory supplied by your transformation context instead. */ const createDecorator: (expression: Expression) => Decorator; /** @deprecated Use `factory.updateDecorator` or the factory supplied by your transformation context instead. */ const updateDecorator: (node: Decorator, expression: Expression) => Decorator; /** @deprecated Use `factory.createPropertyDeclaration` or the factory supplied by your transformation context instead. */ - const createProperty: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) => PropertyDeclaration; + const createProperty: { + (modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + }; /** @deprecated Use `factory.updatePropertyDeclaration` or the factory supplied by your transformation context instead. */ - const updateProperty: (node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) => PropertyDeclaration; + const updateProperty: { + (node: PropertyDeclaration, modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + (node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + }; /** @deprecated Use `factory.createMethodDeclaration` or the factory supplied by your transformation context instead. */ - const createMethod: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => MethodDeclaration; + const createMethod: { + (modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + }; /** @deprecated Use `factory.updateMethodDeclaration` or the factory supplied by your transformation context instead. */ - const updateMethod: (node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => MethodDeclaration; + const updateMethod: { + (node: MethodDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + (node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + }; /** @deprecated Use `factory.createConstructorDeclaration` or the factory supplied by your transformation context instead. */ - const createConstructor: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined) => ConstructorDeclaration; + const createConstructor: { + (modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + }; /** @deprecated Use `factory.updateConstructorDeclaration` or the factory supplied by your transformation context instead. */ - const updateConstructor: (node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined) => ConstructorDeclaration; + const updateConstructor: { + (node: ConstructorDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + (node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + }; /** @deprecated Use `factory.createGetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const createGetAccessor: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => GetAccessorDeclaration; + const createGetAccessor: { + (modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + }; /** @deprecated Use `factory.updateGetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const updateGetAccessor: (node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => GetAccessorDeclaration; + const updateGetAccessor: { + (node: GetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + (node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + }; /** @deprecated Use `factory.createSetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const createSetAccessor: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined) => SetAccessorDeclaration; + const createSetAccessor: { + (modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + }; /** @deprecated Use `factory.updateSetAccessorDeclaration` or the factory supplied by your transformation context instead. */ - const updateSetAccessor: (node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined) => SetAccessorDeclaration; + const updateSetAccessor: { + (node: SetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + (node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + }; /** @deprecated Use `factory.createCallSignature` or the factory supplied by your transformation context instead. */ const createCallSignature: (typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined) => CallSignatureDeclaration; /** @deprecated Use `factory.updateCallSignature` or the factory supplied by your transformation context instead. */ @@ -7019,7 +7132,10 @@ declare namespace ts { /** @deprecated Use `factory.updateConstructSignature` or the factory supplied by your transformation context instead. */ const updateConstructSignature: (node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) => ConstructSignatureDeclaration; /** @deprecated Use `factory.updateIndexSignature` or the factory supplied by your transformation context instead. */ - const updateIndexSignature: (node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode) => IndexSignatureDeclaration; + const updateIndexSignature: { + (node: IndexSignatureDeclaration, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + (node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + }; /** @deprecated Use `factory.createKeywordTypeNode` or the factory supplied by your transformation context instead. */ const createKeywordTypeNode: (kind: TKind) => KeywordTypeNode; /** @deprecated Use `factory.createTypePredicateNode` or the factory supplied by your transformation context instead. */ @@ -7080,13 +7196,14 @@ declare namespace ts { const updateInferTypeNode: (node: InferTypeNode, typeParameter: TypeParameterDeclaration) => InferTypeNode; /** @deprecated Use `factory.createImportTypeNode` or the factory supplied by your transformation context instead. */ const createImportTypeNode: { - (argument: TypeNode, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; (argument: TypeNode, assertions?: ImportTypeAssertionContainer | undefined, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; + (argument: TypeNode, assertions?: ImportTypeAssertionContainer | undefined, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; + (argument: TypeNode, qualifier?: EntityName | undefined, typeArguments?: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; }; /** @deprecated Use `factory.updateImportTypeNode` or the factory supplied by your transformation context instead. */ const updateImportTypeNode: { - (node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; (node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; + (node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean | undefined): ImportTypeNode; }; /** @deprecated Use `factory.createParenthesizedType` or the factory supplied by your transformation context instead. */ const createParenthesizedType: (type: TypeNode) => ParenthesizedTypeNode; @@ -7331,29 +7448,65 @@ declare namespace ts { /** @deprecated Use `factory.updateVariableDeclarationList` or the factory supplied by your transformation context instead. */ const updateVariableDeclarationList: (node: VariableDeclarationList, declarations: readonly VariableDeclaration[]) => VariableDeclarationList; /** @deprecated Use `factory.createFunctionDeclaration` or the factory supplied by your transformation context instead. */ - const createFunctionDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => FunctionDeclaration; + const createFunctionDeclaration: { + (modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + }; /** @deprecated Use `factory.updateFunctionDeclaration` or the factory supplied by your transformation context instead. */ - const updateFunctionDeclaration: (node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) => FunctionDeclaration; + const updateFunctionDeclaration: { + (node: FunctionDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + (node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + }; /** @deprecated Use `factory.createClassDeclaration` or the factory supplied by your transformation context instead. */ - const createClassDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]) => ClassDeclaration; + const createClassDeclaration: { + (modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + }; /** @deprecated Use `factory.updateClassDeclaration` or the factory supplied by your transformation context instead. */ - const updateClassDeclaration: (node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]) => ClassDeclaration; + const updateClassDeclaration: { + (node: ClassDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + (node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + }; /** @deprecated Use `factory.createInterfaceDeclaration` or the factory supplied by your transformation context instead. */ - const createInterfaceDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]) => InterfaceDeclaration; + const createInterfaceDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + }; /** @deprecated Use `factory.updateInterfaceDeclaration` or the factory supplied by your transformation context instead. */ - const updateInterfaceDeclaration: (node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]) => InterfaceDeclaration; + const updateInterfaceDeclaration: { + (node: InterfaceDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + (node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + }; /** @deprecated Use `factory.createTypeAliasDeclaration` or the factory supplied by your transformation context instead. */ - const createTypeAliasDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode) => TypeAliasDeclaration; + const createTypeAliasDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + }; /** @deprecated Use `factory.updateTypeAliasDeclaration` or the factory supplied by your transformation context instead. */ - const updateTypeAliasDeclaration: (node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode) => TypeAliasDeclaration; + const updateTypeAliasDeclaration: { + (node: TypeAliasDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + (node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + }; /** @deprecated Use `factory.createEnumDeclaration` or the factory supplied by your transformation context instead. */ - const createEnumDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]) => EnumDeclaration; + const createEnumDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + }; /** @deprecated Use `factory.updateEnumDeclaration` or the factory supplied by your transformation context instead. */ - const updateEnumDeclaration: (node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]) => EnumDeclaration; + const updateEnumDeclaration: { + (node: EnumDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + (node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + }; /** @deprecated Use `factory.createModuleDeclaration` or the factory supplied by your transformation context instead. */ - const createModuleDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags | undefined) => ModuleDeclaration; + const createModuleDeclaration: { + (modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags | undefined): ModuleDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags | undefined): ModuleDeclaration; + }; /** @deprecated Use `factory.updateModuleDeclaration` or the factory supplied by your transformation context instead. */ - const updateModuleDeclaration: (node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined) => ModuleDeclaration; + const updateModuleDeclaration: { + (node: ModuleDeclaration, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + (node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + }; /** @deprecated Use `factory.createModuleBlock` or the factory supplied by your transformation context instead. */ const createModuleBlock: (statements: readonly Statement[]) => ModuleBlock; /** @deprecated Use `factory.updateModuleBlock` or the factory supplied by your transformation context instead. */ @@ -7367,13 +7520,25 @@ declare namespace ts { /** @deprecated Use `factory.updateNamespaceExportDeclaration` or the factory supplied by your transformation context instead. */ const updateNamespaceExportDeclaration: (node: NamespaceExportDeclaration, name: Identifier) => NamespaceExportDeclaration; /** @deprecated Use `factory.createImportEqualsDeclaration` or the factory supplied by your transformation context instead. */ - const createImportEqualsDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference) => ImportEqualsDeclaration; + const createImportEqualsDeclaration: { + (modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + }; /** @deprecated Use `factory.updateImportEqualsDeclaration` or the factory supplied by your transformation context instead. */ - const updateImportEqualsDeclaration: (node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference) => ImportEqualsDeclaration; + const updateImportEqualsDeclaration: { + (node: ImportEqualsDeclaration, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + (node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + }; /** @deprecated Use `factory.createImportDeclaration` or the factory supplied by your transformation context instead. */ - const createImportDeclaration: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause | undefined) => ImportDeclaration; + const createImportDeclaration: { + (modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause | undefined): ImportDeclaration; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause | undefined): ImportDeclaration; + }; /** @deprecated Use `factory.updateImportDeclaration` or the factory supplied by your transformation context instead. */ - const updateImportDeclaration: (node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined) => ImportDeclaration; + const updateImportDeclaration: { + (node: ImportDeclaration, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + (node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + }; /** @deprecated Use `factory.createNamespaceImport` or the factory supplied by your transformation context instead. */ const createNamespaceImport: (name: Identifier) => NamespaceImport; /** @deprecated Use `factory.updateNamespaceImport` or the factory supplied by your transformation context instead. */ @@ -7387,9 +7552,15 @@ declare namespace ts { /** @deprecated Use `factory.updateImportSpecifier` or the factory supplied by your transformation context instead. */ const updateImportSpecifier: (node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) => ImportSpecifier; /** @deprecated Use `factory.createExportAssignment` or the factory supplied by your transformation context instead. */ - const createExportAssignment: (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression) => ExportAssignment; + const createExportAssignment: { + (modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + (decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + }; /** @deprecated Use `factory.updateExportAssignment` or the factory supplied by your transformation context instead. */ - const updateExportAssignment: (node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression) => ExportAssignment; + const updateExportAssignment: { + (node: ExportAssignment, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + (node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + }; /** @deprecated Use `factory.createNamedExports` or the factory supplied by your transformation context instead. */ const createNamedExports: (elements: readonly ExportSpecifier[]) => NamedExports; /** @deprecated Use `factory.updateNamedExports` or the factory supplied by your transformation context instead. */ @@ -7479,9 +7650,9 @@ declare namespace ts { /** @deprecated Use `factory.updateJsxFragment` or the factory supplied by your transformation context instead. */ const updateJsxFragment: (node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment) => JsxFragment; /** @deprecated Use `factory.createJsxAttribute` or the factory supplied by your transformation context instead. */ - const createJsxAttribute: (name: Identifier, initializer: StringLiteral | JsxExpression | undefined) => JsxAttribute; + const createJsxAttribute: (name: Identifier, initializer: JsxAttributeValue | undefined) => JsxAttribute; /** @deprecated Use `factory.updateJsxAttribute` or the factory supplied by your transformation context instead. */ - const updateJsxAttribute: (node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression | undefined) => JsxAttribute; + const updateJsxAttribute: (node: JsxAttribute, name: Identifier, initializer: JsxAttributeValue | undefined) => JsxAttribute; /** @deprecated Use `factory.createJsxAttributes` or the factory supplied by your transformation context instead. */ const createJsxAttributes: (properties: readonly JsxAttributeLike[]) => JsxAttributes; /** @deprecated Use `factory.updateJsxAttributes` or the factory supplied by your transformation context instead. */ @@ -7693,8 +7864,12 @@ declare namespace ts { * @deprecated Use an appropriate `factory.update...` method instead, use `setCommentRange` or `setSourceMapRange`, and avoid setting `parent`. */ const getMutableClone: (node: T) => T; +} +declare namespace ts { /** @deprecated Use `isTypeAssertionExpression` instead. */ const isTypeAssertion: (node: Node) => node is TypeAssertion; +} +declare namespace ts { /** * @deprecated Use `ts.ReadonlyESMap` instead. */ @@ -7705,8 +7880,237 @@ declare namespace ts { */ interface Map extends ESMap { } +} +declare namespace ts { /** * @deprecated Use `isMemberName` instead. */ const isIdentifierOrPrivateIdentifier: (node: Node) => node is MemberName; } +declare namespace ts { + interface NodeFactory { + /** @deprecated Use the overload that accepts 'modifiers' */ + createConstructorTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; + /** @deprecated Use the overload that accepts 'modifiers' */ + updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; + } +} +declare namespace ts { + interface NodeFactory { + createImportTypeNode(argument: TypeNode, assertions?: ImportTypeAssertionContainer, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; + /** @deprecated Use the overload that accepts 'assertions' */ + createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; + /** @deprecated Use the overload that accepts 'assertions' */ + updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; + } +} +declare namespace ts { + interface NodeFactory { + /** @deprecated Use the overload that accepts 'modifiers' */ + createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; + /** @deprecated Use the overload that accepts 'modifiers' */ + updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + } +} +declare namespace ts { + interface Node { + /** + * @deprecated `decorators` has been removed from `Node` and merged with `modifiers` on the `Node` subtypes that support them. + * Use `ts.canHaveDecorators()` to test whether a `Node` can have decorators. + * Use `ts.getDecorators()` to get the decorators of a `Node`. + * + * For example: + * ```ts + * const decorators = ts.canHaveDecorators(node) ? ts.getDecorators(node) : undefined; + * ``` + */ + readonly decorators?: undefined; + /** + * @deprecated `modifiers` has been removed from `Node` and moved to the `Node` subtypes that support them. + * Use `ts.canHaveModifiers()` to test whether a `Node` can have modifiers. + * Use `ts.getModifiers()` to get the modifiers of a `Node`. + * + * For example: + * ```ts + * const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined; + * ``` + */ + readonly modifiers?: NodeArray | undefined; + } + interface PropertySignature { + /** @deprecated A property signature cannot have an initializer */ + readonly initializer?: Expression | undefined; + } + interface PropertyAssignment { + /** @deprecated A property assignment cannot have a question token */ + readonly questionToken?: QuestionToken | undefined; + /** @deprecated A property assignment cannot have an exclamation token */ + readonly exclamationToken?: ExclamationToken | undefined; + } + interface ShorthandPropertyAssignment { + /** @deprecated A shorthand property assignment cannot have modifiers */ + readonly modifiers?: NodeArray | undefined; + /** @deprecated A shorthand property assignment cannot have a question token */ + readonly questionToken?: QuestionToken | undefined; + /** @deprecated A shorthand property assignment cannot have an exclamation token */ + readonly exclamationToken?: ExclamationToken | undefined; + } + interface FunctionTypeNode { + /** @deprecated A function type cannot have modifiers */ + readonly modifiers?: NodeArray | undefined; + } + interface NodeFactory { + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createParameterDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateParameterDeclaration(node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createPropertyDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updatePropertyDeclaration(node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createMethodDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateMethodDeclaration(node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + /** + * @deprecated This node does not support Decorators. Callers should use an overload that does not accept a `decorators` parameter. + */ + createConstructorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + /** + * @deprecated This node does not support Decorators. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateConstructorDeclaration(node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createGetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateGetAccessorDeclaration(node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createSetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateSetAccessorDeclaration(node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createIndexSignature(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + /** + * @deprecated Decorators and modifiers are no longer supported for this function. Callers should use an overload that does not accept the `decorators` and `modifiers` parameters. + */ + updateIndexSignature(node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; + /** + * @deprecated Decorators and modifiers are no longer supported for this function. Callers should use an overload that does not accept the `decorators` and `modifiers` parameters. + */ + createClassStaticBlockDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, body: Block): ClassStaticBlockDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createClassExpression(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassExpression(node: ClassExpression, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createFunctionDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateFunctionDeclaration(node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createClassDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassDeclaration(node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createInterfaceDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createTypeAliasDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createEnumDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateEnumDeclaration(node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createModuleDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateModuleDeclaration(node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createImportEqualsDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createImportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateImportDeclaration(node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createExportAssignment(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateExportAssignment(node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createExportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateExportDeclaration(node: ExportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; + } +} diff --git a/tsserver/typescriptServices.js b/tsserver/typescriptServices.js index 0d8b6b5f..9e45164b 100644 --- a/tsserver/typescriptServices.js +++ b/tsserver/typescriptServices.js @@ -290,11 +290,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.7"; + ts.versionMajorMinor = "4.8"; // 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 = "4.7.2"; + ts.version = "4.8.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -500,8 +500,10 @@ var ts; return true; } ts.every = every; - function find(array, predicate) { - for (var i = 0; i < array.length; i++) { + function find(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { var value = array[i]; if (predicate(value, i)) { return value; @@ -510,8 +512,10 @@ var ts; return undefined; } ts.find = find; - function findLast(array, predicate) { - for (var i = array.length - 1; i >= 0; i--) { + function findLast(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { var value = array[i]; if (predicate(value, i)) { return value; @@ -522,7 +526,9 @@ var ts; ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate, startIndex) { - for (var i = startIndex || 0; i < array.length; i++) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -531,7 +537,9 @@ var ts; } ts.findIndex = findIndex; function findLastIndex(array, predicate, startIndex) { - for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { if (predicate(array[i], i)) { return i; } @@ -1309,7 +1317,7 @@ var ts; * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return array.length === 0 ? undefined : array[0]; + return array === undefined || array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -1321,7 +1329,7 @@ var ts; * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return array.length === 0 ? undefined : array[array.length - 1]; + return array === undefined || array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -1662,6 +1670,43 @@ var ts; return createMultiMap(); } ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; + function createQueue(items) { + var elements = (items === null || items === void 0 ? void 0 : items.slice()) || []; + var headIndex = 0; + function isEmpty() { + return headIndex === elements.length; + } + function enqueue() { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + elements.push.apply(elements, items); + } + function dequeue() { + if (isEmpty()) { + throw new Error("Queue is empty"); + } + var result = elements[headIndex]; + elements[headIndex] = undefined; // Don't keep referencing dequeued item + headIndex++; + // If more than half of the queue is empty, copy the remaining elements to the + // front and shrink the array (unless we'd be saving fewer than 100 slots) + if (headIndex > 100 && headIndex > (elements.length >> 1)) { + var newLength = elements.length - headIndex; + elements.copyWithin(/*target*/ 0, /*start*/ headIndex); + elements.length = newLength; + headIndex = 0; + } + return result; + } + return { + enqueue: enqueue, + dequeue: dequeue, + isEmpty: isEmpty, + }; + } + ts.createQueue = createQueue; /** * Creates a Set with custom equality and hash code functionality. This is useful when you * want to use something looser than object identity - e.g. "has the same span". @@ -1850,6 +1895,10 @@ var ts; /** Does nothing. */ function noop(_) { } ts.noop = noop; + ts.noopPush = { + push: noop, + length: 0 + }; /** Do nothing and return false */ function returnFalse() { return false; @@ -2205,7 +2254,7 @@ var ts; * and 1 insertion/deletion at 3 characters) */ function getSpellingSuggestion(name, candidates, getName) { - var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var maximumLengthDifference = Math.max(2, Math.floor(name.length * 0.34)); var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother. var bestCandidate; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -2432,6 +2481,7 @@ var ts; startsWith(candidate, prefix) && endsWith(candidate, suffix); } + ts.isPatternMatch = isPatternMatch; function and(f, g) { return function (arg) { return f(arg) && g(arg); }; } @@ -2624,6 +2674,7 @@ var ts; var currentAssertionLevel = 0 /* AssertionLevel.None */; Debug.currentLogLevel = LogLevel.Warning; Debug.isDebugging = false; + Debug.enableDeprecationWarnings = true; function getTypeScriptVersion() { return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version)); } @@ -2842,7 +2893,7 @@ var ts; return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; } if (isFlags) { - var result = ""; + var result = []; var remainingFlags = value; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; @@ -2850,12 +2901,12 @@ var ts; break; } if (enumValue !== 0 && enumValue & value) { - result = "".concat(result).concat(result ? "|" : "").concat(enumName); + result.push(enumName); remainingFlags &= ~enumValue; } } if (remainingFlags === 0) { - return result; + return result.join("|"); } } else { @@ -2869,7 +2920,15 @@ var ts; return value.toString(); } Debug.formatEnum = formatEnum; + var enumMemberCache = new ts.Map(); function getEnumMembers(enumObject) { + // Assuming enum objects do not change at runtime, we can cache the enum members list + // to reuse later. This saves us from reconstructing this each and every time we call + // a formatting function (which can be expensive for large enums like SyntaxKind). + var existing = enumMemberCache.get(enumObject); + if (existing) { + return existing; + } var result = []; for (var name in enumObject) { var value = enumObject[name]; @@ -2877,7 +2936,9 @@ var ts; result.push([value, name]); } } - return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + var sorted = ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + enumMemberCache.set(enumObject, sorted); + return sorted; } function formatSyntaxKind(kind) { return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); @@ -2923,6 +2984,22 @@ var ts; return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true); } Debug.formatFlowFlags = formatFlowFlags; + function formatRelationComparisonResult(result) { + return formatEnum(result, ts.RelationComparisonResult, /*isFlags*/ true); + } + Debug.formatRelationComparisonResult = formatRelationComparisonResult; + function formatCheckMode(mode) { + return formatEnum(mode, ts.CheckMode, /*isFlags*/ true); + } + Debug.formatCheckMode = formatCheckMode; + function formatSignatureCheckMode(mode) { + return formatEnum(mode, ts.SignatureCheckMode, /*isFlags*/ true); + } + Debug.formatSignatureCheckMode = formatSignatureCheckMode; + function formatTypeFacts(facts) { + return formatEnum(facts, ts.TypeFacts, /*isFlags*/ true); + } + Debug.formatTypeFacts = formatTypeFacts; var isDebugInfoEnabled = false; var extendedDebugModule; function extendedDebug() { @@ -3221,7 +3298,7 @@ var ts; function createWarningDeprecation(name, errorAfter, since, message) { var hasWrittenDeprecation = false; return function () { - if (!hasWrittenDeprecation) { + if (Debug.enableDeprecationWarnings && !hasWrittenDeprecation) { log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message)); hasWrittenDeprecation = true; } @@ -3240,6 +3317,7 @@ var ts; warn ? createWarningDeprecation(name, errorAfter, since, options.message) : ts.noop; } + Debug.createDeprecation = createDeprecation; function wrapFunction(deprecation, func) { return function () { deprecation(); @@ -3247,10 +3325,53 @@ var ts; }; } function deprecate(func, options) { - var deprecation = createDeprecation(getFunctionName(func), options); + var _a; + var deprecation = createDeprecation((_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : getFunctionName(func), options); return wrapFunction(deprecation, func); } Debug.deprecate = deprecate; + function formatVariance(varianceFlags) { + var variance = varianceFlags & 7 /* VarianceFlags.VarianceMask */; + var result = variance === 0 /* VarianceFlags.Invariant */ ? "in out" : + variance === 3 /* VarianceFlags.Bivariant */ ? "[bivariant]" : + variance === 2 /* VarianceFlags.Contravariant */ ? "in" : + variance === 1 /* VarianceFlags.Covariant */ ? "out" : + variance === 4 /* VarianceFlags.Independent */ ? "[independent]" : ""; + if (varianceFlags & 8 /* VarianceFlags.Unmeasurable */) { + result += " (unmeasurable)"; + } + else if (varianceFlags & 16 /* VarianceFlags.Unreliable */) { + result += " (unreliable)"; + } + return result; + } + Debug.formatVariance = formatVariance; + var DebugTypeMapper = /** @class */ (function () { + function DebugTypeMapper() { + } + DebugTypeMapper.prototype.__debugToString = function () { + var _a; + type(this); + switch (this.kind) { + case 3 /* TypeMapKind.Function */: return ((_a = this.debugInfo) === null || _a === void 0 ? void 0 : _a.call(this)) || "(function mapper)"; + case 0 /* TypeMapKind.Simple */: return "".concat(this.source.__debugTypeToString(), " -> ").concat(this.target.__debugTypeToString()); + case 1 /* TypeMapKind.Array */: return ts.zipWith(this.sources, this.targets || ts.map(this.sources, function () { return "any"; }), function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(typeof t === "string" ? t : t.__debugTypeToString()); }).join(", "); + case 2 /* TypeMapKind.Deferred */: return ts.zipWith(this.sources, this.targets, function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(t().__debugTypeToString()); }).join(", "); + case 5 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: return "m1: ".concat(this.mapper1.__debugToString().split("\n").join("\n "), "\nm2: ").concat(this.mapper2.__debugToString().split("\n").join("\n ")); + default: return assertNever(this); + } + }; + return DebugTypeMapper; + }()); + Debug.DebugTypeMapper = DebugTypeMapper; + function attachDebugPrototypeIfDebug(mapper) { + if (Debug.isDebugging) { + return Object.setPrototypeOf(mapper, DebugTypeMapper.prototype); + } + return mapper; + } + Debug.attachDebugPrototypeIfDebug = attachDebugPrototypeIfDebug; })(Debug = ts.Debug || (ts.Debug = {})); })(ts || (ts = {})); /* @internal */ @@ -3992,9 +4113,9 @@ var ts; eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } tracingEnabled.push = push; - function pop() { + function pop(results) { ts.Debug.assert(eventStack.length > 0); - writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); + writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp(), results); eventStack.length--; } tracingEnabled.pop = pop; @@ -4008,14 +4129,15 @@ var ts; tracingEnabled.popAll = popAll; // sample every 10ms var sampleInterval = 1000 * 10; - function writeStackEvent(index, endTime) { + function writeStackEvent(index, endTime, results) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { + ts.Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`"); writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } // test if [time,endTime) straddles a sampling point else if (sampleInterval - (time % sampleInterval) <= endTime - time) { - writeEvent("X", phase, name, args, "\"dur\":".concat(endTime - time), time); + writeEvent("X", phase, name, __assign(__assign({}, args), { results: results }), "\"dur\":".concat(endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { @@ -4514,6 +4636,7 @@ var ts; SyntaxKind[SyntaxKind["JSDocFunctionType"] = 317] = "JSDocFunctionType"; SyntaxKind[SyntaxKind["JSDocVariadicType"] = 318] = "JSDocVariadicType"; SyntaxKind[SyntaxKind["JSDocNamepathType"] = 319] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; /** @deprecated Use SyntaxKind.JSDoc */ SyntaxKind[SyntaxKind["JSDocComment"] = 320] = "JSDocComment"; SyntaxKind[SyntaxKind["JSDocText"] = 321] = "JSDocText"; @@ -4588,7 +4711,6 @@ var ts; SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 347] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 126] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 160] = "LastContextualKeyword"; - SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4662,6 +4784,7 @@ var ts; ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["In"] = 32768] = "In"; ModifierFlags[ModifierFlags["Out"] = 65536] = "Out"; + ModifierFlags[ModifierFlags["Decorator"] = 131072] = "Decorator"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. @@ -4669,7 +4792,8 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 116958] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 125951] = "All"; + ModifierFlags[ModifierFlags["All"] = 257023] = "All"; + ModifierFlags[ModifierFlags["Modifier"] = 125951] = "Modifier"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4854,6 +4978,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + NodeBuilderFlags[NodeBuilderFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; @@ -4894,6 +5019,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + TypeFormatFlags[TypeFormatFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -4905,7 +5031,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 848330091] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -5294,6 +5420,11 @@ var ts; // Flags that require TypeFlags.Union /* @internal */ ObjectFlags[ObjectFlags["ContainsIntersections"] = 16777216] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnionComputed"] = 33554432] = "IsUnknownLikeUnionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnion"] = 67108864] = "IsUnknownLikeUnion"; + /* @internal */ // Flags that require TypeFlags.Intersection /* @internal */ ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 16777216] = "IsNeverIntersectionComputed"; @@ -5379,9 +5510,10 @@ var ts; (function (TypeMapKind) { TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple"; TypeMapKind[TypeMapKind["Array"] = 1] = "Array"; - TypeMapKind[TypeMapKind["Function"] = 2] = "Function"; - TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite"; - TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged"; + TypeMapKind[TypeMapKind["Deferred"] = 2] = "Deferred"; + TypeMapKind[TypeMapKind["Function"] = 3] = "Function"; + TypeMapKind[TypeMapKind["Composite"] = 4] = "Composite"; + TypeMapKind[TypeMapKind["Merged"] = 5] = "Merged"; })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {})); var InferencePriority; (function (InferencePriority) { @@ -5760,25 +5892,24 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 4096] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; - TransformFlags[TransformFlags["ContainsLexicalSuper"] = 33554432] = "ContainsLexicalSuper"; - TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 67108864] = "ContainsUpdateExpressionForIdentifier"; - // Please leave this as 1 << 29. - // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. - // It is a good reminder of how much room we have left - TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 8192] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 32768] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 65536] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 131072] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 262144] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 524288] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 1048576] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 2097152] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 4194304] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 8388608] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 16777216] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsDecorators"] = 33554432] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 67108864] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsLexicalSuper"] = 134217728] = "ContainsLexicalSuper"; + TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 268435456] = "ContainsUpdateExpressionForIdentifier"; + TransformFlags[TransformFlags["ContainsPrivateIdentifierInExpression"] = 536870912] = "ContainsPrivateIdentifierInExpression"; + TransformFlags[TransformFlags["HasComputedFlags"] = -2147483648] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; @@ -5797,27 +5928,27 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 591310848] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 591306752] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 574529536] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 570433536] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 589443072] = "ModuleExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = -2147483648] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = -2147483648] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = -2147483648] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = -2072174592] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = -1937940480] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = -1937948672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = -2005057536] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = -2013249536] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = -2147344384] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = -1941676032] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; - TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 33562624] = "ContainsLexicalThisOrSuper"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = -2147278848] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = -2147450880] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = -2146893824] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = -2147483648] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = -2147418112] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = -2147450880] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 134234112] = "ContainsLexicalThisOrSuper"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 33562624] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 134234112] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -5990,7 +6121,7 @@ var ts; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["Modifiers"] = 2359808] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; @@ -6385,7 +6516,7 @@ var ts; }; } function createDirectoryWatcher(dirName, dirPath, fallbackOptions) { - var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName) { + var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName, modifiedTime) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" if (!ts.isString(relativeFileName)) return; @@ -6395,7 +6526,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); + fileCallback(fileName, FileWatcherEventKind.Changed, modifiedTime); } } }, @@ -6449,7 +6580,7 @@ var ts; } else { cache.set(path, { - watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options), + watcher: watchFile(fileName, function (fileName, eventKind, modifiedTime) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind, modifiedTime); }); }, pollingInterval, options), refCount: 1 }); } @@ -6477,7 +6608,8 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + // Pass modified times so tsc --build can use it + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime), modifiedTime); return true; } return false; @@ -6512,7 +6644,7 @@ var ts; */ /*@internal*/ function createDirectoryWatcherSupportingRecursive(_a) { - var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, directoryExists = _a.directoryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, fileSystemEntryExists = _a.fileSystemEntryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; var cache = new ts.Map(); var callbackCache = ts.createMultiMap(); var cacheToUpdateChildWatches = new ts.Map(); @@ -6612,7 +6744,7 @@ var ts; function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) { // Iterate through existing children and update the watches if needed var parentWatcher = cache.get(dirPath); - if (parentWatcher && directoryExists(dirName)) { + if (parentWatcher && fileSystemEntryExists(dirName, 1 /* FileSystemEntryKind.Directory */)) { // Schedule the update and postpone invoke for callbacks scheduleUpdateChildWatches(dirName, dirPath, fileName, options); return; @@ -6685,7 +6817,7 @@ var ts; if (!parentWatcher) return false; var newChildWatches; - var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { + var hasChanges = ts.enumerateInsertsAndDeletes(fileSystemEntryExists(parentDir, 1 /* FileSystemEntryKind.Directory */) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch @@ -6728,17 +6860,19 @@ var ts; })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {})); /*@internal*/ function createFileWatcherCallback(callback) { - return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + return function (_fileName, eventKind, modifiedTime) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", "", modifiedTime); }; } ts.createFileWatcherCallback = createFileWatcherCallback; - function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) { - return function (eventName) { + function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime) { + return function (eventName, _relativeFileName, modifiedTime) { if (eventName === "rename") { - callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + // Check time stamps rather than file system entry checks + modifiedTime || (modifiedTime = getModifiedTime(fileName) || ts.missingFileModifiedTime); + callback(fileName, modifiedTime !== ts.missingFileModifiedTime ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted, modifiedTime); } else { // Change - callback(fileName, FileWatcherEventKind.Changed); + callback(fileName, FileWatcherEventKind.Changed, modifiedTime); } }; } @@ -6762,11 +6896,12 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; + var pollingWatchFile = _a.pollingWatchFile, 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 dynamicPollingWatchFile; var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; + var hitSystemWatcherLimit = false; return { watchFile: watchFile, watchDirectory: watchDirectory @@ -6784,7 +6919,7 @@ var ts; case ts.WatchFileKind.FixedChunkSizePolling: return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: - return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), + return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); case ts.WatchFileKind.UseFsEventsOnParentDirectory: if (!nonPollingWatchFile) { @@ -6845,7 +6980,7 @@ var ts; hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - directoryExists: directoryExists, + fileSystemEntryExists: fileSystemEntryExists, getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories, watchDirectory: nonRecursiveWatchDirectory, realpath: realpath, @@ -6896,6 +7031,124 @@ var ts; }; } } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { + var lastDirectoryPartWithDirectorySeparator; + var lastDirectoryPart; + if (inodeWatching) { + lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substring(fileOrDirectory.lastIndexOf(ts.directorySeparator)); + lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); + } + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + if (watcher) { + watcher.close(); + watcher = undefined; + } + } + }; + function updateWatcher(createWatcher) { + // If watcher is not closed, update it + if (watcher) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + if (hitSystemWatcherLimit) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + try { + var presentWatcher = fsWatchWorker(fileOrDirectory, recursive, inodeWatching ? + callbackChangingToMissingFileSystemEntry : + callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { + callback("rename", ""); + updateWatcher(watchMissingFileSystemEntry); + }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + function callbackChangingToMissingFileSystemEntry(event, relativeName) { + // In some scenarios, file save operation fires event with fileName.ext~ instead of fileName.ext + // To ensure we see the file going missing and coming back up (file delete and then recreated) + // and watches being updated correctly we are calling back with fileName.ext as well as fileName.ext~ + // The worst is we have fired event that was not needed but we wont miss any changes + // especially in cases where file goes missing and watches wrong inode + var originalRelativeName; + if (relativeName && ts.endsWith(relativeName, "~")) { + originalRelativeName = relativeName; + relativeName = relativeName.slice(0, relativeName.length - 1); + } + // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations + // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path + if (event === "rename" && + (!relativeName || + relativeName === lastDirectoryPart || + ts.endsWith(relativeName, lastDirectoryPartWithDirectorySeparator))) { + var modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime; + if (originalRelativeName) + callback(event, originalRelativeName, modifiedTime); + callback(event, relativeName, modifiedTime); + if (inodeWatching) { + // If this was rename event, inode has changed means we need to update watcher + updateWatcher(modifiedTime === ts.missingFileModifiedTime ? watchMissingFileSystemEntry : watchPresentFileSystemEntry); + } + else if (modifiedTime === ts.missingFileModifiedTime) { + updateWatcher(watchMissingFileSystemEntry); + } + } + else { + if (originalRelativeName) + callback(event, originalRelativeName); + callback(event, relativeName); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return watchFile(fileOrDirectory, function (_fileName, eventKind, modifiedTime) { + if (eventKind === FileWatcherEventKind.Created) { + modifiedTime || (modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime); + if (modifiedTime !== ts.missingFileModifiedTime) { + callback("rename", "", modifiedTime); + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + updateWatcher(watchPresentFileSystemEntry); + } + } + }, fallbackPollingInterval, fallbackOptions); + } + } } ts.createSystemWatchFunctions = createSystemWatchFunctions; /** @@ -6933,7 +7186,6 @@ var ts; // not actually work. var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { - var _a; var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/; var _fs = require("fs"); var _path = require("path"); @@ -6943,41 +7195,41 @@ var ts; try { _crypto = require("crypto"); } - catch (_b) { + catch (_a) { _crypto = undefined; } var activeSession; var profilePath = "./profile.cpuprofile"; - var hitSystemWatcherLimit = false; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; + var fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); - var _c = createSystemWatchFunctions({ + var _b = createSystemWatchFunctions({ pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames), getModifiedTime: getModifiedTime, setTimeout: setTimeout, clearTimeout: clearTimeout, - fsWatch: fsWatch, + fsWatchWorker: fsWatchWorker, useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - fileExists: fileExists, + fileSystemEntryExists: fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch, - directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, realpath: realpath, 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); }, - }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; + inodeWatching: isLinuxOrMacOs, + sysLog: sysLog, + }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -7226,110 +7478,14 @@ var ts; // File changed eventKind = FileWatcherEventKind.Changed; } - callback(fileName, eventKind); + callback(fileName, eventKind, curr.mtime); } } - function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { - var options; - var lastDirectoryPartWithDirectorySeparator; - var lastDirectoryPart; - if (isLinuxOrMacOs) { - lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator)); - lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); - } - /** Watcher for the file system entry depending on whether it is missing or present */ - var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? - watchMissingFileSystemEntry() : - watchPresentFileSystemEntry(); - return { - close: function () { - // Close the watcher (either existing file system entry watcher or missing file system entry watcher) - watcher.close(); - watcher = undefined; - } - }; - /** - * Invoke the callback with rename and update the watcher if not closed - * @param createWatcher - */ - function invokeCallbackAndUpdateWatcher(createWatcher) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); - // Call the callback for current directory - callback("rename", ""); - // If watcher is not closed, update it - if (watcher) { - watcher.close(); - watcher = createWatcher(); - } - } - /** - * Watch the file or directory that is currently present - * and when the watched file or directory is deleted, switch to missing file system entry watcher - */ - function watchPresentFileSystemEntry() { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows - // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) - if (options === undefined) { - if (fsSupportsRecursiveFsWatch) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - } - if (hitSystemWatcherLimit) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - try { - var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ? - callbackChangingToMissingFileSystemEntry : - callback); - // Watch the missing file or directory or error - presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); - return presentWatcher; - } - catch (e) { - // Catch the exception and use polling instead - // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - // so instead of throwing error, use fs.watchFile - hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - } - function callbackChangingToMissingFileSystemEntry(event, relativeName) { - // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations - // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path - return event === "rename" && - (!relativeName || - relativeName === lastDirectoryPart || - (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && - !fileSystemEntryExists(fileOrDirectory, entryKind) ? - invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : - callback(event, relativeName); - } - /** - * Watch the file or directory using fs.watchFile since fs.watch threw exception - * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - */ - function watchPresentFileSystemEntryWithFsWatchFile() { - return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); - } - /** - * Watch the file or directory that is missing - * and switch to existing file or directory when the missing filesystem entry is created - */ - function watchMissingFileSystemEntry() { - return watchFile(fileOrDirectory, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { - // Call the callback for current file or directory - // For now it could be callback for the inner directory creation, - // but just return current directory, better than current no-op - invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); - } - }, fallbackPollingInterval, fallbackOptions); - } + function fsWatchWorker(fileOrDirectory, recursive, callback) { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + return _fs.watch(fileOrDirectory, fsSupportsRecursiveFsWatch ? + { persistent: true, recursive: !!recursive } : { persistent: true }, callback); } function readFileWorker(fileName, _encoding) { var buffer; @@ -7466,9 +7622,12 @@ var ts; function getDirectories(path) { return getAccessibleFileSystemEntries(path).directories.slice(); } + function fsRealPathHandlingLongPath(path) { + return path.length < 260 ? _fs.realpathSync.native(path) : _fs.realpathSync(path); + } function realpath(path) { try { - return realpathSync(path); + return fsRealpath(path); } catch (_a) { return path; @@ -7476,12 +7635,19 @@ var ts; } function getModifiedTime(path) { var _a; + // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve + // the CPU time performance. + var originalStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; try { return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime; } catch (e) { return undefined; } + finally { + Error.stackTraceLimit = originalStackTraceLimit; + } } function setModifiedTime(path, time) { try { @@ -8336,6 +8502,7 @@ var ts; String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + or_JSX_element_expected: diag(1145, ts.DiagnosticCategory.Error, "or_JSX_element_expected_1145", "'{' or JSX element expected."), Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), @@ -8389,6 +8556,7 @@ var ts; Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), _0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module: diag(1208, ts.DiagnosticCategory.Error, "_0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_imp_1208", "'{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module."), + Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0: diag(1209, ts.DiagnosticCategory.Error, "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209", "Invalid optional chain from new expression. Did you mean to call '{0}()'?"), Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode: diag(1210, ts.DiagnosticCategory.Error, "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210", "Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of '{0}'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode."), A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), @@ -8481,6 +8649,7 @@ var ts; infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Class_constructor_may_not_be_an_accessor: diag(1341, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_an_accessor_1341", "Class constructor may not be an accessor."), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), @@ -8499,6 +8668,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Class_constructor_may_not_be_a_generator: diag(1360, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_a_generator_1360", "Class constructor may not be a generator."), _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."), _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), @@ -8583,18 +8753,30 @@ var ts; Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, ts.DiagnosticCategory.Message, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."), Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments: diag(1450, ts.DiagnosticCategory.Message, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional assertion as arguments"), Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"), - Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "Resolution modes are only supported when `moduleResolution` is `node16` or `nodenext`."), + resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "'resolution-mode' assertions are only supported when `moduleResolution` is `node16` or `nodenext`."), resolution_mode_should_be_either_require_or_import: diag(1453, ts.DiagnosticCategory.Error, "resolution_mode_should_be_either_require_or_import_1453", "`resolution-mode` should be either `require` or `import`."), resolution_mode_can_only_be_set_for_type_only_imports: diag(1454, ts.DiagnosticCategory.Error, "resolution_mode_can_only_be_set_for_type_only_imports_1454", "`resolution-mode` can only be set for type-only imports."), resolution_mode_is_the_only_valid_key_for_type_import_assertions: diag(1455, ts.DiagnosticCategory.Error, "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455", "`resolution-mode` is the only valid key for type import assertions."), Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require: diag(1456, ts.DiagnosticCategory.Error, "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456", "Type import assertions should have exactly one key - `resolution-mode` - with value `import` or `require`."), + Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk: diag(1457, ts.DiagnosticCategory.Message, "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457", "Matched by default include pattern '**/*'"), + File_is_ECMAScript_module_because_0_has_field_type_with_value_module: diag(1458, ts.DiagnosticCategory.Message, "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458", "File is ECMAScript module because '{0}' has field \"type\" with value \"module\""), + File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module: diag(1459, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459", "File is CommonJS module because '{0}' has field \"type\" whose value is not \"module\""), + File_is_CommonJS_module_because_0_does_not_have_field_type: diag(1460, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_does_not_have_field_type_1460", "File is CommonJS module because '{0}' does not have field \"type\""), + File_is_CommonJS_module_because_package_json_was_not_found: diag(1461, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_package_json_was_not_found_1461", "File is CommonJS module because 'package.json' was not found"), The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."), - Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."), + Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported with 'require'. Use an ECMAScript import instead."), catch_or_finally_expected: diag(1472, ts.DiagnosticCategory.Error, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), An_import_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1473, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473", "An import declaration can only be used at the top level of a module."), An_export_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1474, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474", "An export declaration can only be used at the top level of a module."), Control_what_method_is_used_to_detect_module_format_JS_files: diag(1475, ts.DiagnosticCategory.Message, "Control_what_method_is_used_to_detect_module_format_JS_files_1475", "Control what method is used to detect module-format JS files."), auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules: diag(1476, ts.DiagnosticCategory.Message, "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476", "\"auto\": Treat files with imports, exports, import.meta, jsx (with jsx: react-jsx), or esm format (with module: node16+) as modules."), + An_instantiation_expression_cannot_be_followed_by_a_property_access: diag(1477, ts.DiagnosticCategory.Error, "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477", "An instantiation expression cannot be followed by a property access."), + Identifier_or_string_literal_expected: diag(1478, ts.DiagnosticCategory.Error, "Identifier_or_string_literal_expected_1478", "Identifier or string literal expected."), + The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead: diag(1479, ts.DiagnosticCategory.Error, "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479", "The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import(\"{0}\")' call instead."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module: diag(1480, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480", "To convert this file to an ECMAScript module, change its file extension to '{0}' or create a local package.json file with `{ \"type\": \"module\" }`."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1: diag(1481, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481", "To convert this file to an ECMAScript module, change its file extension to '{0}', or add the field `\"type\": \"module\"` to '{1}'."), + To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0: diag(1482, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482", "To convert this file to an ECMAScript module, add the field `\"type\": \"module\"` to '{0}'."), + To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module: diag(1483, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483", "To convert this file to an ECMAScript module, create a local package.json file with `{ \"type\": \"module\" }`."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8603,8 +8785,11 @@ var ts; Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."), The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."), + This_type_parameter_might_need_an_extends_0_constraint: diag(2208, ts.DiagnosticCategory.Error, "This_type_parameter_might_need_an_extends_0_constraint_2208", "This type parameter might need an `extends {0}` constraint."), The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2209, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209", "The project root is ambiguous, but is required to resolve export map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2210, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210", "The project root is ambiguous, but is required to resolve import map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), + Add_extends_constraint: diag(2211, ts.DiagnosticCategory.Message, "Add_extends_constraint_2211", "Add `extends` constraint."), + Add_extends_constraint_to_all_type_parameters: diag(2212, ts.DiagnosticCategory.Message, "Add_extends_constraint_to_all_type_parameters_2212", "Add `extends` constraint to all type parameters"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -8805,6 +8990,7 @@ var ts; Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + A_tuple_type_cannot_be_indexed_with_a_negative_value: diag(2514, ts.DiagnosticCategory.Error, "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514", "A tuple type cannot be indexed with a negative value."), Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), @@ -9087,6 +9273,12 @@ var ts; Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls: diag(2836, ts.DiagnosticCategory.Error, "Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls_2836", "Import assertions are not allowed on statements that transpile to commonjs 'require' calls."), Import_assertion_values_must_be_string_literal_expressions: diag(2837, ts.DiagnosticCategory.Error, "Import_assertion_values_must_be_string_literal_expressions_2837", "Import assertion values must be string literal expressions."), All_declarations_of_0_must_have_identical_constraints: diag(2838, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_constraints_2838", "All declarations of '{0}' must have identical constraints."), + This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value: diag(2839, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839", "This condition will always return '{0}' since JavaScript compares objects by reference, not value."), + An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes: diag(2840, ts.DiagnosticCategory.Error, "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840", "An interface cannot extend a primitive type like '{0}'; an interface can only extend named types and classes"), + The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(2841, ts.DiagnosticCategory.Error, "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841", "The type of this expression cannot be named without a 'resolution-mode' assertion, which is an unstable feature. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + _0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation: diag(2842, ts.DiagnosticCategory.Error, "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842", "'{0}' is an unused renaming of '{1}'. Did you intend to use it as a type annotation?"), + We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here: diag(2843, ts.DiagnosticCategory.Error, "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843", "We can only write a type for '{0}' by adding a type for the entire parameter here."), + Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2844, ts.DiagnosticCategory.Error, "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844", "Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -9194,7 +9386,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), - Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "Resolution mode assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "'resolution-mode' assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -9497,8 +9689,8 @@ var ts; Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Referenced_project_0_may_not_disable_emit: diag(6310, ts.DiagnosticCategory.Error, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."), - Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), - Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_1_is_older_than_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350", "Project '{0}' is out of date because output '{1}' is older than input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than output '{2}'"), Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), @@ -9542,6 +9734,8 @@ var ts; Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6396, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6397, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."), + 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"), 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."), @@ -9782,6 +9976,8 @@ var ts; Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, ts.DiagnosticCategory.Error, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."), The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."), + You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder: diag(8035, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035", "You cannot rename elements that are defined in a 'node_modules' folder."), + You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -10052,6 +10248,9 @@ var ts; For_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, ts.DiagnosticCategory.Error, "For_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'For await' loops cannot be used inside a class static block."), Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, ts.DiagnosticCategory.Error, "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."), A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, ts.DiagnosticCategory.Error, "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."), + _0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation: diag(18042, ts.DiagnosticCategory.Error, "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042", "'{0}' is a type and cannot be imported in JavaScript files. Use '{1}' in a JSDoc type annotation."), + Types_cannot_appear_in_export_declarations_in_JavaScript_files: diag(18043, ts.DiagnosticCategory.Error, "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043", "Types cannot appear in export declarations in JavaScript files."), + _0_is_automatically_exported_here: diag(18044, ts.DiagnosticCategory.Message, "_0_is_automatically_exported_here_18044", "'{0}' is automatically exported here."), }; })(ts || (ts = {})); var ts; @@ -12939,6 +13138,18 @@ var ts; } } ts.getAssignedName = getAssignedName; + function getDecorators(node) { + if (ts.hasDecorators(node)) { + return ts.filter(node.modifiers, ts.isDecorator); + } + } + ts.getDecorators = getDecorators; + function getModifiers(node) { + if (ts.hasSyntacticModifier(node, 125951 /* ModifierFlags.Modifier */)) { + return ts.filter(node.modifiers, isModifier); + } + } + ts.getModifiers = getModifiers; function getJSDocParameterTagsWorker(param, noCache) { if (param.name) { if (ts.isIdentifier(param.name)) { @@ -13209,6 +13420,12 @@ var ts; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + * + * This does *not* return type parameters from a jsdoc reference to a generic type, eg + * + * type Id = (x: T) => T + * /** @type {Id} / + * function id(x) { return x } */ function getEffectiveTypeParameterDeclarations(node) { if (ts.isJSDocSignature(node)) { @@ -13221,6 +13438,9 @@ var ts; if (node.typeParameters) { return node.typeParameters; } + if (ts.canHaveIllegalTypeParameters(node) && node.typeParameters) { + return node.typeParameters; + } if (ts.isInJSFile(node)) { var decls = ts.getJSDocTypeParameterDeclarations(node); if (decls.length) { @@ -13397,6 +13617,19 @@ var ts; return isLiteralKind(node.kind); } ts.isLiteralExpression = isLiteralExpression; + /** @internal */ + function isLiteralExpressionOfObject(node) { + switch (node.kind) { + case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 13 /* SyntaxKind.RegularExpressionLiteral */: + case 213 /* SyntaxKind.FunctionExpression */: + case 226 /* SyntaxKind.ClassExpression */: + return true; + } + return false; + } + ts.isLiteralExpressionOfObject = isLiteralExpressionOfObject; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { @@ -13606,6 +13839,10 @@ var ts; } ts.isMethodOrAccessor = isMethodOrAccessor; // Type members + function isModifierLike(node) { + return isModifier(node) || ts.isDecorator(node); + } + ts.isModifierLike = isModifierLike; function isTypeElement(node) { var kind = node.kind; return kind === 175 /* SyntaxKind.ConstructSignature */ @@ -14215,7 +14452,6 @@ var ts; case 254 /* SyntaxKind.VariableDeclaration */: case 164 /* SyntaxKind.Parameter */: case 203 /* SyntaxKind.BindingElement */: - case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: case 296 /* SyntaxKind.PropertyAssignment */: case 299 /* SyntaxKind.EnumMember */: @@ -14267,6 +14503,16 @@ var ts; return node.kind === 324 /* SyntaxKind.JSDocLink */ || node.kind === 325 /* SyntaxKind.JSDocLinkCode */ || node.kind === 326 /* SyntaxKind.JSDocLinkPlain */; } ts.isJSDocLinkLike = isJSDocLinkLike; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; // #endregion })(ts || (ts = {})); /* @internal */ @@ -14747,10 +14993,11 @@ var ts; } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { - if (nodeIsMissing(node) || !node.decorators) { + var lastDecorator = !nodeIsMissing(node) && ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + if (!lastDecorator) { return getTokenPosOfNode(node, sourceFile); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastDecorator.end); } ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { @@ -16136,7 +16383,7 @@ var ts; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { - return node.decorators !== undefined + return hasDecorators(node) && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; @@ -16212,6 +16459,8 @@ var ts; case 218 /* SyntaxKind.AwaitExpression */: case 231 /* SyntaxKind.MetaProperty */: return true; + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + return !ts.isHeritageClause(node.parent); case 161 /* SyntaxKind.QualifiedName */: while (node.parent.kind === 161 /* SyntaxKind.QualifiedName */) { node = node.parent; @@ -16383,9 +16632,6 @@ var ts; } ts.isVariableDeclarationInitializedToBareOrAccessedRequire = isVariableDeclarationInitializedToBareOrAccessedRequire; function isVariableDeclarationInitializedWithRequireHelper(node, allowAccessedRequire) { - if (node.kind === 203 /* SyntaxKind.BindingElement */) { - node = node.parent.parent; - } return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, /*requireStringLiteralLikeArgument*/ true); @@ -17037,16 +17283,6 @@ var ts; return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function hasRestParameter(s) { - var last = ts.lastOrUndefined(s.parameters); - return !!last && isRestParameter(last); - } - ts.hasRestParameter = hasRestParameter; - function isRestParameter(node) { - var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; - } - ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { return !!node.typeArguments; } @@ -17168,6 +17404,12 @@ var ts; return [child, node]; } ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild; + function skipTypeParentheses(node) { + while (ts.isParenthesizedTypeNode(node)) + node = node.type; + return node; + } + ts.skipTypeParentheses = skipTypeParentheses; function skipParentheses(node, excludeJSDocTypeAssertions) { var flags = excludeJSDocTypeAssertions ? 1 /* OuterExpressionKinds.Parentheses */ | 16 /* OuterExpressionKinds.ExcludeJSDocTypeAssertion */ : @@ -18914,6 +19156,10 @@ var ts; return hasEffectiveModifier(node, 64 /* ModifierFlags.Readonly */); } ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier; + function hasDecorators(node) { + return hasSyntacticModifier(node, 131072 /* ModifierFlags.Decorator */); + } + ts.hasDecorators = hasDecorators; function getSelectedEffectiveModifierFlags(node, flags) { return getEffectiveModifierFlags(node) & flags; } @@ -18991,7 +19237,7 @@ var ts; * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc. */ function getSyntacticModifierFlagsNoCache(node) { - var flags = modifiersToFlags(node.modifiers); + var flags = ts.canHaveModifiers(node) ? modifiersToFlags(node.modifiers) : 0 /* ModifierFlags.None */; if (node.flags & 4 /* NodeFlags.NestedNamespace */ || (node.kind === 79 /* SyntaxKind.Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* ModifierFlags.Export */; } @@ -19025,6 +19271,7 @@ var ts; case 159 /* SyntaxKind.OverrideKeyword */: return 16384 /* ModifierFlags.Override */; case 101 /* SyntaxKind.InKeyword */: return 32768 /* ModifierFlags.In */; case 144 /* SyntaxKind.OutKeyword */: return 65536 /* ModifierFlags.Out */; + case 165 /* SyntaxKind.Decorator */: return 131072 /* ModifierFlags.Decorator */; } return 0 /* ModifierFlags.None */; } @@ -19402,8 +19649,9 @@ var ts; * Moves the start position of a range past any decorators. */ function moveRangePastDecorators(node) { - return node.decorators && node.decorators.length > 0 - ? moveRangePos(node, node.decorators.end) + var lastDecorator = ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + return lastDecorator && !positionIsSynthesized(lastDecorator.end) + ? moveRangePos(node, lastDecorator.end) : node; } ts.moveRangePastDecorators = moveRangePastDecorators; @@ -19411,8 +19659,9 @@ var ts; * Moves the start position of a range past any decorators or modifiers. */ function moveRangePastModifiers(node) { - return node.modifiers && node.modifiers.length > 0 - ? moveRangePos(node, node.modifiers.end) + var lastModifier = ts.canHaveModifiers(node) ? ts.lastOrUndefined(node.modifiers) : undefined; + return lastModifier && !positionIsSynthesized(lastModifier.end) + ? moveRangePos(node, lastModifier.end) : moveRangePastDecorators(node); } ts.moveRangePastModifiers = moveRangePastModifiers; @@ -19534,7 +19783,8 @@ var ts; function getDeclarationModifierFlagsFromSymbol(s, isWrite) { if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 173 /* SyntaxKind.SetAccessor */; })) || s.valueDeclaration; + var declaration = (isWrite && s.declarations && ts.find(s.declarations, ts.isSetAccessorDeclaration)) + || (s.flags & 32768 /* SymbolFlags.GetAccessor */ && ts.find(s.declarations, ts.isGetAccessorDeclaration)) || s.valueDeclaration; var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* SymbolFlags.Class */ ? flags : flags & ~28 /* ModifierFlags.AccessibilityModifier */; } @@ -20207,8 +20457,9 @@ var ts; */ function isFileForcedToBeModuleByFormat(file) { // Excludes declaration files - they still require an explicit `export {}` or the like - // for back compat purposes. - return file.impliedNodeFormat === ts.ModuleKind.ESNext && !file.isDeclarationFile ? true : undefined; + // for back compat purposes. The only non-declaration files _not_ forced to be a module are `.js` files + // that aren't esm-mode (meaning not in a `type: module` scope). + return (file.impliedNodeFormat === ts.ModuleKind.ESNext || (ts.fileExtensionIsOneOf(file.fileName, [".cjs" /* Extension.Cjs */, ".cts" /* Extension.Cts */, ".mjs" /* Extension.Mjs */, ".mts" /* Extension.Mts */]))) && !file.isDeclarationFile ? true : undefined; } function getSetExternalModuleIndicator(options) { // TODO: Should this callback be cached? @@ -20216,7 +20467,7 @@ var ts; case ts.ModuleDetectionKind.Force: // All non-declaration files are modules, declaration files still do the usual isFileProbablyExternalModule return function (file) { - file.externalModuleIndicator = !file.isDeclarationFile || ts.isFileProbablyExternalModule(file); + file.externalModuleIndicator = ts.isFileProbablyExternalModule(file) || !file.isDeclarationFile || undefined; }; case ts.ModuleDetectionKind.Legacy: // Files are modules if they have imports, exports, or import.meta @@ -20231,10 +20482,7 @@ var ts; if (options.jsx === 4 /* JsxEmit.ReactJSX */ || options.jsx === 5 /* JsxEmit.ReactJSXDev */) { checks.push(isFileModuleFromUsingJSXTag); } - var moduleKind = getEmitModuleKind(options); - if (moduleKind === ts.ModuleKind.Node16 || moduleKind === ts.ModuleKind.NodeNext) { - checks.push(isFileForcedToBeModuleByFormat); - } + checks.push(isFileForcedToBeModuleByFormat); var combined_1 = ts.or.apply(void 0, checks); var callback = function (file) { return void (file.externalModuleIndicator = combined_1(file)); }; return callback; @@ -20276,7 +20524,8 @@ var ts; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; function getEmitModuleDetectionKind(options) { - return options.moduleDetection || ts.ModuleDetectionKind.Auto; + return options.moduleDetection || + (getEmitModuleKind(options) === ts.ModuleKind.Node16 || getEmitModuleKind(options) === ts.ModuleKind.NodeNext ? ts.ModuleDetectionKind.Force : ts.ModuleDetectionKind.Auto); } ts.getEmitModuleDetectionKind = getEmitModuleDetectionKind; function hasJsonModuleEmitEnabled(options) { @@ -20359,6 +20608,10 @@ var ts; return optionsHaveChanges(oldOptions, newOptions, ts.affectsEmitOptionDeclarations); } ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit; + function compilerOptionsAffectDeclarationPath(newOptions, oldOptions) { + return optionsHaveChanges(oldOptions, newOptions, ts.affectsDeclarationPathOptionDeclarations); + } + ts.compilerOptionsAffectDeclarationPath = compilerOptionsAffectDeclarationPath; function getCompilerOptionValue(options, option) { return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; } @@ -21299,8 +21552,12 @@ var ts; return node.parent.templateSpans; case 233 /* SyntaxKind.TemplateSpan */: return node.parent.templateSpans; - case 165 /* SyntaxKind.Decorator */: - return node.parent.decorators; + case 165 /* SyntaxKind.Decorator */: { + var parent_2 = node.parent; + return ts.canHaveDecorators(parent_2) ? parent_2.modifiers : + ts.canHaveIllegalDecorators(parent_2) ? parent_2.illegalDecorators : + undefined; + } case 291 /* SyntaxKind.HeritageClause */: return node.parent.heritageClauses; } @@ -21814,7 +22071,7 @@ var ts; * Wraps an expression in parentheses if it is needed in order to use the expression for * property or element access. */ - function parenthesizeLeftSideOfAccess(expression) { + function parenthesizeLeftSideOfAccess(expression, optionalChain) { // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exception is: // @@ -21823,7 +22080,8 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments) + && (optionalChain || !ts.isOptionalChain(emittedExpression))) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -22770,13 +23028,8 @@ var ts; function createBaseNode(kind) { return baseFactory.createBaseNode(kind); } - function createBaseDeclaration(kind, decorators, modifiers) { + function createBaseDeclaration(kind) { var node = createBaseNode(kind); - node.decorators = asNodeArray(decorators); - node.modifiers = asNodeArray(modifiers); - node.transformFlags |= - propagateChildrenFlags(node.decorators) | - propagateChildrenFlags(node.modifiers); // NOTE: The following properties are commonly set by the binder and are added here to // ensure declarations have a stable shape. node.symbol = undefined; // initialized by binder @@ -22785,10 +23038,15 @@ var ts; node.nextContainer = undefined; // initialized by binder return node; } - function createBaseNamedDeclaration(kind, decorators, modifiers, name) { - var node = createBaseDeclaration(kind, decorators, modifiers); + function createBaseNamedDeclaration(kind, modifiers, name) { + var node = createBaseDeclaration(kind); name = asName(name); node.name = name; + if (ts.canHaveModifiers(node)) { + node.modifiers = asNodeArray(modifiers); + node.transformFlags |= propagateChildrenFlags(node.modifiers); + // node.decorators = filter(node.modifiers, isDecorator); + } // The PropertyName of a member is allowed to be `await`. // We don't need to exclude `await` for type signatures since types // don't propagate child flags. @@ -22811,16 +23069,16 @@ var ts; } return node; } - function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.typeParameters = asNodeArray(typeParameters); node.transformFlags |= propagateChildrenFlags(node.typeParameters); if (typeParameters) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.parameters = createNodeArray(parameters); node.type = type; node.transformFlags |= @@ -22828,50 +23086,45 @@ var ts; propagateChildFlags(node.type); if (type) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used for quick info + node.typeArguments = undefined; return node; } - function updateBaseSignatureDeclaration(updated, original) { - // copy children used only for error reporting - if (original.typeArguments) + function finishUpdateBaseSignatureDeclaration(updated, original) { + if (updated !== original) { + // copy children used for quick info updated.typeArguments = original.typeArguments; + } return update(updated, original); } - function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { - var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); + function createBaseFunctionLikeDeclaration(kind, modifiers, name, typeParameters, parameters, type, body) { + var node = createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateBaseFunctionLikeDeclaration(updated, original) { - // copy children used only for error reporting - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - if (original.typeArguments) - updated.typeArguments = original.typeArguments; - return updateBaseSignatureDeclaration(updated, original); - } - function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.heritageClauses = asNodeArray(heritageClauses); node.transformFlags |= propagateChildrenFlags(node.heritageClauses); return node; } - function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses); + function createBaseClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members); return node; } - function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseBindingLikeDeclaration(kind, modifiers, name, initializer) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.initializer = initializer; node.transformFlags |= propagateChildFlags(node.initializer); return node; } - function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) { - var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer); + function createBaseVariableLikeDeclaration(kind, modifiers, name, type, initializer) { + var node = createBaseBindingLikeDeclaration(kind, modifiers, name, initializer); node.type = type; node.transformFlags |= propagateChildFlags(type); if (type) @@ -22967,7 +23220,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 132 /* SyntaxKind.AwaitKeyword */) { - node.transformFlags |= 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } return node; } @@ -23019,7 +23272,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(80 /* SyntaxKind.PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags |= 16777216 /* TransformFlags.ContainsClassFields */; return node; } // @@ -23066,14 +23319,14 @@ var ts; transformFlags = 1 /* TransformFlags.ContainsTypeScript */; break; case 106 /* SyntaxKind.SuperKeyword */: - transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 33554432 /* TransformFlags.ContainsLexicalSuper */; + transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 134217728 /* TransformFlags.ContainsLexicalSuper */; break; case 124 /* SyntaxKind.StaticKeyword */: transformFlags = 1024 /* TransformFlags.ContainsES2015 */; break; case 108 /* SyntaxKind.ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 8192 /* TransformFlags.ContainsLexicalThis */; + transformFlags = 16384 /* TransformFlags.ContainsLexicalThis */; break; } if (transformFlags) { @@ -23171,7 +23424,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 65536 /* TransformFlags.ContainsComputedPropertyName */; + 131072 /* TransformFlags.ContainsComputedPropertyName */; return node; } // @api @@ -23180,41 +23433,19 @@ var ts; ? update(createComputedPropertyName(expression), node) : node; } - function createTypeParameterDeclaration(modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } - var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, - /*decorators*/ undefined, modifiers, name); + // + // Signature elements + // + // @api + function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) { + var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, modifiers, name); node.constraint = constraint; node.default = defaultType; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateTypeParameterDeclaration(node, modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } + // @api + function updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType) { return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint @@ -23223,8 +23454,8 @@ var ts; : node; } // @api - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -23237,32 +23468,32 @@ var ts; if (questionToken) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; if (ts.modifiersToFlags(node.modifiers) & 16476 /* ModifierFlags.ParameterPropertyModifier */) - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; } return node; } // @api - function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } // @api function createDecorator(expression) { var node = createBaseNode(165 /* SyntaxKind.Decorator */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */ | - 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */ | + 33554432 /* TransformFlags.ContainsDecorators */; return node; } // @api @@ -23276,11 +23507,12 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, - /*decorators*/ undefined, modifiers, name); + var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, modifiers, name); node.type = type; node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.initializer = undefined; return node; } // @api @@ -23289,20 +23521,27 @@ var ts; || node.name !== name || node.questionToken !== questionToken || node.type !== type - ? update(createPropertySignature(modifiers, name, questionToken, type), node) + ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) : node; } + function finishUpdatePropertySignature(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.initializer = original.initializer; + } + return update(updated, original); + } // @api - function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, decorators, modifiers, name, type, initializer); + function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 8388608 /* TransformFlags.ContainsClassFields */; + 16777216 /* TransformFlags.ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; @@ -23310,21 +23549,19 @@ var ts; return node; } // @api - function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.modifiers !== modifiers || node.name !== name || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer - ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23337,12 +23574,12 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node; } // @api - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= @@ -23363,12 +23600,13 @@ var ts; else if (asteriskToken) { node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } + // The following properties are used only to report grammar errors + node.exclamationToken = undefined; return node; } // @api - function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.questionToken !== questionToken @@ -23376,80 +23614,123 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } + function finishUpdateMethodDeclaration(updated, original) { + if (updated !== original) { + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api - function createClassStaticBlockDeclaration(decorators, modifiers, body) { - var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, decorators, modifiers, + function createClassStaticBlockDeclaration(body) { + var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, + /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined); node.body = body; - node.transformFlags = propagateChildFlags(body) | 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags = propagateChildFlags(body) | 16777216 /* TransformFlags.ContainsClassFields */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api - function updateClassStaticBlockDeclaration(node, decorators, modifiers, body) { - return node.decorators !== decorators - || node.modifier !== modifiers - || node.body !== body - ? update(createClassStaticBlockDeclaration(decorators, modifiers, body), node) + function updateClassStaticBlockDeclaration(node, body) { + return node.body !== body + ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) : node; } + function finishUpdateClassStaticBlockDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, decorators, modifiers, + function createConstructorDeclaration(modifiers, parameters, body) { + var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.typeParameters = undefined; + node.type = undefined; return node; } // @api - function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateConstructorDeclaration(node, modifiers, parameters, body) { + return node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node) + ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) : node; } + function finishUpdateConstructorDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, decorators, modifiers, name, + function createGetAccessorDeclaration(modifiers, name, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + return node; } // @api - function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node) + ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) : node; } + function finishUpdateGetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, decorators, modifiers, name, + function createSetAccessorDeclaration(modifiers, name, parameters, body) { + var node = createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + node.type = undefined; + return node; } // @api - function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateSetAccessorDeclaration(node, modifiers, name, parameters, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node) + ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) : node; } + function finishUpdateSetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createCallSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(174 /* SyntaxKind.CallSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23460,13 +23741,12 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node; } // @api function createConstructSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(175 /* SyntaxKind.ConstructSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23477,24 +23757,23 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node; } // @api - function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, decorators, modifiers, + function createIndexSignature(modifiers, parameters, type) { + var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } // @api - function updateIndexSignature(node, decorators, modifiers, parameters, type) { + function updateIndexSignature(node, modifiers, parameters, type) { return node.parameters !== parameters || node.type !== type - || node.decorators !== decorators || node.modifiers !== modifiers - ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node; } // @api @@ -23554,10 +23833,11 @@ var ts; // @api function createFunctionTypeNode(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(179 /* SyntaxKind.FunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.modifiers = undefined; return node; } // @api @@ -23565,9 +23845,15 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node) + ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) : node; } + function finishUpdateFunctionTypeNode(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createConstructorTypeNode() { var args = []; @@ -23579,8 +23865,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, - /*decorators*/ undefined, modifiers, + var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23604,7 +23889,7 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node; } /** @deprecated */ @@ -23784,33 +24069,27 @@ var ts; ? update(createTemplateLiteralType(head, templateSpans), node) : node; } - function createImportTypeNode(argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : false; + // @api + function createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = false; } var node = createBaseNode(200 /* SyntaxKind.ImportType */); node.argument = argument; - node.assertions = assertion; + node.assertions = assertions; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.isTypeOf = isTypeOf; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateImportTypeNode(node, argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : node.isTypeOf; + // @api + function updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; } return node.argument !== argument - || node.assertions !== assertion + || node.assertions !== assertions || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf - ? update(createImportTypeNode(argument, assertion, qualifier, typeArguments, isTypeOf), node) + ? update(createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf), node) : node; } // @api @@ -23909,11 +24188,11 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + 524288 /* TransformFlags.ContainsBindingPattern */; + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } return node; } @@ -23930,7 +24209,7 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; + 524288 /* TransformFlags.ContainsBindingPattern */; return node; } // @api @@ -23942,7 +24221,6 @@ var ts; // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(203 /* SyntaxKind.BindingElement */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; @@ -23955,7 +24233,7 @@ var ts; propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 16384 /* TransformFlags.ContainsRestOrSpread */; + node.transformFlags |= 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -24011,13 +24289,13 @@ var ts; // @api function createPropertyAccessExpression(expression, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.name = asName(name); node.transformFlags = propagateChildFlags(node.expression) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); if (ts.isSuperKeyword(expression)) { // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators @@ -24041,7 +24319,7 @@ var ts; function createPropertyAccessChain(expression, questionDotToken, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= @@ -24050,7 +24328,7 @@ var ts; propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); return node; } // @api @@ -24067,7 +24345,7 @@ var ts; // @api function createElementAccessExpression(expression, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.argumentExpression = asExpression(index); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24095,7 +24373,7 @@ var ts; function createElementAccessChain(expression, questionDotToken, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.argumentExpression = asExpression(index); node.transformFlags |= @@ -24119,7 +24397,7 @@ var ts; // @api function createCallExpression(expression, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); node.transformFlags |= @@ -24130,10 +24408,10 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 4194304 /* TransformFlags.ContainsDynamicImport */; + node.transformFlags |= 8388608 /* TransformFlags.ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24152,7 +24430,7 @@ var ts; function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -24166,7 +24444,7 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24207,7 +24485,7 @@ var ts; // @api function createTaggedTemplateExpression(tag, typeArguments, template) { var node = createBaseExpression(210 /* SyntaxKind.TaggedTemplateExpression */); - node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); + node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.template = template; node.transformFlags |= @@ -24264,8 +24542,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); if (node.typeParameters) { @@ -24293,20 +24570,19 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, - /*decorators*/ undefined, modifiers, + var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* SyntaxKind.EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | 1024 /* TransformFlags.ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { - node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24318,7 +24594,7 @@ var ts; || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } // @api @@ -24368,7 +24644,7 @@ var ts; propagateChildFlags(node.expression) | 256 /* TransformFlags.ContainsES2017 */ | 128 /* TransformFlags.ContainsES2018 */ | - 1048576 /* TransformFlags.ContainsAwait */; + 2097152 /* TransformFlags.ContainsAwait */; return node; } // @api @@ -24389,7 +24665,7 @@ var ts; ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -24410,7 +24686,7 @@ var ts; if (ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -24456,11 +24732,14 @@ var ts; else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { node.transformFlags |= 16 /* TransformFlags.ContainsES2021 */; } + if (operatorKind === 101 /* SyntaxKind.InKeyword */ && ts.isPrivateIdentifier(node.left)) { + node.transformFlags |= 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */; + } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; if (node.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer @@ -24468,8 +24747,8 @@ var ts; var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (target.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } if (target.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); @@ -24595,7 +24874,7 @@ var ts; propagateChildFlags(node.asteriskToken) | 1024 /* TransformFlags.ContainsES2015 */ | 128 /* TransformFlags.ContainsES2018 */ | - 524288 /* TransformFlags.ContainsYield */; + 1048576 /* TransformFlags.ContainsYield */; return node; } // @api @@ -24612,7 +24891,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 16384 /* TransformFlags.ContainsRestOrSpread */; + 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -24622,20 +24901,19 @@ var ts; : node; } // @api - function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, modifiers, name, typeParameters, heritageClauses, members); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; return node; } // @api - function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api @@ -24645,7 +24923,7 @@ var ts; // @api function createExpressionWithTypeArguments(expression, typeArguments) { var node = createBaseNode(228 /* SyntaxKind.ExpressionWithTypeArguments */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24681,7 +24959,7 @@ var ts; // @api function createNonNullExpression(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -24700,7 +24978,7 @@ var ts; function createNonNullChain(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -24783,10 +25061,12 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */); + node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= - propagateChildFlags(node.declarationList); + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.declarationList); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } @@ -24945,7 +25225,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24960,7 +25240,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24977,7 +25257,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -25077,7 +25357,6 @@ var ts; // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { var node = createBaseVariableLikeDeclaration(254 /* SyntaxKind.VariableDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; node.transformFlags |= propagateChildFlags(node.exclamationToken); @@ -25103,11 +25382,11 @@ var ts; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* NodeFlags.BlockScoped */) { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */ | - 131072 /* TransformFlags.ContainsBlockScopedBinding */; + 262144 /* TransformFlags.ContainsBlockScopedBinding */; } return node; } @@ -25118,8 +25397,8 @@ var ts; : node; } // @api - function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -25127,7 +25406,7 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { if (node.asteriskToken) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */; @@ -25140,104 +25419,133 @@ var ts; node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } } + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } + function finishUpdateFunctionDeclaration(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.illegalDecorators = original.illegalDecorators; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } else { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; - if (node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */) { + if (node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } } return node; } // @api - function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api - function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? finishUpdateInterfaceDeclaration(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } + function finishUpdateInterfaceDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + function createTypeAliasDeclaration(modifiers, name, typeParameters, type) { + var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type - ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + ? finishUpdateTypeAliasDeclaration(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; } + function finishUpdateTypeAliasDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, decorators, modifiers, name); + function createEnumDeclaration(modifiers, name, members) { + var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateEnumDeclaration(node, decorators, modifiers, name, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateEnumDeclaration(node, modifiers, name, members) { + return node.modifiers !== modifiers || node.name !== name || node.members !== members - ? update(createEnumDeclaration(decorators, modifiers, name, members), node) + ? finishUpdateEnumDeclaration(createEnumDeclaration(modifiers, name, members), node) : node; } + function finishUpdateEnumDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createModuleDeclaration(decorators, modifiers, name, body, flags) { + function createModuleDeclaration(modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* NodeFlags.None */; } - var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */); + node.modifiers = asNodeArray(modifiers); node.flags |= flags & (16 /* NodeFlags.Namespace */ | 4 /* NodeFlags.NestedNamespace */ | 1024 /* NodeFlags.GlobalAugmentation */); node.name = name; node.body = body; @@ -25246,22 +25554,30 @@ var ts; } else { node.transformFlags |= - propagateChildFlags(node.name) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateModuleDeclaration(node, decorators, modifiers, name, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateModuleDeclaration(node, modifiers, name, body) { + return node.modifiers !== modifiers || node.name !== name || node.body !== body - ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + ? finishUpdateModuleDeclaration(createModuleDeclaration(modifiers, name, body, node.flags), node) : node; } + function finishUpdateModuleDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createModuleBlock(statements) { var node = createBaseNode(262 /* SyntaxKind.ModuleBlock */); @@ -25291,60 +25607,84 @@ var ts; // @api function createNamespaceExportDeclaration(name) { var node = createBaseNamedDeclaration(264 /* SyntaxKind.NamespaceExportDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api function updateNamespaceExportDeclaration(node, name) { return node.name !== name - ? update(createNamespaceExportDeclaration(name), node) + ? finishUpdateNamespaceExportDeclaration(createNamespaceExportDeclaration(name), node) : node; } + function finishUpdateNamespaceExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, decorators, modifiers, name); + function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) { + var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference - ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node) + ? finishUpdateImportEqualsDeclaration(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; } + function finishUpdateImportEqualsDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */, decorators, modifiers); + function createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause), node) + ? finishUpdateImportDeclaration(createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateImportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createImportClause(isTypeOnly, name, namedBindings) { var node = createBaseNode(267 /* SyntaxKind.ImportClause */); @@ -25357,7 +25697,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25417,7 +25757,7 @@ var ts; var node = createBaseNode(268 /* SyntaxKind.NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25433,7 +25773,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.name) | 4 /* TransformFlags.ContainsESNext */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25447,7 +25787,7 @@ var ts; var node = createBaseNode(269 /* SyntaxKind.NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25465,7 +25805,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25477,54 +25817,71 @@ var ts; : node; } // @api - function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */, decorators, modifiers); + function createExportAssignment(modifiers, isExportEquals, expression) { + var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */); + node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(63 /* SyntaxKind.EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); - node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportAssignment(node, decorators, modifiers, expression) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportAssignment(node, modifiers, expression) { + return node.modifiers !== modifiers || node.expression !== expression - ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + ? finishUpdateExportAssignment(createExportAssignment(modifiers, node.isExportEquals, expression), node) : node; } + function finishUpdateExportAssignment(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */, decorators, modifiers); + function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= - propagateChildFlags(node.exportClause) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) + ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createNamedExports(elements) { var node = createBaseNode(273 /* SyntaxKind.NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25542,7 +25899,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25555,9 +25912,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */, - /*decorators*/ undefined, - /*modifiers*/ undefined); + var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */); return node; } // @@ -25568,7 +25923,7 @@ var ts; var node = createBaseNode(277 /* SyntaxKind.ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25624,7 +25979,6 @@ var ts; // @api function createJSDocFunctionType(parameters, type) { var node = createBaseSignatureDeclaration(317 /* SyntaxKind.JSDocFunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); @@ -26276,26 +26630,18 @@ var ts; // @api function createPropertyAssignment(name, initializer) { var node = createBaseNamedDeclaration(296 /* SyntaxKind.PropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer); + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdatePropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updatePropertyAssignment(node, name, initializer) { return node.name !== name @@ -26303,31 +26649,32 @@ var ts; ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) : node; } + function finishUpdatePropertyAssignment(updated, original) { + // copy children used only for error reporting + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { var node = createBaseNamedDeclaration(297 /* SyntaxKind.ShorthandPropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.equalsToken = undefined; + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdateShorthandPropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.equalsToken) - updated.equalsToken = original.equalsToken; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { return node.name !== name @@ -26335,6 +26682,17 @@ var ts; ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) : node; } + function finishUpdateShorthandPropertyAssignment(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.equalsToken = original.equalsToken; + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createSpreadAssignment(expression) { var node = createBaseNode(298 /* SyntaxKind.SpreadAssignment */); @@ -26342,7 +26700,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; return node; } // @api @@ -26662,13 +27020,11 @@ var ts; } function createExportDefault(expression) { return createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); } function createExternalModuleExport(exportName) { return createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, createNamedExports([ createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName) @@ -26826,7 +27182,7 @@ var ts; } else if (ts.getEmitFlags(callee) & 4096 /* EmitFlags.HelperName */) { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee, /*optionalChain*/ false); } else if (ts.isPropertyAccessExpression(callee)) { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { @@ -26855,7 +27211,7 @@ var ts; else { // for `a()` target is `a` and thisArg is `void 0` thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); } return { target: target, thisArg: thisArg }; } @@ -26864,9 +27220,7 @@ var ts; // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560) createParenthesizedExpression(createObjectLiteralExpression([ createSetAccessorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, "value", [createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, paramName, /*questionToken*/ undefined, @@ -27168,30 +27522,32 @@ var ts; else { modifierArray = modifiers; } - return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : - ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : - ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : - ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifierArray, node.parameters, node.body) : - ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.type, node.body) : - ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.body) : - ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifierArray, node.parameters, node.type) : - ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : - ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : - ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.type) : - ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifierArray, node.name, node.members) : - ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifierArray, node.name, node.body) : - ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : - ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : - ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifierArray, node.expression) : - ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : - ts.Debug.assertNever(node); + return ts.isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : + ts.isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : + ts.isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : + ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : + ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : + ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : + ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : + ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : + ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : + ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : + ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : + ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : + ts.isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : + ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : + ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : + ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : + ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : + ts.isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : + ts.isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : + ts.isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : + ts.Debug.assertNever(node); } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -27299,10 +27655,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 33562624 /* TransformFlags.PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 134234112 /* TransformFlags.PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -27333,29 +27689,29 @@ var ts; case 208 /* SyntaxKind.CallExpression */: case 209 /* SyntaxKind.NewExpression */: case 204 /* SyntaxKind.ArrayLiteralExpression */: - return 536887296 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; + return -2147450880 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; case 261 /* SyntaxKind.ModuleDeclaration */: - return 589443072 /* TransformFlags.ModuleExcludes */; + return -1941676032 /* TransformFlags.ModuleExcludes */; case 164 /* SyntaxKind.Parameter */: - return 536870912 /* TransformFlags.ParameterExcludes */; + return -2147483648 /* TransformFlags.ParameterExcludes */; case 214 /* SyntaxKind.ArrowFunction */: - return 557748224 /* TransformFlags.ArrowFunctionExcludes */; + return -2072174592 /* TransformFlags.ArrowFunctionExcludes */; case 213 /* SyntaxKind.FunctionExpression */: case 256 /* SyntaxKind.FunctionDeclaration */: - return 591310848 /* TransformFlags.FunctionExcludes */; + return -1937940480 /* TransformFlags.FunctionExcludes */; case 255 /* SyntaxKind.VariableDeclarationList */: - return 537165824 /* TransformFlags.VariableDeclarationListExcludes */; + return -2146893824 /* TransformFlags.VariableDeclarationListExcludes */; case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return 536940544 /* TransformFlags.ClassExcludes */; + return -2147344384 /* TransformFlags.ClassExcludes */; case 171 /* SyntaxKind.Constructor */: - return 591306752 /* TransformFlags.ConstructorExcludes */; + return -1937948672 /* TransformFlags.ConstructorExcludes */; case 167 /* SyntaxKind.PropertyDeclaration */: - return 570433536 /* TransformFlags.PropertyExcludes */; + return -2013249536 /* TransformFlags.PropertyExcludes */; case 169 /* SyntaxKind.MethodDeclaration */: case 172 /* SyntaxKind.GetAccessor */: case 173 /* SyntaxKind.SetAccessor */: - return 574529536 /* TransformFlags.MethodOrAccessorExcludes */; + return -2005057536 /* TransformFlags.MethodOrAccessorExcludes */; case 130 /* SyntaxKind.AnyKeyword */: case 147 /* SyntaxKind.NumberKeyword */: case 158 /* SyntaxKind.BigIntKeyword */: @@ -27375,23 +27731,23 @@ var ts; case 259 /* SyntaxKind.TypeAliasDeclaration */: return -2 /* TransformFlags.TypeExcludes */; case 205 /* SyntaxKind.ObjectLiteralExpression */: - return 536973312 /* TransformFlags.ObjectLiteralExcludes */; + return -2147278848 /* TransformFlags.ObjectLiteralExcludes */; case 292 /* SyntaxKind.CatchClause */: - return 536903680 /* TransformFlags.CatchClauseExcludes */; + return -2147418112 /* TransformFlags.CatchClauseExcludes */; case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: - return 536887296 /* TransformFlags.BindingPatternExcludes */; + return -2147450880 /* TransformFlags.BindingPatternExcludes */; case 211 /* SyntaxKind.TypeAssertionExpression */: case 229 /* SyntaxKind.AsExpression */: case 350 /* SyntaxKind.PartiallyEmittedExpression */: case 212 /* SyntaxKind.ParenthesizedExpression */: case 106 /* SyntaxKind.SuperKeyword */: - return 536870912 /* TransformFlags.OuterExpressionExcludes */; + return -2147483648 /* TransformFlags.OuterExpressionExcludes */; case 206 /* SyntaxKind.PropertyAccessExpression */: case 207 /* SyntaxKind.ElementAccessExpression */: - return 536870912 /* TransformFlags.PropertyAccessExcludes */; + return -2147483648 /* TransformFlags.PropertyAccessExcludes */; default: - return 536870912 /* TransformFlags.NodeExcludes */; + return -2147483648 /* TransformFlags.NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -28801,6 +29157,11 @@ var ts; return node.kind === 126 /* SyntaxKind.AbstractKeyword */; } ts.isAbstractModifier = isAbstractModifier; + /* @internal */ + function isOverrideModifier(node) { + return node.kind === 159 /* SyntaxKind.OverrideKeyword */; + } + ts.isOverrideModifier = isOverrideModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 106 /* SyntaxKind.SuperKeyword */; @@ -29256,6 +29617,10 @@ var ts; return node.kind === 267 /* SyntaxKind.ImportClause */; } ts.isImportClause = isImportClause; + function isImportTypeAssertionContainer(node) { + return node.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */; + } + ts.isImportTypeAssertionContainer = isImportTypeAssertionContainer; function isAssertClause(node) { return node.kind === 293 /* SyntaxKind.AssertClause */; } @@ -29593,7 +29958,7 @@ var ts; (function (ts) { // Compound nodes function createEmptyExports(factory) { - return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); + return factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); } ts.createEmptyExports = createEmptyExports; function createMemberAccessForPropertyName(factory, target, memberName, location) { @@ -29743,13 +30108,13 @@ var ts; return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({ enumerable: factory.createFalse(), configurable: true, - get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, + get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(getAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, /*type*/ undefined, getAccessor.body // TODO: GH#18217 ), getAccessor), getAccessor), - set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, + set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(setAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, @@ -29768,7 +30133,7 @@ var ts; /*original*/ property); } function createExpressionForMethodDeclaration(factory, method, receiver) { - return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken, + return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(ts.getModifiers(method), method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, /*type*/ undefined, method.body // TODO: GH#18217 @@ -30001,7 +30366,6 @@ var ts; } if (namedBindings) { var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText), /*assertClause*/ undefined); ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* EmitFlags.NeverApplyImportHelper */); @@ -30320,33 +30684,50 @@ var ts; } } ts.getJSDocTypeAliasName = getJSDocTypeAliasName; - function canHaveModifiers(node) { + function canHaveIllegalType(node) { var kind = node.kind; - return kind === 164 /* SyntaxKind.Parameter */ - || kind === 166 /* SyntaxKind.PropertySignature */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 168 /* SyntaxKind.MethodSignature */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ + return kind === 171 /* SyntaxKind.Constructor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalType = canHaveIllegalType; + function canHaveIllegalTypeParameters(node) { + var kind = node.kind; + return kind === 171 /* SyntaxKind.Constructor */ || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalTypeParameters = canHaveIllegalTypeParameters; + function canHaveIllegalDecorators(node) { + var kind = node.kind; + return kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 213 /* SyntaxKind.FunctionExpression */ - || kind === 214 /* SyntaxKind.ArrowFunction */ - || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ || kind === 237 /* SyntaxKind.VariableStatement */ - || kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 257 /* SyntaxKind.ClassDeclaration */ || kind === 258 /* SyntaxKind.InterfaceDeclaration */ || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ || kind === 260 /* SyntaxKind.EnumDeclaration */ || kind === 261 /* SyntaxKind.ModuleDeclaration */ || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ || kind === 266 /* SyntaxKind.ImportDeclaration */ - || kind === 271 /* SyntaxKind.ExportAssignment */ - || kind === 272 /* SyntaxKind.ExportDeclaration */; + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ + || kind === 272 /* SyntaxKind.ExportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */; } - ts.canHaveModifiers = canHaveModifiers; + ts.canHaveIllegalDecorators = canHaveIllegalDecorators; + function canHaveIllegalModifiers(node) { + var kind = node.kind; + return kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 179 /* SyntaxKind.FunctionType */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */; + } + ts.canHaveIllegalModifiers = canHaveIllegalModifiers; ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); @@ -30610,6 +30991,14 @@ var ts; } } ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; + function elideNodes(factory, nodes) { + if (nodes === undefined) + return undefined; + if (nodes.length === 0) + return nodes; + return ts.setTextRange(factory.createNodeArray([], nodes.hasTrailingComma), nodes); + } + ts.elideNodes = elideNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -30617,6 +31006,46 @@ var ts; return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range; } ts.setTextRange = setTextRange; + function canHaveModifiers(node) { + var kind = node.kind; + return kind === 163 /* SyntaxKind.TypeParameter */ + || kind === 164 /* SyntaxKind.Parameter */ + || kind === 166 /* SyntaxKind.PropertySignature */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 168 /* SyntaxKind.MethodSignature */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 176 /* SyntaxKind.IndexSignature */ + || kind === 180 /* SyntaxKind.ConstructorType */ + || kind === 213 /* SyntaxKind.FunctionExpression */ + || kind === 214 /* SyntaxKind.ArrowFunction */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 237 /* SyntaxKind.VariableStatement */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 257 /* SyntaxKind.ClassDeclaration */ + || kind === 258 /* SyntaxKind.InterfaceDeclaration */ + || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 260 /* SyntaxKind.EnumDeclaration */ + || kind === 261 /* SyntaxKind.ModuleDeclaration */ + || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 266 /* SyntaxKind.ImportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */ + || kind === 272 /* SyntaxKind.ExportDeclaration */; + } + ts.canHaveModifiers = canHaveModifiers; + function canHaveDecorators(node) { + var kind = node.kind; + return kind === 164 /* SyntaxKind.Parameter */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 257 /* SyntaxKind.ClassDeclaration */; + } + ts.canHaveDecorators = canHaveDecorators; })(ts || (ts = {})); var ts; (function (ts) { @@ -30686,7 +31115,7 @@ var ts; } ts.isFileProbablyExternalModule = isFileProbablyExternalModule; function isAnExternalModuleIndicatorNode(node) { - return hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) + return ts.canHaveModifiers(node) && hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) || ts.isImportDeclaration(node) || ts.isExportAssignment(node) @@ -30735,7 +31164,7 @@ var ts; visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || @@ -30745,79 +31174,128 @@ var ts; case 298 /* SyntaxKind.SpreadAssignment */: return visitNode(cbNode, node.expression); case 164 /* SyntaxKind.Parameter */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 167 /* SyntaxKind.PropertyDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 166 /* SyntaxKind.PropertySignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 296 /* SyntaxKind.PropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.initializer); case 254 /* SyntaxKind.VariableDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || + return visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 203 /* SyntaxKind.BindingElement */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.dotDotDotToken) || + return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: case 176 /* SyntaxKind.IndexSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); + case 180 /* SyntaxKind.ConstructorType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 179 /* SyntaxKind.FunctionType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + return visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 169 /* SyntaxKind.MethodDeclaration */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 168 /* SyntaxKind.MethodSignature */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 171 /* SyntaxKind.Constructor */: + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 172 /* SyntaxKind.GetAccessor */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 256 /* SyntaxKind.FunctionDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 214 /* SyntaxKind.ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.body); case 178 /* SyntaxKind.TypeReference */: @@ -30945,7 +31423,7 @@ var ts; return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); case 237 /* SyntaxKind.VariableStatement */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); case 255 /* SyntaxKind.VariableDeclarationList */: @@ -31010,27 +31488,26 @@ var ts; return visitNode(cbNode, node.expression); case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 258 /* SyntaxKind.InterfaceDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); case 260 /* SyntaxKind.EnumDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); @@ -31038,17 +31515,17 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 261 /* SyntaxKind.ModuleDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); case 266 /* SyntaxKind.ImportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -31062,7 +31539,8 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.value); case 264 /* SyntaxKind.NamespaceExportDeclaration */: - return visitNode(cbNode, node.name); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNode(cbNode, node.name); case 268 /* SyntaxKind.NamespaceImport */: return visitNode(cbNode, node.name); case 274 /* SyntaxKind.NamespaceExport */: @@ -31071,7 +31549,7 @@ var ts; case 273 /* SyntaxKind.NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); case 272 /* SyntaxKind.ExportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -31081,17 +31559,21 @@ var ts; return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); case 271 /* SyntaxKind.ExportAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); case 223 /* SyntaxKind.TemplateExpression */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 233 /* SyntaxKind.TemplateSpan */: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.literal); case 198 /* SyntaxKind.TemplateLiteralType */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 199 /* SyntaxKind.TemplateLiteralTypeSpan */: - return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.literal); case 162 /* SyntaxKind.ComputedPropertyName */: return visitNode(cbNode, node.expression); case 291 /* SyntaxKind.HeritageClause */: @@ -31102,7 +31584,8 @@ var ts; case 277 /* SyntaxKind.ExternalModuleReference */: return visitNode(cbNode, node.expression); case 276 /* SyntaxKind.MissingDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers); case 351 /* SyntaxKind.CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 278 /* SyntaxKind.JsxElement */: @@ -31781,7 +32264,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* NodeFlags.AwaitContext */) - && !!(node.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -31822,7 +32305,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setFields(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); setFields(sourceFile); } @@ -32750,7 +33233,7 @@ var ts; } return parseElement(); } - function currentNode(parsingContext) { + function currentNode(parsingContext, pos) { // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. // // If there is an outstanding parse error that we've encountered, but not attached to @@ -32763,7 +33246,7 @@ var ts; if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } - var node = syntaxCursor.currentNode(scanner.getStartPos()); + var node = syntaxCursor.currentNode(pos !== null && pos !== void 0 ? pos : scanner.getStartPos()); // Can't reuse a missing node. // Can't reuse a node that intersected the change range. // Can't reuse a node that contains a parse error. This is necessary so that we @@ -33038,7 +33521,9 @@ var ts; case 23 /* ParsingContext.ImportOrExportSpecifiers */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 13 /* ParsingContext.JsxAttributes */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 14 /* ParsingContext.JsxChildren */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - default: return [undefined]; // TODO: GH#18217 `default: Debug.assertNever(context);` + case 24 /* ParsingContext.AssertEntries */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_or_string_literal_expected); // AssertionKey. + case 25 /* ParsingContext.Count */: return ts.Debug.fail("ParsingContext.Count used as a context"); // Not a real context, only a marker. + default: ts.Debug.assertNever(context); } } function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { @@ -33354,7 +33839,6 @@ var ts; parseExpected(58 /* SyntaxKind.ColonToken */); } return finishNode(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier? @@ -33480,10 +33964,9 @@ var ts; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : doOutsideOfAwaitContext(parseDecorators); if (token() === 108 /* SyntaxKind.ThisKeyword */) { var node_1 = factory.createParameterDeclaration(decorators, - /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); @@ -33494,12 +33977,12 @@ var ts; } var savedTopLevel = topLevel; topLevel = false; - var modifiers = parseModifiers(); + var modifiers = combineDecoratorsAndModifiers(decorators, parseModifiers()); var dotDotDotToken = parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */); if (!allowAmbiguity && !isParameterNameStart()) { return undefined; } - var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createParameterDeclaration(modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); topLevel = savedTopLevel; return node; } @@ -33651,7 +34134,8 @@ var ts; var parameters = parseBracketedList(16 /* ParsingContext.Parameters */, function () { return parseParameter(/*inOuterAwaitContext*/ false); }, 22 /* SyntaxKind.OpenBracketToken */, 23 /* SyntaxKind.CloseBracketToken */); var type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - var node = factory.createIndexSignature(decorators, modifiers, parameters, type); + var node = factory.createIndexSignature(modifiers, parameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) { @@ -33724,10 +34208,10 @@ var ts; var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */, 4 /* SignatureFlags.Type */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */, 4 /* SignatureFlags.Type */); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); @@ -34365,10 +34849,10 @@ var ts; setDecoratorContext(/*val*/ false); } var pos = getNodePos(); - var expr = parseAssignmentExpressionOrHigher(); + var expr = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); var operatorToken; while ((operatorToken = parseOptionalToken(27 /* SyntaxKind.CommaToken */))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos); + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), pos); } if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -34376,9 +34860,9 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true) : undefined; } - function parseAssignmentExpressionOrHigher() { + function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) { // AssignmentExpression[in,yield]: // 1) ConditionalExpression[?in,?yield] // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] @@ -34404,7 +34888,7 @@ var ts; // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + var arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction); if (arrowExpression) { return arrowExpression; } @@ -34423,7 +34907,7 @@ var ts; // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. if (expr.kind === 79 /* SyntaxKind.Identifier */ && token() === 38 /* SyntaxKind.EqualsGreaterThanToken */) { - return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, /*asyncModifier*/ undefined); } // Now see if we might be in cases '2' or '3'. // If the expression was a LHS expression, and we have an assignment operator, then @@ -34432,10 +34916,10 @@ var ts; // Note: we call reScanGreaterToken so that we get an appropriately merged token // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos); + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); } // It wasn't an assignment or a lambda. This is a conditional expression: - return parseConditionalExpressionRest(expr, pos); + return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction); } function isYieldExpression() { if (token() === 125 /* SyntaxKind.YieldKeyword */) { @@ -34475,7 +34959,7 @@ var ts; nextToken(); if (!scanner.hasPrecedingLineBreak() && (token() === 41 /* SyntaxKind.AsteriskToken */ || isStartOfExpression())) { - return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher()), pos); + return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)), pos); } else { // if the next token is not on the same line as yield. or we don't have an '*' or @@ -34483,10 +34967,9 @@ var ts; return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { ts.Debug.assert(token() === 38 /* SyntaxKind.EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var parameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, identifier, /*questionToken*/ undefined, @@ -34495,11 +34978,11 @@ var ts; finishNode(parameter, identifier.pos); var parameters = createNodeArray([parameter], parameter.pos, parameter.end); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); - var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier, allowReturnTypeInArrowFunction); var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body); return addJSDocComment(finishNode(node, pos)); } - function tryParseParenthesizedArrowFunctionExpression() { + function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var triState = isParenthesizedArrowFunctionExpression(); if (triState === 0 /* Tristate.False */) { // It's definitely not a parenthesized arrow function expression. @@ -34510,8 +34993,8 @@ var ts; // it out, but don't allow any ambiguity, and return 'undefined' if this could be an // expression instead. return triState === 1 /* Tristate.True */ ? - parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) : - tryParse(parsePossibleParenthesizedArrowFunctionExpression); + parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true, /*allowReturnTypeInArrowFunction*/ true) : + tryParse(function () { return parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction); }); } // True -> We definitely expect a parenthesized arrow function here. // False -> There *cannot* be a parenthesized arrow function here. @@ -34576,7 +35059,7 @@ var ts; // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. if (ts.isModifierKind(second) && second !== 131 /* SyntaxKind.AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { - if (lookAhead(function () { return nextToken() === 127 /* SyntaxKind.AsKeyword */; })) { + if (nextToken() === 127 /* SyntaxKind.AsKeyword */) { // https://github.com/microsoft/TypeScript/issues/44466 return 0 /* Tristate.False */; } @@ -34645,25 +35128,25 @@ var ts; return 2 /* Tristate.Unknown */; } } - function parsePossibleParenthesizedArrowFunctionExpression() { + function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var tokenPos = scanner.getTokenPos(); if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) { return undefined; } - var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false); + var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false, allowReturnTypeInArrowFunction); if (!result) { (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos); } return result; } - function tryParseAsyncSimpleArrowFunctionExpression() { + function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() === 131 /* SyntaxKind.AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* Tristate.True */) { var pos = getNodePos(); var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0 /* OperatorPrecedence.Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); } } return undefined; @@ -34687,7 +35170,7 @@ var ts; } return 0 /* Tristate.False */; } - function parseParenthesizedArrowFunctionExpression(allowAmbiguity) { + function parseParenthesizedArrowFunctionExpression(allowAmbiguity, allowReturnTypeInArrowFunction) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiersForArrowFunction(); @@ -34722,6 +35205,7 @@ var ts; return undefined; } } + var hasReturnColon = token() === 58 /* SyntaxKind.ColonToken */; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) { return undefined; @@ -34750,12 +35234,37 @@ var ts; var lastToken = token(); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); var body = (lastToken === 38 /* SyntaxKind.EqualsGreaterThanToken */ || lastToken === 18 /* SyntaxKind.OpenBraceToken */) - ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier)) + ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier(); + // Given: + // x ? y => ({ y }) : z => ({ z }) + // We try to parse the body of the first arrow function by looking at: + // ({ y }) : z => ({ z }) + // This is a valid arrow function with "z" as the return type. + // + // But, if we're in the true side of a conditional expression, this colon + // terminates the expression, so we cannot allow a return type if we aren't + // certain whether or not the preceding text was parsed as a parameter list. + // + // For example, + // a() ? (b: number, c?: string): void => d() : e + // is determined by isParenthesizedArrowFunctionExpression to unambiguously + // be an arrow expression, so we allow a return type. + if (!allowReturnTypeInArrowFunction && hasReturnColon) { + // However, if the arrow function we were able to parse is followed by another colon + // as in: + // a ? (x): string => x : null + // Then allow the arrow function, and treat the second colon as terminating + // the conditional expression. It's okay to do this because this code would + // be a syntax error in JavaScript (as the second colon shouldn't be there). + if (token() !== 58 /* SyntaxKind.ColonToken */) { + return undefined; + } + } var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseArrowFunctionExpressionBody(isAsync) { + function parseArrowFunctionExpressionBody(isAsync, allowReturnTypeInArrowFunction) { if (token() === 18 /* SyntaxKind.OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* SignatureFlags.Await */ : 0 /* SignatureFlags.None */); } @@ -34783,12 +35292,12 @@ var ts; var savedTopLevel = topLevel; topLevel = false; var node = isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + ? doInAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }) + : doOutsideOfAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }); topLevel = savedTopLevel; return node; } - function parseConditionalExpressionRest(leftOperand, pos) { + function parseConditionalExpressionRest(leftOperand, pos, allowReturnTypeInArrowFunction) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. var questionToken = parseOptionalToken(57 /* SyntaxKind.QuestionToken */); if (!questionToken) { @@ -34797,8 +35306,8 @@ var ts; // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. var colonToken; - return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) - ? parseAssignmentExpressionOrHigher() + return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ false); }), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) + ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(79 /* SyntaxKind.Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* SyntaxKind.ColonToken */))), pos); } function parseBinaryExpressionOrHigher(precedence) { @@ -35183,6 +35692,9 @@ var ts; var typeArguments = tryParse(parseTypeArgumentsInExpression); if (typeArguments !== undefined) { parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments); + if (!isTemplateStartOfTaggedTemplate()) { + expression = factory.createExpressionWithTypeArguments(expression, typeArguments); + } } } if (token() === 20 /* SyntaxKind.OpenParenToken */ || token() === 24 /* SyntaxKind.DotToken */ || token() === 22 /* SyntaxKind.OpenBracketToken */) { @@ -35395,9 +35907,22 @@ var ts; } scanJsxIdentifier(); var pos = getNodePos(); - return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 63 /* SyntaxKind.EqualsToken */ ? undefined : - scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */ ? parseLiteralNode() : - parseJsxExpression(/*inExpressionContext*/ true)), pos); + return finishNode(factory.createJsxAttribute(parseIdentifierName(), parseJsxAttributeValue()), pos); + } + function parseJsxAttributeValue() { + if (token() === 63 /* SyntaxKind.EqualsToken */) { + if (scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */) { + return parseLiteralNode(); + } + if (token() === 18 /* SyntaxKind.OpenBraceToken */) { + return parseJsxExpression(/*inExpressionContext*/ true); + } + if (token() === 29 /* SyntaxKind.LessThanToken */) { + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + parseErrorAtCurrentToken(ts.Diagnostics.or_JSX_element_expected); + } + return undefined; } function parseJsxSpreadAttribute() { var pos = getNodePos(); @@ -35487,6 +36012,11 @@ var ts; if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) { parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers); } + if (ts.isExpressionWithTypeArguments(expression) && expression.typeArguments) { + var pos_2 = expression.typeArguments.pos - 1; + var end = ts.skipTrivia(sourceText, expression.typeArguments.end) + 1; + parseErrorAt(pos_2, end, ts.Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access); + } return finishNode(propertyAccess, pos); } function parseElementAccessExpressionRest(pos, expression, questionDotToken) { @@ -35612,10 +36142,11 @@ var ts; } nextToken(); var typeArguments = parseDelimitedList(20 /* ParsingContext.TypeArguments */, parseType); - if (!parseExpected(31 /* SyntaxKind.GreaterThanToken */)) { + if (reScanGreaterToken() !== 31 /* SyntaxKind.GreaterThanToken */) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } + nextToken(); // We successfully parsed a type argument list. The next token determines whether we want to // treat it as such. If the type argument list is followed by `(` or a template literal, as in // `f(42)`, we favor the type argument interpretation even though JavaScript would view @@ -35629,9 +36160,18 @@ var ts; case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: // foo `...` case 15 /* SyntaxKind.TemplateHead */: // foo `...${100}...` return true; + // A type argument list followed by `<` never makes sense, and a type argument list followed + // by `>` is ambiguous with a (re-scanned) `>>` operator, so we disqualify both. Also, in + // this context, `+` and `-` are unary operators, not binary operators. + case 29 /* SyntaxKind.LessThanToken */: + case 31 /* SyntaxKind.GreaterThanToken */: + case 39 /* SyntaxKind.PlusToken */: + case 40 /* SyntaxKind.MinusToken */: + return false; } - // Consider something a type argument list only if the following token can't start an expression. - return !isStartOfExpression(); + // We favor the type argument list interpretation when it is immediately followed by + // a line break, a binary operator, or something that can't start an expression. + return scanner.hasPrecedingLineBreak() || isBinaryOperator() || !isStartOfExpression(); } function parsePrimaryExpression() { switch (token()) { @@ -35690,13 +36230,13 @@ var ts; function parseSpreadElement() { var pos = getNodePos(); parseExpected(25 /* SyntaxKind.DotDotDotToken */); - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createSpreadElement(expression), pos); } function parseArgumentOrArrayLiteralElement() { return token() === 25 /* SyntaxKind.DotDotDotToken */ ? parseSpreadElement() : token() === 27 /* SyntaxKind.CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) : - parseAssignmentExpressionOrHigher(); + parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); @@ -35714,16 +36254,16 @@ var ts; var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); if (parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */)) { - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc); } var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } var asteriskToken = parseOptionalToken(41 /* SyntaxKind.AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -35743,7 +36283,7 @@ var ts; var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* SyntaxKind.ColonToken */); if (isShorthandPropertyAssignment) { var equalsToken = parseOptionalToken(63 /* SyntaxKind.EqualsToken */); - var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined; + var objectAssignmentInitializer = equalsToken ? allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }) : undefined; node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer); // Save equals token for error reporting. // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful. @@ -35751,11 +36291,11 @@ var ts; } else { parseExpected(58 /* SyntaxKind.ColonToken */); - var initializer = allowInAnd(parseAssignmentExpressionOrHigher); + var initializer = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); node = factory.createPropertyAssignment(name, initializer); } // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; node.questionToken = questionToken; node.exclamationToken = exclamationToken; @@ -35815,6 +36355,9 @@ var ts; typeArguments = expression.typeArguments; expression = expression.expression; } + if (token() === 28 /* SyntaxKind.QuestionDotToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, ts.getTextOfNodeFromSourceText(sourceText, expression)); + } var argumentList = token() === 20 /* SyntaxKind.OpenParenToken */ ? parseArgumentList() : undefined; return finishNode(factory.createNewExpression(expression, typeArguments, argumentList), pos); } @@ -35925,7 +36468,7 @@ var ts; } var node; if (awaitToken ? parseExpected(160 /* SyntaxKind.OfKeyword */) : parseOptional(160 /* SyntaxKind.OfKeyword */)) { - var expression = allowInAnd(parseAssignmentExpressionOrHigher); + var expression = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); parseExpected(21 /* SyntaxKind.CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); } @@ -36330,24 +36873,19 @@ var ts; return modifier.kind === 135 /* SyntaxKind.DeclareKeyword */; } function parseDeclaration() { - // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner - // if we can't reuse the declaration, so that we don't do this work twice? - // // `parseListElement` attempted to get the reused node at this position, // but the ambient context flag was not yet set, so the node appeared // not reusable in that context. - var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier); - if (isAmbient) { - var node = tryReuseAmbientDeclaration(); - if (node) { - return node; - } - } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var decorators = parseDecorators(); var modifiers = parseModifiers(); + var isAmbient = ts.some(modifiers, isDeclareModifier); if (isAmbient) { + var node = tryReuseAmbientDeclaration(pos); + if (node) { + return node; + } for (var _i = 0, _a = modifiers; _i < _a.length; _i++) { var m = _a[_i]; m.flags |= 16777216 /* NodeFlags.Ambient */; @@ -36358,9 +36896,9 @@ var ts; return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); } } - function tryReuseAmbientDeclaration() { + function tryReuseAmbientDeclaration(pos) { return doInsideOfContext(16777216 /* NodeFlags.Ambient */, function () { - var node = currentNode(parsingContext); + var node = currentNode(parsingContext, pos); if (node) { return consumeNode(node); } @@ -36405,7 +36943,7 @@ var ts; // would follow. For recovery and error reporting purposes, return an incomplete declaration. var missing = createMissingNode(276 /* SyntaxKind.MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); - missing.decorators = decorators; + missing.illegalDecorators = decorators; missing.modifiers = modifiers; return missing; } @@ -36417,9 +36955,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* SyntaxKind.StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 18 /* SyntaxKind.OpenBraceToken */ && canParseSemicolon()) { - parseSemicolon(); - return; + if (token() !== 18 /* SyntaxKind.OpenBraceToken */) { + if (flags & 4 /* SignatureFlags.Type */) { + parseTypeMemberSemicolon(); + return; + } + if (canParseSemicolon()) { + parseSemicolon(); + return; + } } return parseFunctionBlock(flags, diagnosticMessage); } @@ -36542,7 +37086,7 @@ var ts; parseSemicolon(); var node = factory.createVariableStatement(modifiers, declarationList); // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker. - node.decorators = decorators; + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36561,7 +37105,8 @@ var ts; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); setAwaitContext(savedAwaitContext); - var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + var node = factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseConstructorName() { @@ -36582,8 +37127,9 @@ var ts; var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */, ts.Diagnostics.or_expected); - var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body); - // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker. + var node = factory.createConstructorDeclaration(modifiers, parameters, body); + // Attach invalid nodes if they exist so that we can report them in the grammar checker. + node.illegalDecorators = decorators; node.typeParameters = typeParameters; node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36597,7 +37143,7 @@ var ts; var parameters = parseParameters(isGenerator | isAsync); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + var node = factory.createMethodDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); // An exclamation token on a method is invalid syntax and will be handled by the grammar checker node.exclamationToken = exclamationToken; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36607,7 +37153,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = doOutsideOfContext(8192 /* NodeFlags.YieldContext */ | 32768 /* NodeFlags.AwaitContext */ | 4096 /* NodeFlags.DisallowInContext */, parseInitializer); parseSemicolonAfterPropertyName(name, type, initializer); - var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer); + var node = factory.createPropertyDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, questionToken || exclamationToken, type, initializer); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36621,18 +37167,18 @@ var ts; } return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken); } - function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) { + function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind, flags) { var name = parsePropertyName(); var typeParameters = parseTypeParameters(); var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); - var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */); + var body = parseFunctionBlockOrSemicolon(flags); var node = kind === 172 /* SyntaxKind.GetAccessor */ - ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) - : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); + ? factory.createGetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, type, body) + : factory.createSetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 173 /* SyntaxKind.SetAccessor */) + if (ts.isSetAccessorDeclaration(node)) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -36698,7 +37244,10 @@ var ts; function parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers) { parseExpectedToken(124 /* SyntaxKind.StaticKeyword */); var body = parseClassStaticBlockBody(); - return withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(decorators, modifiers, body), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(body), pos), hasJSDoc); + node.illegalDecorators = decorators; + node.modifiers = modifiers; + return node; } function parseClassStaticBlockBody() { var savedYieldContext = inYieldContext(); @@ -36761,6 +37310,15 @@ var ts; } return finishNode(factory.createToken(kind), pos); } + function combineDecoratorsAndModifiers(decorators, modifiers) { + if (!decorators) + return modifiers; + if (!modifiers) + return decorators; + var decoratorsAndModifiers = factory.createNodeArray(ts.concatenate(decorators, modifiers)); + ts.setTextRangePosEnd(decoratorsAndModifiers, decorators.pos, modifiers.end); + return decoratorsAndModifiers; + } /* * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect @@ -36801,10 +37359,10 @@ var ts; return parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers); } if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } if (token() === 134 /* SyntaxKind.ConstructorKeyword */ || token() === 10 /* SyntaxKind.StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -36869,8 +37427,8 @@ var ts; } setAwaitContext(savedAwaitContext); var node = kind === 257 /* SyntaxKind.ClassDeclaration */ - ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) - : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); + ? factory.createClassDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members) + : factory.createClassExpression(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseNameOfClassDeclarationOrExpression() { @@ -36927,7 +37485,8 @@ var ts; var typeParameters = parseTypeParameters(); var heritageClauses = parseHeritageClauses(); var members = parseObjectTypeMembers(); - var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = factory.createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36937,7 +37496,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var type = token() === 138 /* SyntaxKind.IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); parseSemicolon(); - var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type); + var node = factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } // In an ambient declaration, the grammar only allows integer literals as initializers. @@ -36962,7 +37522,8 @@ var ts; else { members = createMissingList(); } - var node = factory.createEnumDeclaration(decorators, modifiers, name, members); + var node = factory.createEnumDeclaration(modifiers, name, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleBlock() { @@ -36985,7 +37546,8 @@ var ts; var body = parseOptional(24 /* SyntaxKind.DotToken */) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NodeFlags.NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -37007,7 +37569,8 @@ var ts; else { parseSemicolon(); } - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -37047,7 +37610,7 @@ var ts; parseSemicolon(); var node = factory.createNamespaceExportDeclaration(name); // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -37086,14 +37649,15 @@ var ts; assertClause = parseAssertClause(); } parseSemicolon(); - var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause); + var node = factory.createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAssertEntry() { var pos = getNodePos(); var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* SyntaxKind.StringLiteral */); parseExpected(58 /* SyntaxKind.ColonToken */); - var value = parseAssignmentExpressionOrHigher(); + var value = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createAssertEntry(name, value), pos); } function parseAssertClause(skipAssertKeyword) { @@ -37130,7 +37694,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var moduleReference = parseModuleReference(); parseSemicolon(); - var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference); + var node = factory.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference); + node.illegalDecorators = decorators; var finished = withJSDoc(finishNode(node, pos), hasJSDoc); return finished; } @@ -37319,7 +37884,8 @@ var ts; } parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + var node = factory.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) { @@ -37332,10 +37898,11 @@ var ts; else { parseExpected(88 /* SyntaxKind.DefaultKeyword */); } - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression); + var node = factory.createExportAssignment(modifiers, isExportEquals, expression); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } var ParsingContext; @@ -38126,7 +38693,6 @@ var ts; if (parseOptional(24 /* SyntaxKind.DotToken */)) { var body = parseJSDocTypeNameWithNamespace(/*nested*/ true); var jsDocNamespaceNode = factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NodeFlags.NestedNamespace */ : undefined); return finishNode(jsDocNamespaceNode, pos); } @@ -38563,10 +39129,10 @@ var ts; } function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { - var pos_2 = node.pos; + var pos_3 = node.pos; var visitNode_1 = function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; + ts.Debug.assert(child.pos >= pos_3); + pos_3 = child.end; }; if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -38575,7 +39141,7 @@ var ts; } } forEachChild(node, visitNode_1); - ts.Debug.assert(pos_2 <= node.end); + ts.Debug.assert(pos_3 <= node.end); } } function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { @@ -39173,6 +39739,7 @@ var ts; ["es2022.error", "lib.es2022.error.d.ts"], ["es2022.intl", "lib.es2022.intl.d.ts"], ["es2022.object", "lib.es2022.object.d.ts"], + ["es2022.sharedmemory", "lib.es2022.sharedmemory.d.ts"], ["es2022.string", "lib.es2022.string.d.ts"], ["esnext.array", "lib.es2022.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], @@ -39386,6 +39953,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, defaultValueDescription: false, @@ -39420,12 +39988,40 @@ var ts; affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, defaultValueDescription: 0 /* ScriptTarget.ES3 */, }; + /*@internal*/ + ts.moduleOptionDeclaration = { + name: "module", + shortName: "m", + type: new ts.Map(ts.getEntries({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + es2020: ts.ModuleKind.ES2020, + es2022: ts.ModuleKind.ES2022, + esnext: ts.ModuleKind.ESNext, + node16: ts.ModuleKind.Node16, + nodenext: ts.ModuleKind.NodeNext, + })), + affectsModuleResolution: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Modules, + description: ts.Diagnostics.Specify_what_module_code_is_generated, + defaultValueDescription: undefined, + }; var commandOptionsWithoutBuild = [ // CommandLine only options { @@ -39487,37 +40083,14 @@ var ts; category: ts.Diagnostics.Command_line_Options, affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, isCommandLineOnly: true, description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, defaultValueDescription: false, }, // Basic ts.targetOptionDeclaration, - { - name: "module", - shortName: "m", - type: new ts.Map(ts.getEntries({ - none: ts.ModuleKind.None, - commonjs: ts.ModuleKind.CommonJS, - amd: ts.ModuleKind.AMD, - system: ts.ModuleKind.System, - umd: ts.ModuleKind.UMD, - es6: ts.ModuleKind.ES2015, - es2015: ts.ModuleKind.ES2015, - es2020: ts.ModuleKind.ES2020, - es2022: ts.ModuleKind.ES2022, - esnext: ts.ModuleKind.ESNext, - node16: ts.ModuleKind.Node16, - nodenext: ts.ModuleKind.NodeNext, - })), - affectsModuleResolution: true, - affectsEmit: true, - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Modules, - description: ts.Diagnostics.Specify_what_module_code_is_generated, - defaultValueDescription: undefined, - }, + ts.moduleOptionDeclaration, { name: "lib", type: "list", @@ -39554,6 +40127,7 @@ var ts; type: jsxOptionMap, affectsSourceFile: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -39566,6 +40140,7 @@ var ts; shortName: "d", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -39576,6 +40151,7 @@ var ts; name: "declarationMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -39586,6 +40162,7 @@ var ts; name: "emitDeclarationOnly", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, @@ -39596,6 +40173,7 @@ var ts; name: "sourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -39605,6 +40183,9 @@ var ts; name: "outFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, showInSimplifiedHelpView: true, @@ -39616,6 +40197,8 @@ var ts; name: "outDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, showInSimplifiedHelpView: true, @@ -39626,6 +40209,8 @@ var ts; name: "rootDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Modules, @@ -39636,6 +40221,8 @@ var ts; name: "composite", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isTSConfigOnly: true, category: ts.Diagnostics.Projects, transpileOptionValue: undefined, @@ -39646,6 +40233,8 @@ var ts; name: "tsBuildInfoFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, category: ts.Diagnostics.Projects, @@ -39657,6 +40246,7 @@ var ts; name: "removeComments", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -39675,6 +40265,7 @@ var ts; name: "importHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, defaultValueDescription: false, @@ -39688,6 +40279,7 @@ var ts; })), affectsEmit: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, defaultValueDescription: 0 /* ImportsNotUsedAsValues.Remove */, @@ -39696,6 +40288,7 @@ var ts; name: "downlevelIteration", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, defaultValueDescription: false, @@ -39714,6 +40307,9 @@ var ts; type: "boolean", // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here // The value of each strictFlag depends on own strictFlag value or this and never accessed directly. + // But we need to store `strict` in builf info, even though it won't be examined directly, so that the + // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_all_strict_type_checking_options, @@ -39723,6 +40319,7 @@ var ts; name: "noImplicitAny", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, @@ -39732,6 +40329,7 @@ var ts; name: "strictNullChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_type_checking_take_into_account_null_and_undefined, @@ -39740,6 +40338,8 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, @@ -39748,6 +40348,8 @@ var ts; { name: "strictBindCallApply", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, @@ -39757,6 +40359,7 @@ var ts; name: "strictPropertyInitialization", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, @@ -39766,6 +40369,7 @@ var ts; name: "noImplicitThis", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, @@ -39775,6 +40379,7 @@ var ts; name: "useUnknownInCatchVariables", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, @@ -39784,6 +40389,8 @@ var ts; name: "alwaysStrict", type: "boolean", affectsSourceFile: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_use_strict_is_always_emitted, @@ -39794,6 +40401,7 @@ var ts; name: "noUnusedLocals", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, defaultValueDescription: false, @@ -39802,6 +40410,7 @@ var ts; name: "noUnusedParameters", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, defaultValueDescription: false, @@ -39810,6 +40419,7 @@ var ts; name: "exactOptionalPropertyTypes", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, defaultValueDescription: false, @@ -39818,6 +40428,7 @@ var ts; name: "noImplicitReturns", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, defaultValueDescription: false, @@ -39827,6 +40438,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, defaultValueDescription: false, @@ -39835,6 +40447,7 @@ var ts; name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, defaultValueDescription: false, @@ -39843,6 +40456,7 @@ var ts; name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, defaultValueDescription: false, @@ -39850,6 +40464,8 @@ var ts; { name: "noPropertyAccessFromIndexSignature", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: false, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, @@ -39935,6 +40551,7 @@ var ts; name: "allowSyntheticDefaultImports", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, defaultValueDescription: ts.Diagnostics.module_system_or_esModuleInterop @@ -39944,6 +40561,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, @@ -39960,6 +40578,7 @@ var ts; name: "allowUmdGlobalAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules, defaultValueDescription: false, @@ -39981,6 +40600,7 @@ var ts; name: "sourceRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code, @@ -39989,6 +40609,7 @@ var ts; name: "mapRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, @@ -39997,6 +40618,7 @@ var ts; name: "inlineSourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -40005,6 +40627,7 @@ var ts; name: "inlineSources", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -40014,6 +40637,7 @@ var ts; name: "experimentalDecorators", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, defaultValueDescription: false, @@ -40023,6 +40647,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, defaultValueDescription: false, @@ -40047,6 +40672,7 @@ var ts; type: "string", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, @@ -40064,6 +40690,9 @@ var ts; name: "out", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: false, // for correct behaviour, please use outFile category: ts.Diagnostics.Backwards_Compatibility, @@ -40075,6 +40704,7 @@ var ts; name: "reactNamespace", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, defaultValueDescription: "`React`", @@ -40082,6 +40712,8 @@ var ts; { name: "skipDefaultLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, defaultValueDescription: false, @@ -40097,6 +40729,7 @@ var ts; name: "emitBOM", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, defaultValueDescription: false, @@ -40108,6 +40741,7 @@ var ts; lf: 1 /* NewLineKind.LineFeed */ })), affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Set_the_newline_character_for_emitting_files, @@ -40117,6 +40751,7 @@ var ts; name: "noErrorTruncation", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_truncating_types_in_error_messages, defaultValueDescription: false, @@ -40147,6 +40782,7 @@ var ts; name: "stripInternal", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, defaultValueDescription: false, @@ -40187,6 +40823,7 @@ var ts; name: "noImplicitUseStrict", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, defaultValueDescription: false, @@ -40195,6 +40832,7 @@ var ts; name: "noEmitHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, defaultValueDescription: false, @@ -40203,6 +40841,7 @@ var ts; name: "noEmitOnError", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, @@ -40212,6 +40851,7 @@ var ts; name: "preserveConstEnums", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, defaultValueDescription: false, @@ -40220,6 +40860,8 @@ var ts; name: "declarationDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, category: ts.Diagnostics.Emit, @@ -40229,6 +40871,8 @@ var ts; { name: "skipLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_all_d_ts_files, defaultValueDescription: false, @@ -40238,6 +40882,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unused_labels, defaultValueDescription: undefined, @@ -40247,6 +40892,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code, defaultValueDescription: undefined, @@ -40255,6 +40901,7 @@ var ts; name: "suppressExcessPropertyErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, defaultValueDescription: false, @@ -40263,6 +40910,7 @@ var ts; name: "suppressImplicitAnyIndexErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, defaultValueDescription: false, @@ -40287,6 +40935,7 @@ var ts; name: "noStrictGenericChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, defaultValueDescription: false, @@ -40296,6 +40945,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, defaultValueDescription: ts.Diagnostics.true_for_ES2022_and_above_including_ESNext @@ -40304,6 +40954,7 @@ var ts; name: "preserveValueImports", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, defaultValueDescription: false, @@ -40347,6 +40998,8 @@ var ts; /* @internal */ ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; }); /* @internal */ + ts.affectsDeclarationPathOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsDeclarationPath; }); + /* @internal */ ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); /* @internal */ ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { @@ -41169,7 +41822,7 @@ var ts; return undefined; if (ts.length(specs) !== 1) return specs; - if (specs[0] === "**/*") + if (specs[0] === ts.defaultIncludeSpec) return undefined; return specs; } @@ -41202,6 +41855,7 @@ var ts; return optionDefinition.type; } } + /* @internal */ function getNameOfCompilerOptionValue(value, customTypeMap) { // There is a typeMap associated with this command-line option so use it to map value back to its name return ts.forEachEntry(customTypeMap, function (mapValue, key) { @@ -41210,6 +41864,7 @@ var ts; } }); } + ts.getNameOfCompilerOptionValue = getNameOfCompilerOptionValue; function serializeCompilerOptions(options, pathOptions) { return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); } @@ -41447,6 +42102,8 @@ var ts; // until consistent casing errors are reported return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } + /*@internal*/ + ts.defaultIncludeSpec = "**/*"; /** * Parse the contents of a config file from json or json source file (tsconfig.json). * @param json The contents of the config file to parse @@ -41512,6 +42169,7 @@ var ts; } var includeSpecs = toPropValue(getSpecsFromRaw("include")); var excludeOfRaw = getSpecsFromRaw("exclude"); + var isDefaultIncludeSpec = false; var excludeSpecs = toPropValue(excludeOfRaw); if (excludeOfRaw === "no-prop" && raw.compilerOptions) { var outDir = raw.compilerOptions.outDir; @@ -41521,7 +42179,8 @@ var ts; } } if (filesSpecs === undefined && includeSpecs === undefined) { - includeSpecs = ["**/*"]; + includeSpecs = [ts.defaultIncludeSpec]; + isDefaultIncludeSpec = true; } var validatedIncludeSpecs, validatedExcludeSpecs; // The exclude spec list is converted into a regular expression, which allows us to quickly @@ -41540,7 +42199,8 @@ var ts; validatedFilesSpec: ts.filter(filesSpecs, ts.isString), validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, - pathPatterns: undefined, // Initialized on first use + pathPatterns: undefined, + isDefaultIncludeSpec: isDefaultIncludeSpec, }; } function getFileNames(basePath) { @@ -42200,7 +42860,7 @@ var ts; } if (ts.isImplicitGlob(spec.substring(spec.lastIndexOf(ts.directorySeparator) + 1))) { return { - key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec), + key: ts.removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec)), flags: 1 /* WatchDirectoryFlags.Recursive */ }; } @@ -42370,16 +43030,18 @@ var ts; ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, diagnostics, resultFromCache) { - var _a; + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache) { + var _a, _b; if (resultFromCache) { (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = resultFromCache.affectingLocations).push.apply(_b, affectingLocations); return resultFromCache; } return { resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations, - resolutionDiagnostics: diagnostics + affectingLocations: affectingLocations, + resolutionDiagnostics: diagnostics, }; } function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { @@ -42568,6 +43230,7 @@ var ts; } } var failedLookupLocations = []; + var affectingLocations = []; var features = getDefaultNodeResolutionFeatures(options); // Unlike `import` statements, whose mode-calculating APIs are all guaranteed to return `undefined` if we're in an un-mode-ed module resolution // setting, type references will return their target mode regardless of options because of how the parser works, so we guard against the mode being @@ -42586,6 +43249,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -42602,15 +43266,17 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + var pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host); resolvedTypeReferenceDirective = { primary: primary, - resolvedFileName: resolvedFileName, - originalPath: arePathsEqual(fileName, resolvedFileName, host) ? undefined : fileName, + // If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedFileName: pathsAreEqual ? fileName : resolvedFileName, + originalPath: pathsAreEqual ? undefined : fileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName), }; } - result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, resolutionDiagnostics: diagnostics }; + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, affectingLocations: affectingLocations, resolutionDiagnostics: diagnostics }; perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, /*mode*/ resolutionMode, result); if (traceEnabled) traceResult(result); @@ -42685,17 +43351,7 @@ var ts; * Does not try `@types/${packageName}` - use a second pass if needed. */ function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ts.emptyArray, - features: NodeResolutionFeatures.None, - requestContainingDirectory: containingDirectory, - reportDiagnostic: ts.noop - }; + var moduleResolutionState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); return ts.forEachAncestorDirectory(containingDirectory, function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var nodeModulesFolder = ts.combinePaths(ancestorDirectory, "node_modules"); @@ -42792,7 +43448,7 @@ var ts; ts.createCacheWithRedirects = createCacheWithRedirects; function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { var cache; - return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries }; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries, getInternalMap: getInternalMap }; function getPackageJsonInfo(packageJsonPath) { return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); } @@ -42806,6 +43462,9 @@ var ts; var iter = cache === null || cache === void 0 ? void 0 : cache.entries(); return iter ? ts.arrayFrom(iter) : []; } + function getInternalMap() { + return cache; + } } function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); @@ -42909,15 +43568,18 @@ var ts; } ts.zipToModeAwareCache = zipToModeAwareCache; function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; }, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); - moduleNameToDirectoryMap.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + } function update(options) { updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); } @@ -42993,13 +43655,16 @@ var ts; } ts.createModuleResolutionCache = createModuleResolutionCache; function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { clear: clear, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + } } ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { @@ -43305,16 +43970,20 @@ var ts; function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.NodeNextDefault, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); + var tsconfigExtensions = [Extensions.TSConfig]; function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { var containingDirectory = ts.getDirectoryPath(containingFile); // es module file or cjs-like input file, use a variant of the legacy cjs resolver that supports the selected modern features var esmMode = resolutionMode === ts.ModuleKind.ESNext ? NodeResolutionFeatures.EsmMode : 0; - return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions, redirectedReference); + var extensions = compilerOptions.noDtsResolution ? [Extensions.TsOnly, Extensions.JavaScript] : tsExtensions; + if (compilerOptions.resolveJsonModule) { + extensions = __spreadArray(__spreadArray([], extensions, true), [Extensions.Json], false); + } + return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference); } - var jsOnlyExtensions = [Extensions.JavaScript]; - var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; - var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); - var tsconfigExtensions = [Extensions.TSConfig]; function tryResolveJSModuleWorker(moduleName, initialDir, host) { return nodeModuleNameResolverWorker(NodeResolutionFeatures.None, moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); } @@ -43340,6 +44009,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; // conditions are only used by the node16/nodenext resolver - there's no priority order in the list, //it's essentially a set (priority is determined by object insertion order in the object we look at). var conditions = features & NodeResolutionFeatures.EsmMode ? ["node", "import", "types"] : ["node", "require", "types"]; @@ -43352,6 +44022,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -43359,7 +44030,7 @@ var ts; reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; 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, diagnostics, state.resultFromCache); + 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) { var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); @@ -43385,8 +44056,10 @@ var ts; var resolvedValue = resolved_1.value; if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - var originalPath = arePathsEqual(path, resolvedValue.path, host) ? undefined : resolvedValue.path; - resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath }); + var pathsAreEqual = arePathsEqual(path, resolvedValue.path, host); + var originalPath = pathsAreEqual ? undefined : resolvedValue.path; + // If the path and realpath are differing only in casing prefer path so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedValue = __assign(__assign({}, resolvedValue), { path: pathsAreEqual ? resolvedValue.path : path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; @@ -43649,17 +44322,9 @@ var ts; var entrypoints; var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript; var features = getDefaultNodeResolutionFeatures(options); - var requireState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ["node", "require", "types"], - features: features, - requestContainingDirectory: packageJsonInfo.packageDirectory, - reportDiagnostic: ts.noop - }; + var requireState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); + requireState.conditions = ["node", "require", "types"]; + requireState.requestContainingDirectory = packageJsonInfo.packageDirectory; var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, /*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths); entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path); @@ -43732,22 +44397,27 @@ var ts; } } } - /** - * A function for locating the package.json scope for a given path - */ /*@internal*/ - function getPackageScopeForPath(fileName, packageJsonInfoCache, host, options) { - var state = { + function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) { + return { host: host, compilerOptions: options, traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], + failedLookupLocations: ts.noopPush, + affectingLocations: ts.noopPush, packageJsonInfoCache: packageJsonInfoCache, - features: 0, - conditions: [], + features: NodeResolutionFeatures.None, + conditions: ts.emptyArray, requestContainingDirectory: undefined, reportDiagnostic: ts.noop }; + } + ts.getTemporaryModuleResolutionState = getTemporaryModuleResolutionState; + /** + * A function for locating the package.json scope for a given path + */ + /*@internal*/ + function getPackageScopeForPath(fileName, state) { var parts = ts.getPathComponents(fileName); parts.pop(); while (parts.length > 0) { @@ -43774,6 +44444,7 @@ var ts; if (typeof existing !== "boolean") { if (traceEnabled) trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + state.affectingLocations.push(packageJsonPath); return existing; } else { @@ -43792,6 +44463,7 @@ var ts; var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined }; (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + state.affectingLocations.push(packageJsonPath); return result; } else { @@ -43916,7 +44588,7 @@ var ts; var _a, _b; var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope || !scope.packageJsonContent.exports) { return undefined; } @@ -43975,7 +44647,7 @@ var ts; } var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath); @@ -43997,13 +44669,38 @@ var ts; } return toSearchResult(/*value*/ undefined); } + /** + * @internal + * From https://github.com/nodejs/node/blob/8f39f51cbbd3b2de14b9ee896e26421cc5b20121/lib/internal/modules/esm/resolve.js#L722 - + * "longest" has some nuance as to what "longest" means in the presence of pattern trailers + */ + function comparePatternKeys(a, b) { + var aPatternIndex = a.indexOf("*"); + var bPatternIndex = b.indexOf("*"); + var baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + var baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + if (baseLenA > baseLenB) + return -1; + if (baseLenB > baseLenA) + return 1; + if (aPatternIndex === -1) + return 1; + if (bPatternIndex === -1) + return -1; + if (a.length > b.length) + return -1; + if (b.length > a.length) + return 1; + return 0; + } + ts.comparePatternKeys = comparePatternKeys; function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { 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); } - var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), function (a, b) { return a.length - b.length; }); + 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++) { var potentialTarget = expandingKeys_1[_i]; if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) { @@ -44322,8 +45019,8 @@ var ts; var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths); if (!pathAndExtension && packageInfo - && packageInfo.packageJsonContent.exports === undefined - && packageInfo.packageJsonContent.main === undefined + // eslint-disable-next-line no-null/no-null + && (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null) && state.features & NodeResolutionFeatures.EsmMode) { // EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume // a default `index.js` entrypoint if no `main` or `exports` are present @@ -44432,12 +45129,25 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: cache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: containingDirectory, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, + /*isExternalLibraryImport*/ false, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { @@ -44480,10 +45190,23 @@ var ts; trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; + var affectingLocations = []; var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: undefined, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: packageJsonInfoCache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: undefined, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false, /*cache*/ undefined, /*redirectedReference*/ undefined); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved, + /*isExternalLibraryImport*/ true, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -44849,7 +45572,7 @@ var ts; case 164 /* SyntaxKind.Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind, ", expected JSDocFunctionType"); }); + ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind), ", expected JSDocFunctionType"); }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -46033,8 +46756,6 @@ var ts; // - `BindingElement: BindingPattern Initializer?` // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization // - `BindingElement: BindingPattern Initializer?` - bindEach(node.decorators); - bindEach(node.modifiers); bind(node.dotDotDotToken); bind(node.propertyName); bind(node.initializer); @@ -46375,37 +47096,6 @@ var ts; typeLiteralSymbol.members.set(symbol.escapedName, symbol); } function bindObjectLiteralExpression(node) { - var ElementKind; - (function (ElementKind) { - ElementKind[ElementKind["Property"] = 1] = "Property"; - ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; - })(ElementKind || (ElementKind = {})); - if (inStrictMode && !ts.isAssignmentTarget(node)) { - var seen = new ts.Map(); - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 298 /* SyntaxKind.SpreadAssignment */ || prop.name.kind !== 79 /* SyntaxKind.Identifier */) { - continue; - } - var identifier = prop.name; - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 296 /* SyntaxKind.PropertyAssignment */ || prop.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || prop.kind === 169 /* SyntaxKind.MethodDeclaration */ - ? 1 /* ElementKind.Property */ - : 2 /* ElementKind.Accessor */; - var existingKind = seen.get(identifier.escapedText); - if (!existingKind) { - seen.set(identifier.escapedText, currentKind); - continue; - } - } - } return bindAnonymousDeclaration(node, 4096 /* SymbolFlags.ObjectLiteral */, "__object" /* InternalSymbolName.Object */); } function bindJsxAttributes(node) { @@ -47062,7 +47752,7 @@ var ts; } } function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { + if (ts.some(node.modifiers)) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level @@ -47099,12 +47789,14 @@ var ts; } } function setCommonJsModuleIndicator(node) { - if (file.externalModuleIndicator) { + if (file.externalModuleIndicator && file.externalModuleIndicator !== true) { return false; } if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } return true; } @@ -47518,7 +48210,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) && !ts.getJSDocTypeTag(node) && !(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */)) { + var possibleVariableDecl = node.kind === 254 /* SyntaxKind.VariableDeclaration */ ? node : node.parent.parent; + if (ts.isInJSFile(node) && + ts.isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && + !ts.getJSDocTypeTag(node) && + !(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* SymbolFlags.Alias */, 2097152 /* SymbolFlags.AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -47708,10 +48404,11 @@ var ts; } function isExportsOrModuleExportsOrAlias(sourceFile, node) { var i = 0; - var q = [node]; - while (q.length && i < 100) { + var q = ts.createQueue(); + q.enqueue(node); + while (!q.isEmpty() && i < 100) { i++; - node = q.shift(); + node = q.dequeue(); if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) { return true; } @@ -47719,10 +48416,10 @@ var ts; var symbol = lookupSymbolForName(sourceFile, node.escapedText); if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) { var init = symbol.valueDeclaration.initializer; - q.push(init); + q.enqueue(init); if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) { - q.push(init.left); - q.push(init.right); + q.enqueue(init.left); + q.enqueue(init.right); } } } @@ -47982,7 +48679,10 @@ var ts; TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; - TypeFacts[TypeFacts["All"] = 16777215] = "All"; + TypeFacts[TypeFacts["IsUndefined"] = 16777216] = "IsUndefined"; + TypeFacts[TypeFacts["IsNull"] = 33554432] = "IsNull"; + TypeFacts[TypeFacts["IsUndefinedOrNull"] = 50331648] = "IsUndefinedOrNull"; + TypeFacts[TypeFacts["All"] = 134217727] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. @@ -48024,25 +48724,17 @@ var ts; TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; - TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["VoidFacts"] = 9830144] = "VoidFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 26607360] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 42917664] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 83427327] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 83886079] = "EmptyObjectFacts"; + TypeFacts[TypeFacts["UnknownFacts"] = 83886079] = "UnknownFacts"; TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE"; - TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; // Masks TypeFacts[TypeFacts["OrFactsMask"] = 8256] = "OrFactsMask"; - TypeFacts[TypeFacts["AndFactsMask"] = 16768959] = "AndFactsMask"; - })(TypeFacts || (TypeFacts = {})); - var typeofEQFacts = new ts.Map(ts.getEntries({ - string: 1 /* TypeFacts.TypeofEQString */, - number: 2 /* TypeFacts.TypeofEQNumber */, - bigint: 4 /* TypeFacts.TypeofEQBigInt */, - boolean: 8 /* TypeFacts.TypeofEQBoolean */, - symbol: 16 /* TypeFacts.TypeofEQSymbol */, - undefined: 65536 /* TypeFacts.EQUndefined */, - object: 32 /* TypeFacts.TypeofEQObject */, - function: 64 /* TypeFacts.TypeofEQFunction */ - })); + TypeFacts[TypeFacts["AndFactsMask"] = 134209471] = "AndFactsMask"; + })(TypeFacts = ts.TypeFacts || (ts.TypeFacts = {})); var typeofNEFacts = new ts.Map(ts.getEntries({ string: 256 /* TypeFacts.TypeofNEString */, number: 512 /* TypeFacts.TypeofNENumber */, @@ -48077,7 +48769,7 @@ var ts; CheckMode[CheckMode["RestBindingElement"] = 64] = "RestBindingElement"; // e.g. in `const { a, ...rest } = foo`, when checking the type of `foo` to determine the type of `rest`, // we need to preserve generic types instead of substituting them for constraints - })(CheckMode || (CheckMode = {})); + })(CheckMode = ts.CheckMode || (ts.CheckMode = {})); var SignatureCheckMode; (function (SignatureCheckMode) { SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback"; @@ -48085,7 +48777,7 @@ var ts; SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes"; SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity"; SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback"; - })(SignatureCheckMode || (SignatureCheckMode = {})); + })(SignatureCheckMode = ts.SignatureCheckMode || (ts.SignatureCheckMode = {})); var IntersectionState; (function (IntersectionState) { IntersectionState[IntersectionState["None"] = 0] = "None"; @@ -48419,7 +49111,7 @@ var ts; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); - return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + return node ? getContextualTypeForObjectLiteralElement(node, /*contextFlags*/ undefined) : undefined; }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -48427,7 +49119,7 @@ var ts; }, getContextualTypeForJsxAttribute: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); - return node && getContextualTypeForJsxAttribute(node); + return node && getContextualTypeForJsxAttribute(node, /*contextFlags*/ undefined); }, isContextSensitive: isContextSensitive, getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, @@ -48541,9 +49233,9 @@ var ts; return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, - tryGetThisTypeAt: function (nodeIn, includeGlobalThis) { + tryGetThisTypeAt: function (nodeIn, includeGlobalThis, container) { var node = ts.getParseTreeNode(nodeIn); - return node && tryGetThisTypeAt(node, includeGlobalThis); + return node && tryGetThisTypeAt(node, includeGlobalThis, container); }, getTypeArgumentConstraint: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); @@ -48633,6 +49325,7 @@ var ts; var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); var subtypeReductionCache = new ts.Map(); + var cachedTypes = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var markerTypes = new ts.Set(); @@ -48641,11 +49334,10 @@ var ts; var unresolvedSymbols = new ts.Map(); var errorTypes = new ts.Map(); var anyType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); - var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); + var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 262144 /* ObjectFlags.NonInferrableType */); var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error"); var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved"); - var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); @@ -48674,8 +49366,7 @@ var ts; var esSymbolType = createIntrinsicType(4096 /* TypeFlags.ESSymbol */, "symbol"); var voidType = createIntrinsicType(16384 /* TypeFlags.Void */, "void"); var neverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); + var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* TypeFlags.NonPrimitive */, "object"); @@ -48685,16 +49376,30 @@ var ts; var numberOrBigIntType = getUnionType([numberType, bigintType]); var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]); var numericStringType = getTemplateLiteralType(["", ""], [numberType]); // The `${number}` type - var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }); - var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }); + var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }, function () { return "(restrictive mapper)"; }); + var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }, function () { return "(permissive mapper)"; }); var uniqueLiteralType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); // `uniqueLiteralType` is a special `never` flagged by union reduction to behave as a literal - var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }); // replace all type parameters with the unique literal type (disregarding constraints) + var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }, function () { return "(unique literal mapper)"; }); // replace all type parameters with the unique literal type (disregarding constraints) + var outofbandVarianceMarkerHandler; + var reportUnreliableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); + } + return t; + }, function () { return "(unmeasurable reporter)"; }); + var reportUnmeasurableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); + } + return t; + }, function () { return "(unreliable reporter)"; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyJsxObjectType.objectFlags |= 2048 /* ObjectFlags.JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* SymbolFlags.TypeLiteral */, "__type" /* InternalSymbolName.Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray)]) : unknownType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyGenericType.instantiations = new ts.Map(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); @@ -48708,6 +49413,9 @@ var ts; var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); + var markerSuperTypeForCheck = createTypeParameter(); + var markerSubTypeForCheck = createTypeParameter(); + markerSubTypeForCheck.constraint = markerSuperTypeForCheck; var noTypePredicate = createTypePredicate(1 /* TypePredicateKind.Identifier */, "<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); @@ -48837,21 +49545,13 @@ var ts; var potentialNewTargetCollisions = []; var potentialWeakMapSetCollisions = []; var potentialReflectCollisions = []; + var potentialUnusedRenamedBindingElementsInTypes = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); - var typeofTypesByName = new ts.Map(ts.getEntries({ - string: stringType, - number: numberType, - bigint: bigintType, - boolean: booleanType, - symbol: esSymbolType, - undefined: undefinedType - })); var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var outofbandVarianceMarkerHandler; var subtypeRelation = new ts.Map(); var strictSubtypeRelation = new ts.Map(); var assignableRelation = new ts.Map(); @@ -48877,6 +49577,14 @@ var ts; ]; initializeTypeChecker(); return checker; + function getCachedType(key) { + return key ? cachedTypes.get(key) : undefined; + } + function setCachedType(key, type) { + if (key) + cachedTypes.set(key, type); + return type; + } function getJsxNamespace(location) { if (location) { var file = ts.getSourceFileOfNode(location); @@ -49741,6 +50449,7 @@ var ts; if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 111551 /* SymbolFlags.Value */)) { // Remember the property node, it will be used later to report appropriate error + ts.Debug.assertNode(location, ts.isPropertyDeclaration); propertyWithInvalidInitializer = location; } } @@ -49930,11 +50639,27 @@ var ts; } } } + // The invalid initializer error is needed in two situation: + // 1. When result is undefined, after checking for a missing "this." + // 2. When result is defined + function checkAndReportErrorForInvalidInitializer() { + if (propertyWithInvalidInitializer && !(useDefineForClassFields && ts.getEmitScriptTarget(compilerOptions) >= 9 /* ScriptTarget.ES2022 */)) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed + // with ESNext+useDefineForClassFields because the scope semantics are different. + error(errorLocation, errorLocation && propertyWithInvalidInitializer.type && ts.textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) + ? ts.Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor + : ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg)); + return true; + } + return false; + } if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(function () { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForInvalidInitializer() && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && @@ -49942,7 +50667,16 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { + var suggestedLib = void 0; + // Report missing lib first + if (nameArg) { + suggestedLib = getSuggestedLibForNonExistentName(nameArg); + if (suggestedLib) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib); + } + } + // then spelling suggestions + if (!suggestedLib && getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -49961,16 +50695,9 @@ var ts; } } } - if (!suggestion) { - if (nameArg) { - var lib = getSuggestedLibForNonExistentName(nameArg); - if (lib) { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib); - } - else { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); - } - } + // And then fall back to unspecified "not found" + if (!suggestion && !suggestedLib && nameArg) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); } suggestionCount++; } @@ -49978,12 +50705,7 @@ var ts; } return undefined; } - if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ScriptTarget.ESNext */ && useDefineForClassFields)) { - // We have a match, but the reference occurred within a property initializer and the identifier also binds - // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed - // with ESNext+useDefineForClassFields because the scope semantics are different. - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + else if (checkAndReportErrorForInvalidInitializer()) { return undefined; } // Perform extra checks only if error reporting was requested @@ -50085,7 +50807,7 @@ var ts; if (decl.kind === 163 /* SyntaxKind.TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); } } } @@ -50194,7 +50916,12 @@ var ts; function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { if (isPrimitiveTypeName(name)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(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)); + } + else { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + } return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); @@ -50214,6 +50941,16 @@ var ts; } return false; } + function isExtendedByInterface(node) { + var grandparent = node.parent.parent; + var parentOfGrandparent = grandparent.parent; + if (grandparent && parentOfGrandparent) { + var isExtending = ts.isHeritageClause(grandparent) && grandparent.token === 94 /* SyntaxKind.ExtendsKeyword */; + var isInterface = ts.isInterfaceDeclaration(parentOfGrandparent); + return isExtending && isInterface; + } + return false; + } function maybeMappedType(node, symbol) { var container = ts.findAncestor(node.parent, function (n) { return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit"; @@ -50345,7 +51082,8 @@ var ts; && isAliasableOrJsExpression(node.parent.right) || node.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || node.kind === 296 /* SyntaxKind.PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node); + || node.kind === 254 /* SyntaxKind.VariableDeclaration */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) + || node.kind === 203 /* SyntaxKind.BindingElement */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -50438,7 +51176,7 @@ var ts; return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker - return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); + return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { var _a; @@ -50716,10 +51454,6 @@ var ts; checkExpressionCached(expression); return getNodeLinks(expression).resolvedSymbol; } - function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) { - var expression = node.initializer; - return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve); - } function getTargetOfAccessExpression(node, dontRecursivelyResolve) { if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */)) { return undefined; @@ -50751,7 +51485,7 @@ var ts; case 297 /* SyntaxKind.ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); case 296 /* SyntaxKind.PropertyAssignment */: - return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); + return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); case 207 /* SyntaxKind.ElementAccessExpression */: case 206 /* SyntaxKind.PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); @@ -51156,7 +51890,40 @@ var ts; // An override clause will take effect for type-only imports and import types, and allows importing the types across formats, regardless of // normal mode restrictions if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext && !ts.getResolutionModeOverrideForClause(overrideClause)) { - error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); + if (ts.findAncestor(location, ts.isImportEqualsDeclaration)) { + // ImportEquals in a ESM file resolving to another ESM file + error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); + } + else { + // CJS file resolving to an ESM file + var diagnosticDetails = void 0; + var ext = ts.tryGetExtensionFromPath(currentSourceFile.fileName); + if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) { + var scope = currentSourceFile.packageJsonScope; + var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined; + if (scope && !scope.packageJsonContent.type) { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json")); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, ts.combinePaths(scope.packageDirectory, "package.json")); + } + } + else { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, targetExt); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module); + } + } + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(diagnosticDetails, ts.Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, moduleReference))); + } } } // merged symbol is module declaration symbol combined with all augmentations @@ -51665,8 +52432,9 @@ var ts; function getExportSymbolOfValueSymbolIfExported(symbol) { return getMergedSymbol(symbol && (symbol.flags & 1048576 /* SymbolFlags.ExportValue */) !== 0 && symbol.exportSymbol || symbol); } - function symbolIsValue(symbol) { - return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && !getTypeOnlyAliasDeclaration(symbol)); + function symbolIsValue(symbol, includeTypeOnlyMembers) { + return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || + symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -51706,7 +52474,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getStringLiteralType)); + return getUnionType(ts.arrayFrom(typeofNEFacts.keys(), getStringLiteralType)); } function createTypeParameter(symbol) { var type = createType(262144 /* TypeFlags.TypeParameter */); @@ -52115,13 +52883,25 @@ var ts; && isDeclarationVisible(declaration.parent)) { return addVisibleAlias(declaration, declaration); } - else if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isBindingElement(declaration) && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement - && ts.isVariableDeclaration(declaration.parent.parent) - && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) - && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) - && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) - && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { - return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + else if (ts.isBindingElement(declaration)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement + && ts.isVariableDeclaration(declaration.parent.parent) + && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) + && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) + && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) + && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + } + else if (symbol.flags & 2 /* SymbolFlags.BlockScopedVariable */) { + var variableStatement = ts.findAncestor(declaration, ts.isVariableStatement); + if (ts.hasSyntacticModifier(variableStatement, 1 /* ModifierFlags.Export */)) { + return true; + } + if (!isDeclarationVisible(variableStatement.parent)) { + return false; + } + return addVisibleAlias(declaration, variableStatement); + } } // Declaration is not visible return false; @@ -52163,6 +52943,9 @@ var ts; if (symbol && symbol.flags & 262144 /* SymbolFlags.TypeParameter */ && meaning & 788968 /* SymbolFlags.Type */) { return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; } + if (!symbol && ts.isThisIdentifier(firstIdentifier) && isSymbolAccessible(getSymbolOfNode(ts.getThisContainer(firstIdentifier, /*includeArrowFunctions*/ false)), firstIdentifier, meaning, /*computeAliases*/ false).accessibility === 0 /* SymbolAccessibility.Accessible */) { + return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; + } // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* SymbolAccessibility.NotAccessible */, @@ -52251,7 +53034,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* TypeFormatFlags.None */; } - return flags & 814775659 /* TypeFormatFlags.NodeBuilderFlagsMask */; + return flags & 848330091 /* TypeFormatFlags.NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { return !!type.symbol && !!(type.symbol.flags & 32 /* SymbolFlags.Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* TypeFlags.Object */) && !!(ts.getObjectFlags(type) & 16777216 /* ObjectFlags.IsClassInstanceClone */))); @@ -52353,6 +53136,12 @@ var ts; return context.truncating = context.approximateLength > ((context.flags & 1 /* NodeBuilderFlags.NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { + var savedFlags = context.flags; + var typeNode = typeToTypeNodeWorker(type, context); + context.flags = savedFlags; + return typeNode; + } + function typeToTypeNodeWorker(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); } @@ -52492,6 +53281,9 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* SymbolFlags.Class */)) return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes); + if (ts.length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) { + return ts.factory.createArrayTypeNode(typeArgumentNodes[0]); + } return symbolToTypeNode(type.aliasSymbol, context, 788968 /* SymbolFlags.Type */, typeArgumentNodes); } var objectFlags = ts.getObjectFlags(type); @@ -52528,8 +53320,8 @@ var ts; if (type.symbol) { return symbolToTypeNode(type.symbol, context, 788968 /* SymbolFlags.Type */); } - var name = (type === markerSuperType || type === markerSubType) && varianceTypeParameter && varianceTypeParameter.symbol ? - (type === markerSubType ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; + var name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? + (type === markerSubTypeForCheck ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name), /*typeArguments*/ undefined); } if (type.flags & 1048576 /* TypeFlags.Union */ && type.origin) { @@ -52595,7 +53387,7 @@ var ts; var name = typeParameterToName(newParam, context); var newTypeVariable = ts.factory.createTypeReferenceNode(name); context.approximateLength += 37; // 15 each for two added conditionals, 7 for an added infer type - var newMapper = prependTypeMapping(type.root.checkType, newParam, type.combinedMapper || type.mapper); + var newMapper = prependTypeMapping(type.root.checkType, newParam, type.mapper); var saveInferTypeParameters_1 = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode_1 = typeToTypeNodeHelper(instantiateType(type.root.extendsType, newMapper), context); @@ -52636,6 +53428,10 @@ var ts; } return typeToTypeNodeHelper(type, context); } + function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) { + return isMappedTypeWithKeyofConstraintDeclaration(type) + && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */); + } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 524288 /* TypeFlags.Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -52645,7 +53441,7 @@ var ts; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` - if (!(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { var newParam = createTypeParameter(createSymbol(262144 /* SymbolFlags.TypeParameter */, "T")); var name = typeParameterToName(newParam, context); newTypeVariable = ts.factory.createTypeReferenceNode(name); @@ -52661,11 +53457,12 @@ var ts; var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; var result = ts.setEmitFlags(mappedTypeNode, 1 /* EmitFlags.SingleLine */); - if (isMappedTypeWithKeyofConstraintDeclaration(type) && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { // homomorphic mapped type with a non-homomorphic naive inlining // wrap it with a conditional like `SomeModifiersType extends infer U ? {..the mapped type...} : never` to ensure the resulting // type stays homomorphic - return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); + var originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type.declaration.typeParameter.constraint.type)) || unknownType, type.mapper); + return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* TypeFlags.Unknown */ ? undefined : typeToTypeNodeHelper(originalConstraint, context))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); } return result; } @@ -52682,7 +53479,7 @@ var ts; // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* SymbolFlags.Class */ && !getBaseTypeVariableOfClass(symbol) - && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 226 /* SyntaxKind.ClassExpression */ && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */) || + && !(symbol.valueDeclaration && ts.isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */ && (!ts.isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*computeAliases*/ false).accessibility !== 0 /* SymbolAccessibility.Accessible */)) || symbol.flags & (384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -52948,7 +53745,7 @@ var ts; var id = ids_1[_i]; qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id; } - return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf); + return ts.factory.updateImportTypeNode(root, root.argument, root.assertions, qualifier, typeArguments, root.isTypeOf); } else { // first shift type arguments @@ -53052,7 +53849,7 @@ var ts; anyType : getNonMissingTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* CheckFlags.Late */ && isLateBoundName(propertySymbol.escapedName)) { + if (context.tracker.trackSymbol && isLateBoundName(propertySymbol.escapedName)) { if (propertySymbol.declarations) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { @@ -53197,7 +53994,6 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, @@ -53209,8 +54005,7 @@ var ts; context.encounteredError = true; } context.approximateLength += (name.length + 4); - return ts.factory.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + return ts.factory.createIndexSignature(indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { var _a, _b, _c, _d; @@ -53229,7 +54024,7 @@ var ts; var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* CheckFlags.RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 171 /* SyntaxKind.Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); - var thisParameter = tryGetThisParameterDeclaration(signature, context); + var thisParameter = context.flags & 33554432 /* NodeBuilderFlags.OmitThisParameter */ ? undefined : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { parameters.unshift(thisParameter); } @@ -53262,15 +54057,15 @@ var ts; var node = kind === 174 /* SyntaxKind.CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 175 /* SyntaxKind.ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 168 /* SyntaxKind.MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(modifiers, parameters, /*body*/ undefined) : + kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 317 /* SyntaxKind.JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 179 /* SyntaxKind.FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : kind === 180 /* SyntaxKind.ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : kind === 213 /* SyntaxKind.FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : kind === 214 /* SyntaxKind.ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); @@ -53287,7 +54082,6 @@ var ts; var thisTag = ts.getJSDocThisTag(signature.declaration); if (thisTag && thisTag.typeExpression) { return ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); @@ -53319,7 +54113,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); - var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined; + var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && ts.canHaveModifiers(parameterDeclaration) ? ts.map(ts.getModifiers(parameterDeclaration), ts.factory.cloneNode) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* CheckFlags.RestParameter */; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -53330,21 +54124,27 @@ var ts; ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* CheckFlags.OptionalParameter */; var questionToken = isOptional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined; - var parameterNode = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + var parameterNode = ts.factory.createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { - return elideInitializerAndSetEmitFlags(node); - function elideInitializerAndSetEmitFlags(node) { + return elideInitializerAndPropertyRenamingAndSetEmitFlags(node); + function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) { if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { trackComputedName(node.expression, context.enclosingDeclaration, context); } - var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags); if (ts.isBindingElement(visited)) { - visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, - /*initializer*/ undefined); + if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, + /* propertyName*/ undefined, visited.propertyName, + /*initializer*/ undefined); + } + else { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, + /*initializer*/ undefined); + } } if (!ts.nodeIsSynthesized(visited)) { visited = ts.factory.cloneNode(visited); @@ -53553,6 +54353,7 @@ var ts; return symbol.parent ? ts.factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var _a, _b, _c, _d; var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module var isTypeOf = meaning === 111551 /* SymbolFlags.Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { @@ -53570,6 +54371,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral("import")) ]))); + (_b = (_a = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _b === void 0 ? void 0 : _b.call(_a); } } if (!specifier) { @@ -53589,6 +54391,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral(swappedMode === ts.ModuleKind.ESNext ? "import" : "require")) ]))); + (_d = (_c = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _d === void 0 ? void 0 : _d.call(_c); } } if (!assertion) { @@ -53990,9 +54793,7 @@ var ts; } if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdotToken*/ undefined, "x", /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); @@ -54000,14 +54801,13 @@ var ts; if (ts.isJSDocFunctionType(node)) { if (ts.isJSDocConstructSignature(node)) { var newTypeNode_1; - return ts.factory.createConstructorTypeNode(node.modifiers, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createConstructorTypeNode( + /*modifiers*/ undefined, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } else { return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } @@ -54026,7 +54826,7 @@ var ts; !(ts.length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) { return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); } - return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.assertions, node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { var _a = trackExistingEntityName(node, context, includePrivateSymbol), introducesError = _a.introducesError, result = _a.node; @@ -54078,7 +54878,7 @@ var ts; } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 169 /* SyntaxKind.MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -54139,8 +54939,7 @@ var ts; var name_3 = ns.name; var body = ns.body; if (ts.length(excessExports)) { - ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, + ns = ts.factory.updateModuleDeclaration(ns, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, /*alias*/ undefined, id); })), /*moduleSpecifier*/ undefined)], false)))); @@ -54166,7 +54965,6 @@ var ts; if (ts.length(exports) > 1) { var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; }); statements = __spreadArray(__spreadArray([], nonExports, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), /*moduleSpecifier*/ undefined)], false); @@ -54181,7 +54979,6 @@ var ts; // remove group members from statements and then merge group members and add back to statements statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), true), [ ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier) ], false); @@ -54221,7 +55018,7 @@ var ts; } else { // some items filtered, others not - update the export declaration - statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); + statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); } } return statements; @@ -54286,12 +55083,11 @@ var ts; if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) { var oldContext = context; context = cloneNodeBuilderContext(context); - var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); + serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); if (context.reportedDiagnostic) { oldcontext.reportedDiagnostic = context.reportedDiagnostic; // hoist diagnostic result into outer context } context = oldContext; - return result; } } // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias @@ -54372,7 +55168,6 @@ var ts; && ((_d = type.symbol) === null || _d === void 0 ? void 0 : _d.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, alias, localName)])), 0 /* ModifierFlags.None */); context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* SymbolFlags.Value */); @@ -54405,7 +55200,6 @@ var ts; // ``` // To create an export named `g` that does _not_ shadow the local `g` addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name, localName)])), 0 /* ModifierFlags.None */); needsExportDeclaration = false; @@ -54454,16 +55248,15 @@ var ts; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); if (!resolvedModule) continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); } } } if (needsPostExportDefault) { - addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportAssignment(/*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); } else if (needsExportDeclaration) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* ModifierFlags.None */); } @@ -54531,7 +55324,7 @@ var ts; && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); - addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); + addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; context.enclosingDeclaration = oldEnclosingDecl; } @@ -54547,7 +55340,6 @@ var ts; var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* SymbolFlags.Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), constructSignatures, true), callSignatures, true), members, true)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { @@ -54573,7 +55365,6 @@ var ts; var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* InternalSymbolName.ExportEquals */; }), function (s) { var _a, _b; @@ -54590,13 +55381,11 @@ var ts; return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name === targetName ? undefined : targetName, name); })))]); addResult(ts.factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* NodeFlags.Namespace */), 0 /* ModifierFlags.None */); } } function serializeEnum(symbol, symbolName, modifierFlags) { - addResult(ts.factory.createEnumDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { + addResult(ts.factory.createEnumDeclaration(ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { // TODO: Handle computed names // I hate that to get the initialized value we need to walk back to the declarations here; but there's no // other way to get the possible const value of an enum member that I'm aware of, as the value is cached @@ -54657,7 +55446,7 @@ var ts; // emit akin to the above would be needed. // Add a namespace // Create namespace as non-synthetic so it is usable as an enclosing declaration - var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace, enclosingDeclaration); fakespace.locals = ts.createSymbolTable(props); fakespace.symbol = props[0].parent; @@ -54676,11 +55465,10 @@ var ts; results = oldResults; // replace namespace with synthetic version var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, d.expression, ts.factory.createIdentifier("default" /* InternalSymbolName.Default */))])) : d; }); var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* ModifierFlags.Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced; - fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); + fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); addResult(fakespace, modifierFlags); // namespaces can never be default exported } } @@ -54736,7 +55524,7 @@ var ts; ? getBaseConstructorTypeOfClass(staticType) : anyType; var heritageClauses = __spreadArray(__spreadArray([], !ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], true), !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(117 /* SyntaxKind.ImplementsKeyword */, implementsExpressions)], true); - var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); + var symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties @@ -54754,7 +55542,6 @@ var ts; // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? [ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -54771,12 +55558,11 @@ var ts; ts.isInJSFile(symbol.valueDeclaration) && !ts.some(getSignaturesOfType(staticType, 1 /* SignatureKind.Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? - [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : + [ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : serializeSignatures(1 /* SignatureKind.Construct */, staticType, staticBaseType, 171 /* SyntaxKind.Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), staticMembers, true), constructors, true), publicProperties, true), privateProperties, true)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags); } function getSomeTargetNameFromDeclarations(declarations) { @@ -54828,7 +55614,6 @@ var ts; var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier( /*isTypeOnly*/ false, propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1), /*importClause*/ undefined), 0 /* ModifierFlags.None */); @@ -54852,12 +55637,10 @@ var ts; var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); // 'y' // import _x = require('y'); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* ModifierFlags.None */); // import x = _x.z addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); break; @@ -54874,7 +55657,6 @@ var ts; // an external `import localName = require("whatever")` var isLocalImport = !(target.flags & 512 /* SymbolFlags.ValueModule */) && !ts.isVariableDeclaration(node); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), isLocalImport ? symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false) @@ -54888,7 +55670,6 @@ var ts; break; case 267 /* SyntaxKind.ImportClause */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag @@ -54898,19 +55679,16 @@ var ts; break; case 268 /* SyntaxKind.NamespaceImport */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), /*assertClause*/ undefined), 0 /* ModifierFlags.None */); break; case 274 /* SyntaxKind.NamespaceExport */: addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* ModifierFlags.None */); break; case 270 /* SyntaxKind.ImportSpecifier */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamedImports([ @@ -54949,7 +55727,6 @@ var ts; } function serializeExportSpecifier(localName, targetName, specifier) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* ModifierFlags.None */); } @@ -54990,7 +55767,6 @@ var ts; context.tracker.trackSymbol = function () { return false; }; if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* SymbolFlags.All */))); } else { @@ -55005,7 +55781,6 @@ var ts; // serialize as `import _Ref = t.arg.et; export { _Ref as name }` var varName = getUnusedName(name, symbol); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false)), 0 /* ModifierFlags.None */); serializeExportSpecifier(name, varName); @@ -55036,7 +55811,6 @@ var ts; } if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName))); return true; } @@ -55086,9 +55860,7 @@ var ts; if (p.flags & 98304 /* SymbolFlags.Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SymbolFlags.SetAccessor */) { - result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], @@ -55096,8 +55868,7 @@ var ts; } if (p.flags & 32768 /* SymbolFlags.GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* ModifierFlags.Private */; - result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; @@ -55105,8 +55876,7 @@ var ts; // This is an else/if as accessors and properties can't merge in TS, but might in JS // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* SymbolFlags.Property */ | 3 /* SymbolFlags.Variable */ | 98304 /* SymbolFlags.Accessor */)) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); @@ -55115,8 +55885,7 @@ var ts; var type = getTypeOfSymbol(p); var signatures = getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (flag & 8 /* ModifierFlags.Private */) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, /*type*/ undefined, /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } @@ -55174,8 +55943,7 @@ var ts; } } if (privateProtected) { - return [ts.setTextRange(ts.factory.createConstructorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), + return [ts.setTextRange(ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(privateProtected), /*parameters*/ [], /*body*/ undefined), signatures[0].declaration)]; } @@ -55874,7 +56642,7 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 32768 /* TypeFlags.Undefined */) ? getNonUndefinedType(type) : type; + return strictNullChecks && !(getTypeFacts(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 16777216 /* TypeFacts.IsUndefined */) ? getNonUndefinedType(type) : type; } return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)], 2 /* UnionReduction.Subtype */)); } @@ -56275,7 +57043,7 @@ var ts; (resolvedSymbol || symbol).exports.forEach(function (s, name) { var _a; var exportedMember = members_4.get(name); - if (exportedMember && exportedMember !== s) { + if (exportedMember && exportedMember !== s && !(s.flags & 2097152 /* SymbolFlags.Alias */)) { if (s.flags & 111551 /* SymbolFlags.Value */ && exportedMember.flags & 111551 /* SymbolFlags.Value */) { // If the member has an additional value-like declaration, union the types from the two declarations, // but issue an error if they occurred in two different files. The purpose is to support a JS file with @@ -56309,6 +57077,17 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.indexInfos); + if (initialSize === members_4.size) { + if (type.aliasSymbol) { + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = type.aliasTypeArguments; + } + if (ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */) { + result.aliasSymbol = type.symbol; + var args = getTypeArguments(type); + result.aliasTypeArguments = ts.length(args) ? args : undefined; + } + } result.objectFlags |= (ts.getObjectFlags(type) & 4096 /* ObjectFlags.JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* SymbolFlags.Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { result.objectFlags |= 16777216 /* ObjectFlags.IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type @@ -56360,11 +57139,7 @@ var ts; if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAny(element, anyType); } - // When we're including the pattern in the type (an indication we're obtaining a contextual type), we - // use the non-inferrable any type. Inference will never directly infer this type, but it is possible - // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases, - // widening of the binding pattern type substitutes a regular any for the non-inferrable any. - return includePatternInType ? nonInferrableAnyType : anyType; + return anyType; } // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { @@ -57365,7 +58140,7 @@ var ts; error(declaration.typeExpression.type, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } else { - error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + error(ts.isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } } links.declaredType = type; @@ -58669,6 +59444,9 @@ var ts; else if (type.objectFlags & 32 /* ObjectFlags.Mapped */) { resolveMappedTypeMembers(type); } + else { + ts.Debug.fail("Unhandled object type " + ts.Debug.formatObjectFlags(type.objectFlags)); + } } else if (type.flags & 1048576 /* TypeFlags.Union */) { resolveUnionTypeMembers(type); @@ -58676,6 +59454,9 @@ var ts; else if (type.flags & 2097152 /* TypeFlags.Intersection */) { resolveIntersectionTypeMembers(type); } + else { + ts.Debug.fail("Unhandled type " + ts.Debug.formatTypeFlags(type.flags)); + } } return type; } @@ -58863,7 +59644,7 @@ var ts; } } } - else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { hasDisjointDomainType = true; } } @@ -58875,12 +59656,13 @@ var ts; // intersection operation to reduce the union constraints. for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { var t = types_6[_a]; - if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { constraints = ts.append(constraints, t); } } } - return getIntersectionType(constraints); + // The source types were normalized; ensure the result is normalized too. + return getNormalizedType(getIntersectionType(constraints), /*writing*/ false); } return undefined; } @@ -58991,7 +59773,7 @@ var ts; } if (t.flags & 268435456 /* TypeFlags.StringMapping */) { var constraint = getBaseConstraint(t.type); - return constraint ? getStringMappingType(t.symbol, constraint) : stringType; + return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType; } if (t.flags & 8388608 /* TypeFlags.IndexedAccess */) { if (isMappedTypeGenericIndexedAccess(t)) { @@ -59077,7 +59859,7 @@ var ts; var objectType; return !!(type.flags & 8388608 /* TypeFlags.IndexedAccess */ && ts.getObjectFlags(objectType = type.objectType) & 32 /* ObjectFlags.Mapped */ && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && - !objectType.declaration.questionToken && !objectType.declaration.nameType); + !(getMappedTypeModifiers(objectType) & 8 /* MappedTypeModifiers.ExcludeOptional */) && !objectType.declaration.nameType); } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, @@ -59356,12 +60138,12 @@ var ts; * @param type a type to look up property from * @param name a name of property to look up in a given type */ - function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment) { + function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) { type = getReducedApparentType(type); if (type.flags & 524288 /* TypeFlags.Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { + if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) { return symbol; } if (skipObjectFunctionPropertyAugment) @@ -59467,12 +60249,15 @@ var ts; // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(declaration) { + var _a; var result; - for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { - var node = _a[_i]; + for (var _i = 0, _b = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _b.length; _i++) { + var node = _b[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); } - return result; + return (result === null || result === void 0 ? void 0 : result.length) ? result + : ts.isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) === null || _a === void 0 ? void 0 : _a.typeParameters + : undefined; } function symbolsToArray(symbols) { var result = []; @@ -60023,8 +60808,7 @@ var ts; var _a; var inferences; if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { - for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; + var _loop_15 = function (declaration) { if (declaration.parent.kind === 190 /* SyntaxKind.InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the @@ -60032,12 +60816,12 @@ var ts; // present, we form an intersection of the inferred constraint types. var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; if (grandParent.kind === 178 /* SyntaxKind.TypeReference */ && !omitTypeReferences) { - var typeReference = grandParent; - var typeParameters = getTypeParametersForTypeReference(typeReference); - if (typeParameters) { - var index = typeReference.typeArguments.indexOf(childTypeParameter); - if (index < typeParameters.length) { - var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + var typeReference_1 = grandParent; + var typeParameters_1 = getTypeParametersForTypeReference(typeReference_1); + if (typeParameters_1) { + var index = typeReference_1.typeArguments.indexOf(childTypeParameter); + if (index < typeParameters_1.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters_1[index]); if (declaredConstraint) { // Type parameter constraints can reference other type parameters so // constraints need to be instantiated. If instantiation produces the @@ -60045,7 +60829,9 @@ var ts; // type Foo = [T, U]; // type Bar = T extends Foo ? Foo : T; // the instantiated constraint for U is X, so we discard that inference. - var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var mapper = makeDeferredTypeMapper(typeParameters_1, typeParameters_1.map(function (_, index) { return function () { + return getEffectiveTypeArgumentAtIndex(typeReference_1, typeParameters_1, index); + }; })); var constraint = instantiateType(declaredConstraint, mapper); if (constraint !== typeParameter) { inferences = ts.append(inferences, constraint); @@ -60083,6 +60869,10 @@ var ts; inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); } } + }; + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + _loop_15(declaration); } } return inferences && getIntersectionType(inferences); @@ -60145,13 +60935,13 @@ var ts; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type - // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // of an object literal or a non-inferrable type. This is because there are operations in the type checker // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type = types_8[_i]; - if (!(type.flags & excludeKinds)) { + if (excludeKinds === undefined || !(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } } @@ -60163,7 +60953,7 @@ var ts; if (!type) { type = createObjectType(4 /* ObjectFlags.Reference */, target.symbol); target.instantiations.set(id, type); - type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0; type.target = target; type.resolvedTypeArguments = typeArguments; } @@ -60971,7 +61761,7 @@ var ts; var lastRequiredIndex = -1; var firstRestIndex = -1; var lastOptionalOrRestIndex = -1; - var _loop_15 = function (i) { + var _loop_16 = function (i) { var type = elementTypes[i]; var flags = target.elementFlags[i]; if (flags & 8 /* ElementFlags.Variadic */) { @@ -61001,7 +61791,7 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - var state_4 = _loop_15(i); + var state_4 = _loop_16(i); if (typeof state_4 === "object") return state_4.value; } @@ -61197,7 +61987,7 @@ var ts; var templates = ts.filter(types, isPatternLiteralType); if (templates.length) { var i = types.length; - var _loop_16 = function () { + var _loop_17 = function () { i--; var t = types[i]; if (t.flags & 128 /* TypeFlags.StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { @@ -61205,7 +61995,7 @@ var ts; } }; while (i > 0) { - _loop_16(); + _loop_17(); } } } @@ -61282,14 +62072,14 @@ var ts; var namedUnions = []; addNamedUnions(namedUnions, types); var reducedTypes = []; - var _loop_17 = function (t) { + var _loop_18 = function (t) { if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) { reducedTypes.push(t); } }; for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) { var t = typeSet_1[_i]; - _loop_17(t); + _loop_18(t); } if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) { return namedUnions[0]; @@ -61424,7 +62214,7 @@ var ts; } return includes; } - function removeRedundantPrimitiveTypes(types, includes) { + function removeRedundantSupertypes(types, includes) { var i = types.length; while (i > 0) { i--; @@ -61432,7 +62222,9 @@ var ts; var remove = t.flags & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || t.flags & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || t.flags & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */; + t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + t.flags & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + isEmptyAnonymousObjectType(t) && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -61554,7 +62346,7 @@ var ts; // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types, aliasSymbol, aliasTypeArguments, noSupertypeReduction) { var typeMembershipMap = new ts.Map(); var includes = addTypesToIntersection(typeMembershipMap, 0, types); var typeSet = ts.arrayFrom(typeMembershipMap.values()); @@ -61591,11 +62383,11 @@ var ts; if (includes & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || includes & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || includes & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */) { - removeRedundantPrimitiveTypes(typeSet, includes); - } - if (includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 524288 /* TypeFlags.Object */) { - ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + includes & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */) { + if (!noSupertypeReduction) + removeRedundantSupertypes(typeSet, includes); } if (includes & 262144 /* TypeFlags.IncludesMissingType */) { typeSet[typeSet.indexOf(undefinedType)] = missingType; @@ -61634,8 +62426,9 @@ var ts; } var constituents = getCrossProductIntersections(typeSet); // We attach a denormalized origin type when at least one constituent of the cross-product union is an - // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions). - var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; + // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions) and + // the denormalized origin has fewer constituents than the union itself. + var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; result = getUnionType(constituents, 1 /* UnionReduction.Literal */, aliasSymbol, aliasTypeArguments, origin); } } @@ -61678,11 +62471,21 @@ var ts; } return intersections; } + function getConstituentCount(type) { + return !(type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) || type.aliasSymbol ? 1 : + type.flags & 1048576 /* TypeFlags.Union */ && type.origin ? getConstituentCount(type.origin) : + getConstituentCountOfTypes(type.types); + } + function getConstituentCountOfTypes(types) { + return ts.reduceLeft(types, function (n, t) { return n + getConstituentCount(t); }, 0); + } function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var aliasSymbol = getAliasSymbolForTypeNode(node); - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var types = ts.map(node.types, getTypeFromTypeNode); + var noSupertypeReduction = types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType; + links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); } return links.resolvedType; } @@ -61810,19 +62613,22 @@ var ts; * to reduce the resulting type if possible (since only intersections with conflicting literal-typed properties are reducible). */ function isPossiblyReducibleByInstantiation(type) { - return ts.some(type.types, function (t) { - var uniqueFilled = getUniqueLiteralFilledInstantiation(t); - return getReducedType(uniqueFilled) !== uniqueFilled; - }); + var uniqueFilled = getUniqueLiteralFilledInstantiation(type); + return getReducedType(uniqueFilled) !== uniqueFilled; + } + function shouldDeferIndexType(type) { + return !!(type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || + isGenericTupleType(type) || + isGenericMappedType(type) && !hasDistributiveNameType(type) || + type.flags & 1048576 /* TypeFlags.Union */ && ts.some(type.types, isPossiblyReducibleByInstantiation) || + type.flags & 2097152 /* TypeFlags.Intersection */ && maybeTypeOfKind(type, 465829888 /* TypeFlags.Instantiable */) && ts.some(type.types, isEmptyAnonymousObjectType)); } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } type = getReducedType(type); - return type.flags & 1048576 /* TypeFlags.Union */ ? isPossiblyReducibleByInstantiation(type) - ? getIndexTypeForGenericType(type, stringsOnly) - : getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + return shouldDeferIndexType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + type.flags & 1048576 /* TypeFlags.Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : + type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ ? getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) : type === wildcardType ? wildcardType : type.flags & 2 /* TypeFlags.Unknown */ ? neverType : @@ -61948,9 +62754,12 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type; + // 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; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -61961,6 +62770,15 @@ var ts; } return str; } + function applyTemplateStringMapping(symbol, texts, types) { + switch (intrinsicTypeKinds.get(symbol.escapedName)) { + case 0 /* IntrinsicTypeKind.Uppercase */: return [texts.map(function (t) { return t.toUpperCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 1 /* IntrinsicTypeKind.Lowercase */: return [texts.map(function (t) { return t.toLowerCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 2 /* IntrinsicTypeKind.Capitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toUpperCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + case 3 /* IntrinsicTypeKind.Uncapitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toLowerCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + } + return [texts, types]; + } function getStringMappingTypeForGenericType(symbol, type) { var id = "".concat(getSymbolId(symbol), ",").concat(getTypeId(type)); var result = stringMappingTypes.get(id); @@ -62062,21 +62880,28 @@ var ts; getFlowTypeOfReference(accessExpression, propType) : propType; } - if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName) && +propName >= 0) { + if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName)) { + var index = +propName; if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 16 /* AccessFlags.NoTupleBoundsCheck */)) { var indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { + if (index < 0) { + error(indexNode, ts.Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); + return undefinedType; + } error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); } else { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } } - errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, function (t) { - var restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; - }); + if (index >= 0) { + errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); + return mapType(objectType, function (t) { + var restType = getRestTypeOfTupleType(t) || undefinedType; + return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; + }); + } } } if (!(indexType.flags & 98304 /* TypeFlags.Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* TypeFlags.StringLike */ | 296 /* TypeFlags.NumberLike */ | 12288 /* TypeFlags.ESSymbolLike */)) { @@ -62202,7 +63027,7 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -62340,7 +63165,7 @@ var ts; function substituteIndexedMappedType(objectType, index) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]); var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return instantiateType(getTemplateTypeFromMappedType(objectType.target || objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) { if (accessFlags === void 0) { accessFlags = 0 /* AccessFlags.None */; } @@ -62488,7 +63313,7 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_18 = function () { + var _loop_19 = function () { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; @@ -62609,7 +63434,7 @@ var ts; // 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_5 = _loop_18(); + var state_5 = _loop_19(); if (typeof state_5 === "object") return state_5.value; if (state_5 === "break") @@ -62710,6 +63535,7 @@ var ts; } } function getTypeFromImportTypeNode(node) { + var _a; var links = getNodeLinks(node); if (!links.resolvedType) { if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments @@ -62729,6 +63555,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } + var isExportEquals = !!((_a = innerModuleSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* InternalSymbolName.ExportEquals */)); var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); @@ -62740,9 +63567,11 @@ var ts; // That, in turn, ultimately uses `getPropertyOfType` on the type of the symbol, which differs slightly from // the `exports` lookup process that only looks up namespace members which is used for most type references var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace)); - var next = node.isTypeOf - ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText) - : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var symbolFromVariable = node.isTypeOf || ts.isInJSFile(node) && isExportEquals + ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ true) + : undefined; + var symbolFromModule = node.isTypeOf ? undefined : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var next = symbolFromModule !== null && symbolFromModule !== void 0 ? symbolFromModule : symbolFromVariable; if (!next) { error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); return links.resolvedType = errorType; @@ -63239,7 +64068,7 @@ var ts; switch (mapper.kind) { case 0 /* TypeMapKind.Simple */: return type === mapper.source ? mapper.target : type; - case 1 /* TypeMapKind.Array */: + case 1 /* TypeMapKind.Array */: { var sources = mapper.sources; var targets = mapper.targets; for (var i = 0; i < sources.length; i++) { @@ -63248,25 +64077,39 @@ var ts; } } return type; - case 2 /* TypeMapKind.Function */: + } + case 2 /* TypeMapKind.Deferred */: { + var sources = mapper.sources; + var targets = mapper.targets; + for (var i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets[i](); + } + } + return type; + } + case 3 /* TypeMapKind.Function */: return mapper.func(type); - case 3 /* TypeMapKind.Composite */: - case 4 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: + case 5 /* TypeMapKind.Merged */: var t1 = getMappedType(type, mapper.mapper1); - return t1 !== type && mapper.kind === 3 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); + return t1 !== type && mapper.kind === 4 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); } } function makeUnaryTypeMapper(source, target) { - return { kind: 0 /* TypeMapKind.Simple */, source: source, target: target }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 0 /* TypeMapKind.Simple */, source: source, target: target }); } function makeArrayTypeMapper(sources, targets) { - return { kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }); } - function makeFunctionTypeMapper(func) { - return { kind: 2 /* TypeMapKind.Function */, func: func }; + function makeFunctionTypeMapper(func, debugInfo) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 3 /* TypeMapKind.Function */, func: func, debugInfo: ts.Debug.isDebugging ? debugInfo : undefined }); + } + function makeDeferredTypeMapper(sources, targets) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 2 /* TypeMapKind.Deferred */, sources: sources, targets: targets }); } function makeCompositeTypeMapper(kind, mapper1, mapper2) { - return { kind: kind, mapper1: mapper1, mapper2: mapper2 }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: kind, mapper1: mapper1, mapper2: mapper2 }); } function createTypeEraser(sources) { return createTypeMapper(sources, /*targets*/ undefined); @@ -63276,19 +64119,20 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(context, index) { - return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; }); + var forwardInferences = context.inferences.slice(index); + return createTypeMapper(ts.map(forwardInferences, function (i) { return i.typeParameter; }), ts.map(forwardInferences, function () { return unknownType; })); } function combineTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(3 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; } function mergeTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; } function prependTypeMapping(source, target, mapper) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); } function appendTypeMapping(mapper, source, target) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); } function getRestrictiveTypeParameter(tp) { return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), @@ -63554,6 +64398,7 @@ var ts; result.mapper = mapper; result.aliasSymbol = aliasSymbol || type.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + result.objectFlags |= result.aliasTypeArguments ? getPropagatingFlagsOfTypes(result.aliasTypeArguments) : 0; return result; } function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { @@ -64202,7 +65047,7 @@ var ts; }); } function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; if (isTupleLikeType(source)) { return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); @@ -64269,7 +65114,7 @@ var ts; }); } function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); } @@ -64356,7 +65201,7 @@ var ts; var sourceSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && - (getFalsyFlags(sourceType) & 98304 /* TypeFlags.Nullable */) === (getFalsyFlags(targetType) & 98304 /* TypeFlags.Nullable */); + (getTypeFacts(sourceType) & 50331648 /* TypeFacts.IsUndefinedOrNull */) === (getTypeFacts(targetType) & 50331648 /* TypeFacts.IsUndefinedOrNull */); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* SignatureCheckMode.StrictArity */) | (strictVariance ? 2 /* SignatureCheckMode.StrictCallback */ : 1 /* SignatureCheckMode.BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* SignatureCheckMode.Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); @@ -64468,6 +65313,20 @@ var ts; return !!(ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && (type.members && isEmptyResolvedType(type) || type.symbol && type.symbol.flags & 2048 /* SymbolFlags.TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0)); } + function isUnknownLikeUnionType(type) { + if (strictNullChecks && type.flags & 1048576 /* TypeFlags.Union */) { + if (!(type.objectFlags & 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */)) { + var types = type.types; + type.objectFlags |= 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */ | (types.length >= 3 && types[0].flags & 32768 /* TypeFlags.Undefined */ && + types[1].flags & 65536 /* TypeFlags.Null */ && ts.some(types, isEmptyAnonymousObjectType) ? 67108864 /* ObjectFlags.IsUnknownLikeUnion */ : 0); + } + return !!(type.objectFlags & 67108864 /* ObjectFlags.IsUnknownLikeUnion */); + } + return false; + } + function containsUndefinedType(type) { + return !!((type.flags & 1048576 /* TypeFlags.Union */ ? type.types[0] : type).flags & 32768 /* TypeFlags.Undefined */); + } function isStringIndexSignatureOnlyType(type) { return type.flags & 524288 /* TypeFlags.Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) || @@ -64547,7 +65406,7 @@ var ts; return true; if (s & 65536 /* TypeFlags.Null */ && (!strictNullChecks && !(t & 3145728 /* TypeFlags.UnionOrIntersection */) || t & 65536 /* TypeFlags.Null */)) return true; - if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */) + if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(ts.getObjectFlags(source) & 8192 /* ObjectFlags.FreshLiteral */))) return true; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* TypeFlags.Any */) @@ -64557,6 +65416,9 @@ var ts; // bit-flag enum types sometimes look like literal enum types with numeric literal values. if (s & (8 /* TypeFlags.Number */ | 256 /* TypeFlags.NumberLiteral */) && !(s & 1024 /* TypeFlags.EnumLiteral */) && (t & 32 /* TypeFlags.Enum */ || relation === assignableRelation && t & 256 /* TypeFlags.NumberLiteral */ && t & 1024 /* TypeFlags.EnumLiteral */)) return true; + // Anything is assignable to a union containing undefined, null, and {} + if (isUnknownLikeUnionType(target)) + return true; } return false; } @@ -64599,16 +65461,27 @@ var ts; function getNormalizedType(type, writing) { while (true) { var t = isFreshLiteralType(type) ? type.regularType : - ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getReducedType(type) : + ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : + type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* TypeFlags.Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* TypeFlags.Simplifiable */ ? getSimplifiedType(type, writing) : type; - t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) - break; + return t; type = t; } + } + function getNormalizedUnionOrIntersectionType(type, writing) { + var reduced = getReducedType(type); + if (reduced !== type) { + return reduced; + } + if (type.flags & 2097152 /* TypeFlags.Intersection */) { + var normalizedTypes = ts.sameMap(type.types, function (t) { return getNormalizedType(t, writing); }); + if (normalizedTypes !== type.types) { + return getIntersectionType(normalizedTypes); + } + } return type; } /** @@ -64840,7 +65713,7 @@ var ts; ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable"); generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); } - if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperType && target !== markerSubType) { + if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperTypeForCheck && target !== markerSubTypeForCheck) { var constraint = getBaseConstraintOfType(target); var needsOriginalSource = void 0; if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) { @@ -65055,6 +65928,7 @@ var ts; return 0 /* Ternary.False */; } function reportErrorResults(originalSource, originalTarget, source, target, headMessage) { + var _a, _b; var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; @@ -65095,6 +65969,14 @@ var ts; return; } reportRelationError(headMessage, source, target); + if (source.flags & 262144 /* TypeFlags.TypeParameter */ && ((_b = (_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) === null || _b === void 0 ? void 0 : _b[0]) && !getConstraintOfType(source)) { + var syntheticParam = cloneTypeParameter(source); + syntheticParam.constraint = instantiateType(target, makeUnaryTypeMapper(source, syntheticParam)); + if (hasNonCircularBaseConstraint(syntheticParam)) { + var targetConstraintString = typeToString(target, source.symbol.declarations[0]); + associateRelatedInfo(ts.createDiagnosticForNode(source.symbol.declarations[0], ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint, targetConstraintString)); + } + } } function traceUnionsOrIntersectionsTooLarge(source, target) { if (!ts.tracing) { @@ -65147,7 +66029,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_19 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -65210,7 +66092,7 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_6 = _loop_19(prop); + var state_6 = _loop_20(prop); if (typeof state_6 === "object") return state_6.value; } @@ -65232,7 +66114,7 @@ var ts; return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* TypeFlags.Primitive */) && !(target.flags & 131068 /* TypeFlags.Primitive */)); } if (target.flags & 2097152 /* TypeFlags.Intersection */) { - return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* IntersectionState.Target */); + return typeRelatedToEachType(source, target, reportErrors, 2 /* IntersectionState.Target */); } // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the // constraints of all non-primitive types in the source into a new intersection. We do this because the @@ -65442,10 +66324,10 @@ var ts; // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component var saved = entry & 24 /* RelationComparisonResult.ReportsMask */; if (saved & 8 /* RelationComparisonResult.ReportsUnmeasurable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers)); + instantiateType(source, reportUnmeasurableMapper); } if (saved & 16 /* RelationComparisonResult.ReportsUnreliable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } } return entry & 1 /* RelationComparisonResult.Succeeded */ ? -1 /* Ternary.True */ : 0 /* Ternary.False */; @@ -65545,13 +66427,40 @@ var ts; return result; } 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 */)) { + // 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 + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + // This also handles type parameters, as a type parameter with a union constraint compared against a union + // 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 && 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) { + resetErrorInfo(saveErrorInfo); + } + 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; - var saveErrorInfo = captureErrorCalculationState(); var sourceFlags = source.flags; var targetFlags = target.flags; if (relation === identityRelation) { @@ -65597,29 +66506,6 @@ var ts; if (result = unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState)) { return result; } - if (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */) { - // 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 - // when the target is a union type. Another is when the intersection contains types belonging - // to one of the disjoint domains. For example, given type variables T and U, each with the - // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and - // we need to check this constraint against a union on the target side. Also, given a type - // variable V constrained to 'string | number', 'V & number' has a combined constraint of - // 'string & number | number & number' which reduces to just 'number'. - // This also handles type parameters, as a type parameter with a union constraint compared against a union - // 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 && 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 - if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - } // The ordered decomposition above doesn't handle all cases. Specifically, we also need to handle: // Source is instantiable (e.g. source has union or intersection constraint). // Source is an object, target is a union (e.g. { a, b: boolean } <=> { a, b: true } | { a, b: false }). @@ -65663,6 +66549,20 @@ var ts; } } } + if (relation === comparableRelation && sourceFlags & 262144 /* TypeFlags.TypeParameter */) { + // This is a carve-out in comparability to essentially forbid comparing a type parameter + // 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 */) { + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { + return result; + } + constraint = getConstraintOfTypeParameter(constraint); + } + } + return 0 /* Ternary.False */; + } } else if (targetFlags & 4194304 /* TypeFlags.Index */) { var targetType_1 = target.type; @@ -65726,7 +66626,6 @@ var ts; result &= isRelatedTo(source.indexType, target.indexType, 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } if (reportErrors) { @@ -65829,7 +66728,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } var c = target; @@ -65844,7 +66742,6 @@ var ts; if (result = skipTrue ? -1 /* Ternary.True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false)) { result &= skipFalse ? -1 /* Ternary.True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false); if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65857,31 +66754,29 @@ var ts; } // Report unreliable variance for type variables referenced in template literal type placeholders. // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* Ternary.True */; } } + else if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + if (!(source.flags & 268435456 /* TypeFlags.StringMapping */)) { + if (isMemberOfStringMapping(source, target)) { + return -1 /* Ternary.True */; + } + } + } if (sourceFlags & 8650752 /* TypeFlags.TypeVariable */) { // IndexedAccess comparisons are handled above in the `targetFlags & TypeFlage.IndexedAccess` branch if (!(sourceFlags & 8388608 /* TypeFlags.IndexedAccess */ && targetFlags & 8388608 /* TypeFlags.IndexedAccess */)) { - var constraint = getConstraintOfType(source); - if (!constraint || (sourceFlags & 262144 /* TypeFlags.TypeParameter */ && constraint.flags & 1 /* TypeFlags.Any */)) { - // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* TypeFlags.NonPrimitive */), 3 /* RecursionFlags.Both */)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } + var constraint = getConstraintOfType(source) || unknownType; // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed - else if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && constraint !== unknownType && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { return result; } if (isMappedTypeGenericIndexedAccess(source)) { @@ -65890,7 +66785,6 @@ var ts; var indexConstraint = getConstraintOfType(source.indexType); if (indexConstraint) { if (result = isRelatedTo(getIndexedAccessType(source.objectType, indexConstraint), target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65899,7 +66793,6 @@ var ts; } else if (sourceFlags & 4194304 /* TypeFlags.Index */) { if (result = isRelatedTo(keyofConstraintType, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65907,22 +66800,22 @@ var ts; if (!(targetFlags & 134217728 /* TypeFlags.TemplateLiteral */)) { var constraint = getBaseConstraintOfType(source); if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } } else if (sourceFlags & 268435456 /* TypeFlags.StringMapping */) { - if (targetFlags & 268435456 /* TypeFlags.StringMapping */ && source.symbol === target.symbol) { + if (targetFlags & 268435456 /* TypeFlags.StringMapping */) { + if (source.symbol !== target.symbol) { + return 0 /* Ternary.False */; + } if (result = isRelatedTo(source.type, target.type, 3 /* RecursionFlags.Both */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } else { var constraint = getBaseConstraintOfType(source); if (constraint && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65931,7 +66824,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } if (targetFlags & 16777216 /* TypeFlags.Conditional */) { @@ -65954,7 +66846,6 @@ var ts; result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65965,7 +66856,6 @@ var ts; var distributiveConstraint = hasNonCircularBaseConstraint(source) ? getConstraintOfDistributiveConditionalType(source) : undefined; if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65975,7 +66865,6 @@ var ts; var defaultConstraint = getDefaultConstraintOfConditionalType(source); if (defaultConstraint) { if (result = isRelatedTo(defaultConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65988,7 +66877,6 @@ var ts; if (isGenericMappedType(target)) { if (isGenericMappedType(source)) { if (result = mappedTypeRelatedTo(source, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -66126,18 +67014,6 @@ var ts; } } } - function reportUnmeasurableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); - } - return p; - } - function reportUnreliableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); - } - return p; - } // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice // that S and T are contra-variant whereas X and Y are co-variant. @@ -66147,7 +67023,7 @@ var ts; if (modifiersRelated) { var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); - var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); + var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMapper : reportUnreliableMapper); if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* RecursionFlags.Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { @@ -66201,11 +67077,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_20 = 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_21 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -66221,7 +67097,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_8 = _loop_21(i); + var state_8 = _loop_22(i); switch (state_8) { case "continue-outer": continue outer; } @@ -66235,7 +67111,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_7 = _loop_20(combination); + var state_7 = _loop_21(combination); if (typeof state_7 === "object") return state_7.value; } @@ -66683,7 +67559,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, makeFunctionTypeMapper(reportUnreliableMarkers)); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, reportUnreliableMapper); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -66838,7 +67714,7 @@ var ts; return typeCouldHaveTopLevelSingletonTypes(constraint); } } - return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */); + return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */); } function getExactOptionalUnassignableProperties(source, target) { if (isTupleType(source) && isTupleType(target)) @@ -66942,7 +67818,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_22 = 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 */ : @@ -66978,12 +67854,12 @@ var ts; } variances.push(variance); }; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - _loop_22(tp); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var tp = typeParameters_2[_i]; + _loop_23(tp); } links.variances = variances; - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); } return links.variances; } @@ -67321,35 +68197,33 @@ var ts; var commonBaseType; for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { var t = types_13[_i]; - var baseType = getBaseTypeOfLiteralType(t); - if (!commonBaseType) { - commonBaseType = baseType; - } - if (baseType === t || baseType !== commonBaseType) { - return false; + if (!(t.flags & 131072 /* TypeFlags.Never */)) { + var baseType = getBaseTypeOfLiteralType(t); + commonBaseType !== null && commonBaseType !== void 0 ? commonBaseType : (commonBaseType = baseType); + if (baseType === t || baseType !== commonBaseType) { + return false; + } } } return true; } - // When the candidate types are all literal types with the same base type, return a union - // of those literal types. Otherwise, return the leftmost type for which no type to the - // right is a supertype. - function getSupertypeOrUnion(types) { - if (types.length === 1) { - return types[0]; - } - return literalTypesWithSameBaseType(types) ? - getUnionType(types) : - ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + function getCombinedTypeFlags(types) { + return ts.reduceLeft(types, function (flags, t) { return flags | (t.flags & 1048576 /* TypeFlags.Union */ ? getCombinedTypeFlags(t.types) : t.flags); }, 0); } function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); + if (types.length === 1) { + return types[0]; } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* TypeFlags.Nullable */); }); - return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* TypeFlags.Nullable */) : - getUnionType(types, 2 /* UnionReduction.Subtype */); + // Remove nullable types from each of the candidates. + var primaryTypes = strictNullChecks ? ts.sameMap(types, function (t) { return filterType(t, function (u) { return !(u.flags & 98304 /* TypeFlags.Nullable */); }); }) : types; + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + var superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? + getUnionType(primaryTypes) : + ts.reduceLeft(primaryTypes, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + // Add any nullable types that occurred in the candidates back to the result. + return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & 98304 /* TypeFlags.Nullable */); } // Return the leftmost type for which no type to the right is a subtype. function getCommonSubtype(types) { @@ -67453,9 +68327,14 @@ var ts; type.flags & 256 /* TypeFlags.NumberLiteral */ ? numberType : type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? bigintType : type.flags & 512 /* TypeFlags.BooleanLiteral */ ? booleanType : - type.flags & 1048576 /* TypeFlags.Union */ ? mapType(type, getBaseTypeOfLiteralType) : + type.flags & 1048576 /* TypeFlags.Union */ ? getBaseTypeOfLiteralTypeUnion(type) : type; } + function getBaseTypeOfLiteralTypeUnion(type) { + var _a; + var key = "B".concat(getTypeId(type)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); + } function getWidenedLiteralType(type) { return type.flags & 1024 /* TypeFlags.EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : type.flags & 128 /* TypeFlags.StringLiteral */ && isFreshLiteralType(type) ? stringType : @@ -67536,29 +68415,8 @@ var ts; var value = _a.value; return value.base10Value === "0"; } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - result |= getFalsyFlags(t); - } - return result; - } - // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null - // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns - // no flags for all other types (including non-falsy literal types). - function getFalsyFlags(type) { - return type.flags & 1048576 /* TypeFlags.Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? type.value === "" ? 128 /* TypeFlags.StringLiteral */ : 0 : - type.flags & 256 /* TypeFlags.NumberLiteral */ ? type.value === 0 ? 256 /* TypeFlags.NumberLiteral */ : 0 : - type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* TypeFlags.BigIntLiteral */ : 0 : - type.flags & 512 /* TypeFlags.BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* TypeFlags.BooleanLiteral */ : 0 : - type.flags & 117724 /* TypeFlags.PossiblyFalsy */; - } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 117632 /* TypeFlags.DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* TypeFlags.DefinitelyFalsy */); }) : - type; + return filterType(type, function (t) { return !!(getTypeFacts(t) & 4194304 /* TypeFacts.Truthy */); }); } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); @@ -67593,20 +68451,15 @@ var ts; return type.flags & 32768 /* TypeFlags.Undefined */ ? type : getUnionType([type, isProperty ? missingType : undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { - // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates - // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' - // that isn't eliminated by a NonNullable instantiation. - var reducedType = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* SymbolFlags.TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? - getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : - reducedType; + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : + getIntersectionType([type, emptyObjectType]); } function getNonNullableType(type) { - return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + return strictNullChecks ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; @@ -67660,12 +68513,13 @@ var ts; * with no call or construct signatures. */ function isObjectTypeWithInferableIndex(type) { + var objectFlags = ts.getObjectFlags(type); return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* SymbolFlags.ObjectLiteral */ | 2048 /* SymbolFlags.TypeLiteral */ | 384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */)) !== 0 && !(type.symbol.flags & 32 /* SymbolFlags.Class */) - && !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & 4194304 /* ObjectFlags.ObjectRestType */) || !!(objectFlags & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* CheckFlags.Readonly */); @@ -67998,27 +68852,29 @@ var ts; signature: signature, flags: flags, compareTypes: compareTypes, - mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }), - nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }), + mapper: reportUnmeasurableMapper, + nonFixingMapper: reportUnmeasurableMapper, }; + context.mapper = makeFixingMapperForContext(context); + context.nonFixingMapper = makeNonFixingMapperForContext(context); return context; } - function mapToInferredType(context, t, fix) { - var inferences = context.inferences; - for (var i = 0; i < inferences.length; i++) { - var inference = inferences[i]; - if (t === inference.typeParameter) { - if (fix && !inference.isFixed) { - // Before we commit to a particular inference (and thus lock out any further inferences), - // we infer from any intra-expression inference sites we have collected. - inferFromIntraExpressionSites(context); - clearCachedInferences(inferences); - inference.isFixed = true; - } - return getInferredType(context, i); + function makeFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (inference, i) { return function () { + if (!inference.isFixed) { + // Before we commit to a particular inference (and thus lock out any further inferences), + // we infer from any intra-expression inference sites we have collected. + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; } - } - return t; + return getInferredType(context, i); + }; })); + } + function makeNonFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (_, i) { return function () { + return getInferredType(context, i); + }; })); } function clearCachedInferences(inferences) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { @@ -68287,13 +69143,40 @@ var ts; return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen); } - function isValidBigIntString(s) { + /** + * Tests whether the provided string can be parsed as a number. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting number matches the input when converted back to a string. + */ + function isValidNumberString(s, roundTripOnly) { + if (s === "") + return false; + var n = +s; + return isFinite(n) && (!roundTripOnly || "" + n === s); + } + /** + * @param text a valid bigint string excluding a trailing `n`, but including a possible prefix `-`. Use `isValidBigIntString(text, roundTripOnly)` before calling this function. + */ + function parseBigIntLiteralType(text) { + var negative = text.startsWith("-"); + var base10Value = ts.parsePseudoBigInt("".concat(negative ? text.slice(1) : text, "n")); + return getBigIntLiteralType({ negative: negative, base10Value: base10Value }); + } + /** + * Tests whether the provided string can be parsed as a bigint. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting bigint matches the input when converted back to a string. + */ + function isValidBigIntString(s, roundTripOnly) { + if (s === "") + return false; var scanner = ts.createScanner(99 /* ScriptTarget.ESNext */, /*skipTrivia*/ false); var success = true; scanner.setOnError(function () { return success = false; }); scanner.setText(s + "n"); var result = scanner.scan(); - if (result === 40 /* SyntaxKind.MinusToken */) { + var negative = result === 40 /* SyntaxKind.MinusToken */; + if (negative) { result = scanner.scan(); } var flags = scanner.getTokenFlags(); @@ -68302,7 +69185,33 @@ var ts; // * a bigint can be scanned, and that when it is scanned, it is // * the full length of the input string (so the scanner is one character beyond the augmented input length) // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) - return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */); + return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */) + && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); + } + function isMemberOfStringMapping(source, target) { + if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + return true; + } + if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { + return isTypeAssignableTo(source, target); + } + if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + // We need to see whether applying the same mappings of the target + // onto the source would produce an identical type *and* that + // it's compatible with the inner-most non-string-mapped type. + // + // The intuition here is that if same mappings don't affect the source at all, + // and the source is compatible with the unmapped target, then they must + // still reside in the same domain. + var mappingStack = []; + while (target.flags & 268435456 /* TypeFlags.StringMapping */) { + mappingStack.unshift(target.symbol); + target = target.type; + } + var mappedSource = ts.reduceLeft(mappingStack, function (memo, value) { return getStringMappingType(value, memo); }, source); + return mappedSource === source && isMemberOfStringMapping(source, target); + } + return false; } function isValidTypeForTemplateLiteralPlaceholder(source, target) { if (source === target || target.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */)) { @@ -68310,9 +69219,10 @@ var ts; } if (source.flags & 128 /* TypeFlags.StringLiteral */) { var value = source.value; - return !!(target.flags & 8 /* TypeFlags.Number */ && value !== "" && isFinite(+value) || - target.flags & 64 /* TypeFlags.BigInt */ && value !== "" && isValidBigIntString(value) || - target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName); + return !!(target.flags & 8 /* TypeFlags.Number */ && isValidNumberString(value, /*roundTripOnly*/ false) || + target.flags & 64 /* TypeFlags.BigInt */ && isValidBigIntString(value, /*roundTripOnly*/ false) || + target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName || + target.flags & 268435456 /* TypeFlags.StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target)); } if (source.flags & 134217728 /* TypeFlags.TemplateLiteral */) { var texts = source.texts; @@ -68435,10 +69345,13 @@ var ts; propagationType = savePropagationType; return; } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - // Source and target are types originating in the same generic type alias declaration. - // Simply infer from source type arguments to target type arguments. - inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + if (source.aliasSymbol && source.aliasSymbol === target.aliasSymbol) { + if (source.aliasTypeArguments) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + } + // And if there weren't any type arguments, there's no reason to run inference as the types must be the same. return; } if (source === target && source.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { @@ -68494,18 +69407,26 @@ var ts; target = getActualTypeVariable(target); } if (target.flags & 8650752 /* TypeFlags.TypeVariable */) { - // If target is a type parameter, make an inference, unless the source type contains - // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). - // Because the anyFunctionType is internal, it should not be exposed to the user by adding - // it as an inference candidate. Hopefully, a better candidate will come along that does - // not contain anyFunctionType when we come back to this argument for its second round - // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard - // when constructing types from type parameters that had no inference candidates). - if (source === nonInferrableAnyType || source === silentNeverType || (priority & 128 /* InferencePriority.ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + // Skip inference if the source is "blocked", which is used by the language service to + // prevent inference on nodes currently being edited. + if (isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); if (inference) { + // If target is a type parameter, make an inference, unless the source type contains + // a "non-inferrable" type. Types with this flag set are markers used to prevent inference. + // + // For example: + // - anyFunctionType is a wildcard type that's used to avoid contextually typing functions; + // it's internal, so should not be exposed to the user by adding it as a candidate. + // - autoType (and autoArrayType) is a special "any" used in control flow; like anyFunctionType, + // it's internal and should not be observable. + // - silentNeverType is returned by getInferredType when instantiating a generic function for + // inference (and a type variable has no mapping). + // + // This flag is infectious; if we produce Box (where never is silentNeverType), Box is + // also non-inferrable. if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) { return; } @@ -68562,15 +69483,11 @@ var ts; inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target)); } else if (source.flags & 4194304 /* TypeFlags.Index */ && target.flags & 4194304 /* TypeFlags.Index */) { - contravariant = !contravariant; - inferFromTypes(source.type, target.type); - contravariant = !contravariant; + inferFromContravariantTypes(source.type, target.type); } else if ((isLiteralType(source) || source.flags & 4 /* TypeFlags.String */) && target.flags & 4194304 /* TypeFlags.Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - contravariant = !contravariant; - inferWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); - contravariant = !contravariant; + inferFromContravariantTypesWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); } else if (source.flags & 8388608 /* TypeFlags.IndexedAccess */ && target.flags & 8388608 /* TypeFlags.IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -68583,10 +69500,7 @@ var ts; } else if (source.flags & 33554432 /* TypeFlags.Substitution */) { inferFromTypes(source.baseType, target); - var oldPriority = priority; - priority |= 4 /* InferencePriority.SubstituteSource */; - inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority - priority = oldPriority; + inferWithPriority(source.substitute, target, 4 /* InferencePriority.SubstituteSource */); // Make substitute inference at a lower priority } else if (target.flags & 16777216 /* TypeFlags.Conditional */) { invokeOnce(source, target, inferToConditionalType); @@ -68636,6 +69550,18 @@ var ts; inferFromTypes(source, target); priority = savePriority; } + function inferFromContravariantTypesWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromContravariantTypes(source, target); + priority = savePriority; + } + function inferToMultipleTypesWithPriority(source, targets, targetFlags, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferToMultipleTypes(source, targets, targetFlags); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -68700,10 +69626,13 @@ var ts; } } function inferFromContravariantTypes(source, target) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + function inferFromContravariantTypesIfStrictFunctionTypes(source, target) { if (strictFunctionTypes || priority & 1024 /* InferencePriority.AlwaysStrict */) { - contravariant = !contravariant; - inferFromTypes(source, target); - contravariant = !contravariant; + inferFromContravariantTypes(source, target); } else { inferFromTypes(source, target); @@ -68722,8 +69651,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var type = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* TypeFlags.Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -68867,11 +69796,8 @@ var ts; inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else { - var savePriority = priority; - priority |= contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; - inferToMultipleTypes(source, targetTypes, target.flags); - priority = savePriority; + inferToMultipleTypesWithPriority(source, targetTypes, target.flags, contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0); } } function inferToTemplateLiteralType(source, target) { @@ -68884,8 +69810,57 @@ 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_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 + // allowed template literal placeholder types, infer from a literal type corresponding to the constraint. + if (source_1.flags & 128 /* TypeFlags.StringLiteral */ && target_3.flags & 8650752 /* TypeFlags.TypeVariable */) { + var inferenceContext = getInferenceInfoForType(target_3); + var constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : undefined; + if (constraint && !isTypeAny(constraint)) { + var constraintTypes = constraint.flags & 1048576 /* TypeFlags.Union */ ? constraint.types : [constraint]; + var allTypeFlags_1 = ts.reduceLeft(constraintTypes, function (flags, t) { return flags | t.flags; }, 0); + // If the constraint contains `string`, we don't need to look for a more preferred type + if (!(allTypeFlags_1 & 4 /* TypeFlags.String */)) { + var str_1 = source_1.value; + // If the type contains `number` or a number literal and the string isn't a valid number, exclude numbers + if (allTypeFlags_1 & 296 /* TypeFlags.NumberLike */ && !isValidNumberString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~296 /* TypeFlags.NumberLike */; + } + // If the type contains `bigint` or a bigint literal and the string isn't a valid bigint, exclude bigints + if (allTypeFlags_1 & 2112 /* TypeFlags.BigIntLike */ && !isValidBigIntString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~2112 /* TypeFlags.BigIntLike */; + } + // for each type in the constraint, find the highest priority matching type + var matchingType = ts.reduceLeft(constraintTypes, function (left, right) { + return !(right.flags & allTypeFlags_1) ? left : + left.flags & 4 /* TypeFlags.String */ ? left : right.flags & 4 /* TypeFlags.String */ ? source_1 : + left.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? left : right.flags & 134217728 /* TypeFlags.TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source_1, right) ? source_1 : + left.flags & 268435456 /* TypeFlags.StringMapping */ ? left : right.flags & 268435456 /* TypeFlags.StringMapping */ && str_1 === applyStringMapping(right.symbol, str_1) ? source_1 : + left.flags & 128 /* TypeFlags.StringLiteral */ ? left : right.flags & 128 /* TypeFlags.StringLiteral */ && right.value === str_1 ? right : + left.flags & 8 /* TypeFlags.Number */ ? left : right.flags & 8 /* TypeFlags.Number */ ? getNumberLiteralType(+str_1) : + left.flags & 32 /* TypeFlags.Enum */ ? left : right.flags & 32 /* TypeFlags.Enum */ ? getNumberLiteralType(+str_1) : + left.flags & 256 /* TypeFlags.NumberLiteral */ ? left : right.flags & 256 /* TypeFlags.NumberLiteral */ && right.value === +str_1 ? right : + left.flags & 64 /* TypeFlags.BigInt */ ? left : right.flags & 64 /* TypeFlags.BigInt */ ? parseBigIntLiteralType(str_1) : + left.flags & 2048 /* TypeFlags.BigIntLiteral */ ? left : right.flags & 2048 /* TypeFlags.BigIntLiteral */ && ts.pseudoBigIntToString(right.value) === str_1 ? right : + left.flags & 16 /* TypeFlags.Boolean */ ? left : right.flags & 16 /* TypeFlags.Boolean */ ? str_1 === "true" ? trueType : str_1 === "false" ? falseType : booleanType : + left.flags & 512 /* TypeFlags.BooleanLiteral */ ? left : right.flags & 512 /* TypeFlags.BooleanLiteral */ && right.intrinsicName === str_1 ? right : + left.flags & 32768 /* TypeFlags.Undefined */ ? left : right.flags & 32768 /* TypeFlags.Undefined */ && right.intrinsicName === str_1 ? right : + left.flags & 65536 /* TypeFlags.Null */ ? left : right.flags & 65536 /* TypeFlags.Null */ && right.intrinsicName === str_1 ? right : + left; + }, neverType); + if (!(matchingType.flags & 131072 /* TypeFlags.Never */)) { + inferFromTypes(matchingType, target_3); + return "continue"; + } + } + } + } + inferFromTypes(source_1, target_3); + }; for (var i = 0; i < types.length; i++) { - inferFromTypes(matches ? matches[i] : neverType, types[i]); + _loop_24(i); } } } @@ -68999,20 +69974,17 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } - function inferFromSignature(source, target, skipParameters) { - if (!skipParameters) { - var saveBivariant = bivariant; - var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; - // Once we descend into a bivariant signature we remain bivariant for all nested inferences - bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; - applyToParameterTypes(source, target, inferFromContravariantTypes); - bivariant = saveBivariant; - } + function inferFromSignature(source, target) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; + applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); + bivariant = saveBivariant; applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { @@ -69259,6 +70231,15 @@ var ts; var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); return key && key + "." + propName; } + break; + case 201 /* SyntaxKind.ObjectBindingPattern */: + case 202 /* SyntaxKind.ArrayBindingPattern */: + case 256 /* SyntaxKind.FunctionDeclaration */: + case 213 /* SyntaxKind.FunctionExpression */: + case 214 /* SyntaxKind.ArrowFunction */: + case 169 /* SyntaxKind.MethodDeclaration */: + // Handle pseudo-references originating in getNarrowedTypeOfSymbol. + return "".concat(getNodeId(node), "#").concat(getTypeId(declaredType)); } return undefined; } @@ -69403,7 +70384,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_23 = 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) { @@ -69427,9 +70408,9 @@ var ts; } } }; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - var state_9 = _loop_23(type); + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var type = types_15[_i]; + var state_9 = _loop_25(type); if (typeof state_9 === "object") return state_9.value; } @@ -69518,23 +70499,25 @@ var ts; // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 131072 /* TypeFlags.Never */) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType)) { - reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types - } - // Our crude heuristic produces an invalid result in some cases: see GH#26130. - // For now, when that happens, we give up and don't narrow at all. (This also - // means we'll never narrow for erroneous assignments where the assigned type - // is not assignable to the declared type.) - if (isTypeAssignableTo(assignedType, reducedType)) { - return reducedType; - } + var _a; + if (declaredType === assignedType) { + return declaredType; } - return declaredType; + if (assignedType.flags & 131072 /* TypeFlags.Never */) { + return assignedType; + } + var key = "A".concat(getTypeId(declaredType), ",").concat(getTypeId(assignedType)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); + } + function getAssignmentReducedTypeWorker(declaredType, assignedType) { + var filteredType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + // Ensure that we narrow to fresh types if the assignment is a fresh boolean literal type. + var reducedType = assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType; + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType; } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype @@ -69543,14 +70526,16 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type, ignoreObjects) { - if (ignoreObjects === void 0) { ignoreObjects = false; } + function getTypeFacts(type) { + if (type.flags & (2097152 /* TypeFlags.Intersection */ | 465829888 /* TypeFlags.Instantiable */)) { + type = getBaseConstraintOfType(type) || unknownType; + } var flags = type.flags; - if (flags & 4 /* TypeFlags.String */) { + if (flags & (4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */)) { return strictNullChecks ? 16317953 /* TypeFacts.StringStrictFacts */ : 16776705 /* TypeFacts.StringFacts */; } - if (flags & 128 /* TypeFlags.StringLiteral */) { - var isEmpty = type.value === ""; + if (flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */)) { + var isEmpty = flags & 128 /* TypeFlags.StringLiteral */ && type.value === ""; return strictNullChecks ? isEmpty ? 12123649 /* TypeFacts.EmptyStringStrictFacts */ : 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* TypeFacts.EmptyStringFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; @@ -69582,20 +70567,20 @@ var ts; (type === falseType || type === regularFalseType) ? 12580616 /* TypeFacts.FalseFacts */ : 16774920 /* TypeFacts.TrueFacts */; } if (flags & 524288 /* TypeFlags.Object */) { - if (ignoreObjects) { - return 16768959 /* TypeFacts.AndFactsMask */; // This is the identity element for computing type facts of intersection. - } return ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && isEmptyObjectType(type) ? - strictNullChecks ? 16318463 /* TypeFacts.EmptyObjectStrictFacts */ : 16777215 /* TypeFacts.EmptyObjectFacts */ : + strictNullChecks ? 83427327 /* TypeFacts.EmptyObjectStrictFacts */ : 83886079 /* TypeFacts.EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* TypeFacts.FunctionStrictFacts */ : 16728000 /* TypeFacts.FunctionFacts */ : strictNullChecks ? 7888800 /* TypeFacts.ObjectStrictFacts */ : 16736160 /* TypeFacts.ObjectFacts */; } - if (flags & (16384 /* TypeFlags.Void */ | 32768 /* TypeFlags.Undefined */)) { - return 9830144 /* TypeFacts.UndefinedFacts */; + if (flags & 16384 /* TypeFlags.Void */) { + return 9830144 /* TypeFacts.VoidFacts */; + } + if (flags & 32768 /* TypeFlags.Undefined */) { + return 26607360 /* TypeFacts.UndefinedFacts */; } if (flags & 65536 /* TypeFlags.Null */) { - return 9363232 /* TypeFacts.NullFacts */; + return 42917664 /* TypeFacts.NullFacts */; } if (flags & 12288 /* TypeFlags.ESSymbolLike */) { return strictNullChecks ? 7925520 /* TypeFacts.SymbolStrictFacts */ : 16772880 /* TypeFacts.SymbolFacts */; @@ -69606,37 +70591,56 @@ var ts; if (flags & 131072 /* TypeFlags.Never */) { return 0 /* TypeFacts.None */; } - if (flags & 465829888 /* TypeFlags.Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : - strictNullChecks ? 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; - } if (flags & 1048576 /* TypeFlags.Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* TypeFacts.None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* TypeFacts.None */); } if (flags & 2097152 /* TypeFlags.Intersection */) { - // When an intersection contains a primitive type we ignore object type constituents as they are - // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. - ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */)); - return getIntersectionTypeFacts(type, ignoreObjects); + return getIntersectionTypeFacts(type); } - return 16777215 /* TypeFacts.All */; + return 83886079 /* TypeFacts.UnknownFacts */; } - function getIntersectionTypeFacts(type, ignoreObjects) { + function getIntersectionTypeFacts(type) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + var ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */); // When computing the type facts of an intersection type, certain type facts are computed as `and` // and others are computed as `or`. var oredFacts = 0 /* TypeFacts.None */; - var andedFacts = 16777215 /* TypeFacts.All */; + var andedFacts = 134217727 /* TypeFacts.All */; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - var f = getTypeFacts(t, ignoreObjects); - oredFacts |= f; - andedFacts &= f; + if (!(ignoreObjects && t.flags & 524288 /* TypeFlags.Object */)) { + var f = getTypeFacts(t); + oredFacts |= f; + andedFacts &= f; + } } - return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 16768959 /* TypeFacts.AndFactsMask */; + return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 134209471 /* TypeFacts.AndFactsMask */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } + // This function is similar to getTypeWithFacts, except that in strictNullChecks mode it replaces type + // unknown with the union {} | null | undefined (and reduces that accordingly), and it intersects remaining + // instantiable types with {}, {} | null, or {} | undefined in order to remove null and/or undefined. + function getAdjustedTypeWithFacts(type, facts) { + var reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 /* TypeFlags.Unknown */ ? unknownUnionType : type, facts)); + if (strictNullChecks) { + switch (facts) { + case 524288 /* TypeFacts.NEUndefined */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ ? getIntersectionType([t, getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ && !maybeTypeOfKind(reduced, 65536 /* TypeFlags.Null */) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t; }); + case 1048576 /* TypeFacts.NENull */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ ? getIntersectionType([t, getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ && !maybeTypeOfKind(reduced, 32768 /* TypeFlags.Undefined */) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t; }); + case 2097152 /* TypeFacts.NEUndefinedOrNull */: + case 4194304 /* TypeFacts.Truthy */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 262144 /* TypeFacts.EQUndefinedOrNull */ ? getGlobalNonNullableTypeInstantiation(t) : t; }); + } + } + return reduced; + } + function recombineUnknownType(type) { + return type === unknownUnionType ? unknownType : type; + } function getTypeWithDefault(type, defaultExpression) { return defaultExpression ? getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : @@ -69791,19 +70795,17 @@ var ts; } return links.switchTypes; } - function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) { + // Get the type names from all cases in a switch on `typeof`. The default clause and/or duplicate type names are + // represented as undefined. Return undefined if one or more case clause expressions are not string literals. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + if (ts.some(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 289 /* SyntaxKind.CaseClause */ && !ts.isStringLiteralLike(clause.expression); })) { + return undefined; + } var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 289 /* SyntaxKind.CaseClause */) { - if (ts.isStringLiteralLike(clause.expression)) { - witnesses.push(clause.expression.text); - continue; - } - return ts.emptyArray; - } - if (retainDefault) - witnesses.push(/*explicitDefaultStatement*/ undefined); + var text = clause.kind === 289 /* SyntaxKind.CaseClause */ ? clause.expression.text : undefined; + witnesses.push(text && !ts.contains(witnesses, text) ? text : undefined); } return witnesses; } @@ -69885,8 +70887,8 @@ var ts; var types = origin && origin.flags & 1048576 /* TypeFlags.Union */ ? origin.types : type.types; var mappedTypes; var changed = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; var mapped = t.flags & 1048576 /* TypeFlags.Union */ ? mapType(t, mapper, noReductions) : mapper(t); changed || (changed = t !== mapped); if (mapped) { @@ -69972,8 +70974,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (!(t.flags & 131072 /* TypeFlags.Never */)) { if (!(ts.getObjectFlags(t) & 256 /* ObjectFlags.EvolvingArray */)) { return false; @@ -70434,7 +71436,7 @@ var ts; } // for (const _ in ref) acts as a nonnull on ref if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 243 /* SyntaxKind.ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { - return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); } // Assignment doesn't affect reference return undefined; @@ -70694,7 +71696,7 @@ var ts; if (isEvolvingArrayTypeList(types)) { return getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))); } - var result = getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + var result = recombineUnknownType(getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction)); if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* TypeFlags.Union */ && ts.arraysEqual(result.types, declaredType.types)) { return declaredType; } @@ -70796,11 +71798,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return type.flags & 2 /* TypeFlags.Unknown */ && assumeTrue ? nonNullUnknownType : - getTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); + return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -70922,7 +71923,7 @@ var ts; var targetType = ts.hasStaticModifier(ts.Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows: @@ -70940,7 +71941,7 @@ var ts; // Note that we include any and unknown in the exclusion test because their domain includes null and undefined. var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) || equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* TypeFlags.AnyOrUnknown */ | nullableFlags)); }); - return removeNullable ? getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; + return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* TypeFlags.Any */) { @@ -70950,9 +71951,6 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (assumeTrue && (type.flags & 2 /* TypeFlags.Unknown */) && (operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 35 /* SyntaxKind.ExclamationEqualsToken */) && (valueType.flags & 65536 /* TypeFlags.Null */)) { - return getUnionType([nullType, undefinedType]); - } if ((type.flags & 2 /* TypeFlags.Unknown */) && assumeTrue && (operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */ || operator === 37 /* SyntaxKind.ExclamationEqualsEqualsToken */)) { if (valueType.flags & (131068 /* TypeFlags.Primitive */ | 67108864 /* TypeFlags.NonPrimitive */)) { return valueType; @@ -70972,7 +71970,7 @@ var ts; valueType.flags & 65536 /* TypeFlags.Null */ ? assumeTrue ? 131072 /* TypeFacts.EQNull */ : 1048576 /* TypeFacts.NENull */ : assumeTrue ? 65536 /* TypeFacts.EQUndefined */ : 524288 /* TypeFacts.NEUndefined */; - return type.flags & 2 /* TypeFlags.Unknown */ && facts & (1048576 /* TypeFacts.NENull */ | 2097152 /* TypeFacts.NEUndefinedOrNull */) ? nonNullUnknownType : getTypeWithFacts(type, facts); + return getAdjustedTypeWithFacts(type, facts); } if (assumeTrue) { var filterFn = operator === 34 /* SyntaxKind.EqualsEqualsToken */ ? @@ -70993,24 +71991,13 @@ var ts; var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } - if (type.flags & 1 /* TypeFlags.Any */ && literal.text === "function") { - return type; - } - if (assumeTrue && type.flags & 2 /* TypeFlags.Unknown */ && literal.text === "object") { - // The non-null unknown type is used to track whether a previous narrowing operation has removed the null type - // from the unknown type. For example, the expression `x && typeof x === 'object'` first narrows x to the non-null - // unknown type, and then narrows that to the non-primitive type. - return type === nonNullUnknownType ? nonPrimitiveType : getUnionType([nonPrimitiveType, nullType]); - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 128 /* TypeFacts.TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */; - var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text); - return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts); + return assumeTrue ? + narrowTypeByTypeName(type, literal.text) : + getTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */); } function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); @@ -71057,97 +72044,52 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* TypeFlags.Never */ ? defaultType : getUnionType([caseType, defaultType]); } - function getImpliedTypeFromTypeofGuard(type, text) { - switch (text) { - case "function": - return type.flags & 1 /* TypeFlags.Any */ ? type : globalFunctionType; - case "object": - return type.flags & 2 /* TypeFlags.Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; - default: - return typeofTypesByName.get(text); - } - } - // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are - // super-types of the implied guard will be retained in the final type: this is because type-facts only - // filter. Instead, we would like to replace those union constituents with the more precise type implied by - // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not - // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to - // filtering by type-facts. - function narrowUnionMemberByTypeof(candidate) { - return function (type) { - if (isTypeSubtypeOf(type, candidate)) { - return type; - } - if (isTypeSubtypeOf(candidate, type)) { - return candidate; - } - if (type.flags & 465829888 /* TypeFlags.Instantiable */) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(candidate, constraint)) { - return getIntersectionType([type, candidate]); - } - } - return type; - }; + function narrowTypeByTypeName(type, typeName) { + switch (typeName) { + case "string": return narrowTypeByTypeFacts(type, stringType, 1 /* TypeFacts.TypeofEQString */); + case "number": return narrowTypeByTypeFacts(type, numberType, 2 /* TypeFacts.TypeofEQNumber */); + case "bigint": return narrowTypeByTypeFacts(type, bigintType, 4 /* TypeFacts.TypeofEQBigInt */); + case "boolean": return narrowTypeByTypeFacts(type, booleanType, 8 /* TypeFacts.TypeofEQBoolean */); + case "symbol": return narrowTypeByTypeFacts(type, esSymbolType, 16 /* TypeFacts.TypeofEQSymbol */); + case "object": return type.flags & 1 /* TypeFlags.Any */ ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32 /* TypeFacts.TypeofEQObject */), narrowTypeByTypeFacts(type, nullType, 131072 /* TypeFacts.EQNull */)]); + case "function": return type.flags & 1 /* TypeFlags.Any */ ? type : narrowTypeByTypeFacts(type, globalFunctionType, 64 /* TypeFacts.TypeofEQFunction */); + case "undefined": return narrowTypeByTypeFacts(type, undefinedType, 65536 /* TypeFacts.EQUndefined */); + } + return narrowTypeByTypeFacts(type, nonPrimitiveType, 128 /* TypeFacts.TypeofEQHostObject */); + } + function narrowTypeByTypeFacts(type, impliedType, facts) { + return mapType(type, function (t) { + // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate + // the constituent based on its type facts. We use the strict subtype relation because it treats `object` + // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, + // but are classified as "function" according to `typeof`. + return isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? getTypeFacts(t) & facts ? t : neverType : + // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied + // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. + isTypeSubtypeOf(impliedType, t) ? impliedType : + // Neither the constituent nor the implied type is a subtype of the other, however their domains may still + // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate + // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. + getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : + neverType; + }); } function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { - var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true); - if (!switchWitnesses.length) { + var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!witnesses) { return type; } - // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause - var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); - var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); - var clauseWitnesses; - var switchFacts; - if (defaultCaseLocation > -1) { - // We no longer need the undefined denoting an explicit default case. Remove the undefined and - // fix-up clauseStart and clauseEnd. This means that we don't have to worry about undefined in the - // witness array. - var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); - // The adjusted clause start and end after removing the `default` statement. - var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; - var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; - clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); - switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); - } - else { - clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); - switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); - } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause. + var defaultIndex = ts.findIndex(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 290 /* SyntaxKind.DefaultClause */; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultIndex >= clauseStart && defaultIndex < clauseEnd); if (hasDefaultClause) { - return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + // In the default clause we filter constituents down to those that are not-equal to all handled cases. + var notEqualFacts_1 = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); + return filterType(type, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }); } - /* - The implied type is the raw type suggested by a - value being caught in this clause. - - When the clause contains a default case we ignore - the implied type and try to narrow using any facts - we can learn: see `switchFacts`. - - Example: - switch (typeof x) { - case 'number': - case 'string': break; - default: break; - case 'number': - case 'boolean': break - } - - In the first clause (case `number` and `string`) the - implied type is number | string. - - In the default clause we de not compute an implied type. - - In the third clause (case `number` and `boolean`) - the naive implied type is number | boolean, however - we use the type facts to narrow the implied type to - boolean. We know that number cannot be selected - because it is caught in the first clause. - */ - var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts); - return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts); + // In the non-default cause we create a union of the type narrowed by each of the listed cases. + var clauseWitnesses = witnesses.slice(clauseStart, clauseEnd); + return getUnionType(ts.map(clauseWitnesses, function (text) { return text ? narrowTypeByTypeName(type, text) : neverType; })); } function isMatchingConstructorReference(expr) { return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || @@ -71198,7 +72140,7 @@ var ts; var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } @@ -71232,29 +72174,48 @@ var ts; if (!nonConstructorTypeInUnion) return type; } - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { + function getNarrowedType(type, candidate, assumeTrue, checkDerived) { + var _a; + var key = type.flags & 1048576 /* TypeFlags.Union */ ? "N".concat(getTypeId(type), ",").concat(getTypeId(candidate), ",").concat((assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)) : undefined; + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); + } + function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) { + var isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf; if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - // If the current type is a union type, remove all constituents that couldn't be instances of - // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 1048576 /* TypeFlags.Union */) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 131072 /* TypeFlags.Never */)) { - return assignableType; - } + if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { + return candidate; } - // If the candidate type is a subtype of the target type, narrow to the candidate type. - // Otherwise, if the target type is assignable to the candidate type, keep the target type. - // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate - // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the - // two types. - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); + // We first attempt to filter the current type, narrowing constituents as appropriate and removing + // constituents that are unrelated to the candidate. + var keyPropertyName = type.flags & 1048576 /* TypeFlags.Union */ ? getKeyPropertyName(type) : undefined; + var narrowedType = mapType(candidate, function (c) { + // If a discriminant property is available, use that to reduce the type. + var discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName); + var matching = discriminant && getConstituentTypeForKeyType(type, discriminant); + // For each constituent t in the current type, if t and and c are directly related, pick the most + // specific of the two. When t and c are related in both directions, we prefer c for type predicates + // because that is the asserted type, but t for `instanceof` because generics aren't reflected in + // prototype object types. + var directlyRelated = mapType(matching || type, checkDerived ? + function (t) { return isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType; } : + function (t) { return isTypeSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : neverType; }); + // If no constituents are directly related, create intersections for any generic constituents that + // are related by constraint. + return directlyRelated.flags & 131072 /* TypeFlags.Never */ ? + mapType(type, function (t) { return maybeTypeOfKind(t, 465829888 /* TypeFlags.Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType; }) : + directlyRelated; + }); + // If filtering produced a non-empty type, return that. Otherwise, pick the most specific of the two + // based on assignability, or as a last resort produce an intersection. + return !(narrowedType.flags & 131072 /* TypeFlags.Never */) ? narrowedType : + isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -71282,15 +72243,15 @@ var ts; var predicateArgument = getTypePredicateArgument(predicate, callExpression); if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + return getNarrowedType(type, predicate.type, assumeTrue, /*checkDerived*/ false); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && !(getTypeFacts(predicate.type) & 65536 /* TypeFacts.EQUndefined */)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(predicateArgument, type); if (access) { - return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); + return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, /*checkDerived*/ false); }); } } } @@ -71343,7 +72304,7 @@ var ts; } function narrowTypeByOptionality(type, expr, assumePresent) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -71429,8 +72390,8 @@ var ts; var annotationIncludesUndefined = strictNullChecks && declaration.kind === 164 /* SyntaxKind.Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 32768 /* TypeFlags.Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* TypeFlags.Undefined */); + getTypeFacts(declaredType) & 16777216 /* TypeFacts.IsUndefined */ && + !(getTypeFacts(checkExpression(declaration.initializer)) & 16777216 /* TypeFacts.IsUndefined */); popTypeResolution(); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* TypeFacts.NEUndefined */) : declaredType; } @@ -71451,7 +72412,9 @@ var ts; !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { - return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); + return type.flags & 2097152 /* TypeFlags.Intersection */ ? + ts.some(type.types, isGenericTypeWithUnionConstraint) : + !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); } function isGenericTypeWithoutNullableConstraint(type) { return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* TypeFlags.Nullable */)); @@ -71465,7 +72428,7 @@ var ts; !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 64 /* CheckMode.RestBindingElement */ ? getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) - : getContextualType(node)); + : getContextualType(node, /*contextFlags*/ undefined)); return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { @@ -71479,7 +72442,7 @@ var ts; var substituteConstraints = !(checkMode && checkMode & 2 /* CheckMode.Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); - return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* TypeFlags.Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (n) { @@ -71627,9 +72590,7 @@ var ts; getNodeLinks(container).flags |= 8192 /* NodeCheckFlags.CaptureArguments */; return getTypeOfSymbol(symbol); } - // We should only mark aliases as referenced if there isn't a local value declaration - // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that - if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + if (shouldMarkIdentifierAliasReferenced(node)) { markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); @@ -71756,13 +72717,32 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function shouldMarkIdentifierAliasReferenced(node) { + var _a; + var parent = node.parent; + if (parent) { + // A property access expression LHS? checkPropertyAccessExpression will handle that. + if (ts.isPropertyAccessExpression(parent) && parent.expression === node) { + return false; + } + // Next two check for an identifier inside a type only export. + if (ts.isExportSpecifier(parent) && parent.isTypeOnly) { + return false; + } + var greatGrandparent = (_a = parent.parent) === null || _a === void 0 ? void 0 : _a.parent; + if (greatGrandparent && ts.isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) { + return false; + } + } + return true; + } function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } @@ -71890,7 +72870,7 @@ var ts; } function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) { if (ts.isPropertyDeclaration(container) && ts.hasStaticModifier(container) && - container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.length(container.parent.decorators)) { + container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.hasDecorators(container.parent)) { error(thisExpression, ts.Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); } } @@ -72312,7 +73292,7 @@ var ts; // We have an object literal method. Check if the containing object literal has a contextual type // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in // any directly enclosing object literals. - var contextualType = getApparentTypeOfContextualType(containingLiteral); + var contextualType = getApparentTypeOfContextualType(containingLiteral, /*contextFlags*/ undefined); var literal = containingLiteral; var type = contextualType; while (type) { @@ -72324,7 +73304,7 @@ var ts; break; } literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); + type = getApparentTypeOfContextualType(literal, /*contextFlags*/ undefined); } // There was no contextual ThisType for the containing object literal, so the contextual type // for 'this' is the non-null form of the contextual type for the containing object literal or @@ -72381,7 +73361,7 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } - function getContextualTypeForVariableLikeDeclaration(declaration) { + function getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -72390,18 +73370,18 @@ var ts; case 164 /* SyntaxKind.Parameter */: return getContextuallyTypedParameterType(declaration); case 203 /* SyntaxKind.BindingElement */: - return getContextualTypeForBindingElement(declaration); + return getContextualTypeForBindingElement(declaration, contextFlags); case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isStatic(declaration)) { - return getContextualTypeForStaticPropertyDeclaration(declaration); + return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); } // By default, do nothing and return undefined - only the above cases have context implied by a parent } } - function getContextualTypeForBindingElement(declaration) { + function getContextualTypeForBindingElement(declaration, contextFlags) { var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - var parentType = getContextualTypeForVariableLikeDeclaration(parent) || + var parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== 203 /* SyntaxKind.BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 64 /* CheckMode.RestBindingElement */ : 0 /* CheckMode.Normal */); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; @@ -72417,8 +73397,8 @@ var ts; return getTypeOfPropertyOfType(parentType, text); } } - function getContextualTypeForStaticPropertyDeclaration(declaration) { - var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent); + function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) { + var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags); if (!parentType) return undefined; return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName); @@ -72434,29 +73414,32 @@ var ts; function getContextualTypeForInitializerExpression(node, contextFlags) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var result = getContextualTypeForVariableLikeDeclaration(declaration); + var result = getContextualTypeForVariableLikeDeclaration(declaration, contextFlags); if (result) { return result; } - if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable + if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name) && declaration.name.elements.length > 0) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } } return undefined; } - function getContextualTypeForReturnExpression(node) { + function getContextualTypeForReturnExpression(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { var functionFlags = ts.getFunctionFlags(func); if (functionFlags & 1 /* FunctionFlags.Generator */) { // Generator or AsyncGenerator function - var use = functionFlags & 2 /* FunctionFlags.Async */ ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; - var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined); - if (!iterationTypes) { + var isAsyncGenerator_1 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_1); }); + } + var iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + if (!iterationReturnType) { return undefined; } - contextualReturnType = iterationTypes.returnType; + contextualReturnType = iterationReturnType; // falls through to unwrap Promise for AsyncGenerators } if (functionFlags & 2 /* FunctionFlags.Async */) { // Async function or AsyncGenerator function @@ -72477,15 +73460,19 @@ var ts; } return undefined; } - function getContextualTypeForYieldOperand(node) { + function getContextualTypeForYieldOperand(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { + var isAsyncGenerator_2 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_2); }); + } return node.asteriskToken ? contextualReturnType - : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, isAsyncGenerator_2); } } return undefined; @@ -72505,14 +73492,14 @@ var ts; } function getContextualIterationType(kind, functionDecl) { var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* FunctionFlags.Async */); - var contextualReturnType = getContextualReturnType(functionDecl); + var contextualReturnType = getContextualReturnType(functionDecl, /*contextFlags*/ undefined); if (contextualReturnType) { return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || undefined; } return undefined; } - function getContextualReturnType(functionDecl) { + function getContextualReturnType(functionDecl, contextFlags) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed var returnType = getReturnTypeFromAnnotation(functionDecl); @@ -72527,7 +73514,7 @@ var ts; } var iife = ts.getImmediatelyInvokedFunctionExpression(functionDecl); if (iife) { - return getContextualType(iife); + return getContextualType(iife, contextFlags); } return undefined; } @@ -72601,6 +73588,14 @@ var ts; var lhsType = getTypeOfExpression(e.expression); return ts.isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText); } + if (ts.isElementAccessExpression(e)) { + var propType = checkExpressionCached(e.argumentExpression); + if (!isTypeUsableAsPropertyName(propType)) { + return undefined; + } + var lhsType = getTypeOfExpression(e.expression); + return getPropertyOfType(lhsType, getPropertyNameFromType(propType)); + } return undefined; function tryGetPrivateIdentifierPropertyOfType(type, id) { var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id); @@ -72622,7 +73617,7 @@ var ts; if (decl && (ts.isPropertyDeclaration(decl) || ts.isPropertySignature(decl))) { var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); return (overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper)) || - (decl.initializer && getTypeOfExpression(binaryExpression.left)); + (ts.isPropertyDeclaration(decl) ? decl.initializer && getTypeOfExpression(binaryExpression.left) : undefined); } if (kind === 0 /* AssignmentDeclarationKind.None */) { return getTypeOfExpression(binaryExpression.left); @@ -72755,7 +73750,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; - var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element, contextFlags); if (propertyAssignmentType) { return propertyAssignmentType; } @@ -72790,8 +73785,8 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined; } - function getContextualTypeForChildJsxExpression(node, child) { - var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + function getContextualTypeForChildJsxExpression(node, child, contextFlags) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); // JSX expression is in children of JSX Element, we will look for an "children" attribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { @@ -72809,27 +73804,27 @@ var ts; } }, /*noReductions*/ true)); } - function getContextualTypeForJsxExpression(node) { + function getContextualTypeForJsxExpression(node, contextFlags) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) - ? getContextualType(node) + ? getContextualType(node, contextFlags) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent, node) + ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) : undefined; } - function getContextualTypeForJsxAttribute(attribute) { + function getContextualTypeForJsxAttribute(attribute, contextFlags) { // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName if (ts.isJsxAttribute(attribute)) { - var attributesType = getApparentTypeOfContextualType(attribute.parent); + var attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return getContextualType(attribute.parent); + return getContextualType(attribute.parent, contextFlags); } } // Return true if the given expression is possibly a discriminant value. We limit the kinds of @@ -72882,22 +73877,20 @@ var ts; 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 && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { // 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. - if (contextFlags && contextFlags & 1 /* ContextFlags.Signature */) { - return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); - } + return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); + } + if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.returnMapper) { // For other purposes (e.g. determining whether to produce literal types) we only // incorporate inferences made from the return type in a function call. We remove // the 'boolean' type from the contextual type such that contextually typed boolean // literals actually end up widening to 'boolean' (see #48363). - if (inferenceContext.returnMapper) { - var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); - return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? - filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : - type; - } + var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); + return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? + filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : + type; } } return contextualType; @@ -72952,9 +73945,9 @@ var ts; return getContextualTypeForInitializerExpression(node, contextFlags); case 214 /* SyntaxKind.ArrowFunction */: case 247 /* SyntaxKind.ReturnStatement */: - return getContextualTypeForReturnExpression(node); + return getContextualTypeForReturnExpression(node, contextFlags); case 224 /* SyntaxKind.YieldExpression */: - return getContextualTypeForYieldOperand(parent); + return getContextualTypeForYieldOperand(parent, contextFlags); case 218 /* SyntaxKind.AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); case 208 /* SyntaxKind.CallExpression */: @@ -72992,17 +73985,17 @@ var ts; case 271 /* SyntaxKind.ExportAssignment */: return tryGetTypeFromEffectiveTypeNode(parent); case 288 /* SyntaxKind.JsxExpression */: - return getContextualTypeForJsxExpression(parent); + return getContextualTypeForJsxExpression(parent, contextFlags); case 285 /* SyntaxKind.JsxAttribute */: case 287 /* SyntaxKind.JsxSpreadAttribute */: - return getContextualTypeForJsxAttribute(parent); + return getContextualTypeForJsxAttribute(parent, contextFlags); case 280 /* SyntaxKind.JsxOpeningElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; function tryFindWhenConstTypeReference(node) { - return getContextualType(node); + return getContextualType(node, contextFlags); } } function getInferenceContext(node) { @@ -73262,8 +74255,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var current = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var current = types_18[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -73304,7 +74297,7 @@ var ts; var elementCount = elements.length; var elementTypes = []; var elementFlags = []; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var inDestructuringPattern = ts.isAssignmentTarget(node); var inConstContext = isConstContext(node); var hasOmittedExpression = false; @@ -73475,7 +74468,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 201 /* SyntaxKind.ObjectBindingPattern */ || contextualType.pattern.kind === 205 /* SyntaxKind.ObjectLiteralExpression */); var inConstContext = isConstContext(node); @@ -73814,7 +74807,7 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes, /*contextFlags*/ undefined); var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* SymbolFlags.Property */, jsxChildrenPropertyName); @@ -74425,19 +75418,19 @@ var ts; return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { - return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */); + return !!(getTypeFacts(type) & 50331648 /* TypeFacts.IsUndefinedOrNull */); } function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function reportObjectPossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportObjectPossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); } - function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); @@ -74447,9 +75440,9 @@ var ts; error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */; - if (kind) { - reportError(node, kind); + var facts = getTypeFacts(type); + if (facts & 50331648 /* TypeFacts.IsUndefinedOrNull */) { + reportError(node, facts); var t = getNonNullableType(type); return t.flags & (98304 /* TypeFlags.Nullable */ | 131072 /* TypeFlags.Never */) ? errorType : t; } @@ -74618,9 +75611,8 @@ var ts; markAliasReferenced(parentSymbol, node); } return isErrorType(apparentType) ? errorType : apparentType; - ; } - prop = getPropertyOfType(apparentType, right.escapedText); + prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ node.kind === 161 /* SyntaxKind.QualifiedName */); } // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. // `Foo` is also not referenced in `enum FooCopy { Bar = Foo.Bar }`, because the enum member value gets inlined @@ -74745,7 +75737,7 @@ var ts; assumeUninitialized = true; } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) { error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -74928,9 +75920,9 @@ var ts; function getSuggestedSymbolForNonexistentProperty(name, containingType) { var props = getPropertiesOfType(containingType); if (typeof name !== "string") { - var parent_2 = name.parent; - if (ts.isPropertyAccessExpression(parent_2)) { - props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + var parent_3 = name.parent; + if (ts.isPropertyAccessExpression(parent_3)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_3, containingType, prop); }); } name = ts.idText(name); } @@ -75432,29 +76424,43 @@ var ts; // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. if (node.kind !== 165 /* SyntaxKind.Decorator */) { - var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); + var skipBindingPatterns = ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }); + var contextualType = getContextualType(node, skipBindingPatterns ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); if (contextualType) { var inferenceTargetType = getReturnTypeOfSignature(signature); if (couldContainTypeVariables(inferenceTargetType)) { - // We clone the inference context to avoid disturbing a resolution in progress for an - // outer call expression. Effectively we just want a snapshot of whatever has been - // inferred for any outer call expression so far. var outerContext = getInferenceContext(node); - var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); - var instantiatedType = instantiateType(contextualType, outerMapper); - // If the contextual type is a generic function type with a single call signature, we - // instantiate the type with its own type parameters and type arguments. This ensures that - // the type parameters are not erased to type any during type inference such that they can - // be inferred as actual types from the contextual type. For example: - // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; - // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); - // Above, the type of the 'value' parameter is inferred to be 'A'. - var contextualSignature = getSingleCallSignature(instantiatedType); - var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : - instantiatedType; - // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + var isFromBindingPattern = !skipBindingPatterns && getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) !== contextualType; + // A return type inference from a binding pattern can be used in instantiating the contextual + // type of an argument later in inference, but cannot stand on its own as the final return type. + // It is incorporated into `context.returnMapper` which is used in `instantiateContextualType`, + // but doesn't need to go into `context.inferences`. This allows a an array binding pattern to + // produce a tuple for `T` in + // declare function f(cb: () => T): T; + // const [e1, e2, e3] = f(() => [1, "hi", true]); + // but does not produce any inference for `T` in + // declare function f(): T; + // const [e1, e2, e3] = f(); + if (!isFromBindingPattern) { + // We clone the inference context to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); + var instantiatedType = instantiateType(contextualType, outerMapper); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + } // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -75781,7 +76787,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_24 = 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 === 225 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -75798,7 +76804,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_24(i); + _loop_26(i); } return effectiveArgs_1; } @@ -76005,7 +77011,7 @@ var ts; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray; var typeArguments; - if (!isDecorator) { + if (!isDecorator && !ts.isSuperCall(node)) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 106 /* SyntaxKind.SuperKeyword */) { @@ -76084,6 +77090,15 @@ var ts; if (result) { return result; } + result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + // Preemptively cache the result; getResolvedSignature will do this after we return, but + // we need to ensure that the result is present for the error checks below so that if + // this signature is encountered again, we handle the circularity (rather than producing a + // different result which may produce no errors and assert). Callers of getResolvedSignature + // don't hit this issue because they only observe this result after it's had a chance to + // be cached, but the error reporting code below executes before getResolvedSignature sets + // resolvedSignature. + getNodeLinks(node).resolvedSignature = result; // No signatures were applicable. Now report errors based on the last applicable signature with // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, @@ -76118,7 +77133,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_25 = 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) { @@ -76136,7 +77151,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_25(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"); @@ -76175,7 +77190,7 @@ var ts; } } } - return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + return result; function addImplementationSuccessElaboration(failed, diagnostic) { var _a, _b; var oldCandidatesForArgumentError = candidatesForArgumentError; @@ -76255,7 +77270,7 @@ var ts; argCheckMode = checkMode & 32 /* CheckMode.IsForStringLiteralArgumentCompletions */; if (inferenceContext) { var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -76294,7 +77309,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_26 = 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; }); @@ -76302,7 +77317,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_26(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -76470,7 +77485,7 @@ var ts; // returns a function type, we choose to defer processing. This narrowly permits function composition // operators to flow inferences through return types, but otherwise processes calls right away. We // use the resolvingSignature singleton to indicate that we deferred processing. This result will be - // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and + // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and // from which we never make inferences). if (checkMode & 8 /* CheckMode.SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) { skippedGenericFunction(node, checkMode); @@ -76647,8 +77662,8 @@ var ts; if (apparentType.flags & 1048576 /* TypeFlags.Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var constituent = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var constituent = types_19[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -76814,7 +77829,7 @@ var ts; // file would probably be preferable. var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* SymbolFlags.Type */); var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* SymbolFlags.Type */, node); - var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); var parameterSymbol = createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, "props"); parameterSymbol.type = result; return createSignature(declaration, @@ -77023,8 +78038,8 @@ var ts; var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode); if (signature === resolvingSignature) { // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that - // returns a function type. We defer checking and return nonInferrableType. - return nonInferrableType; + // returns a function type. We defer checking and return silentNeverType. + return silentNeverType; } checkDeprecatedSignature(signature, node); if (node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { @@ -77632,17 +78647,6 @@ var ts; } } } - var restType = getEffectiveRestType(context); - if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { - // The contextual signature has a generic rest parameter. We first instantiate the contextual - // signature (without fixing type parameters) and assign types to contextually typed parameters. - var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper); - assignContextualParameterTypes(signature, instantiatedContext); - // We then infer from a tuple type representing the parameters that correspond to the contextual - // rest parameter. - var restPos = getParameterCount(context) - 1; - inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType); - } } function assignContextualParameterTypes(signature, context) { if (context.typeParameters) { @@ -77835,7 +78839,7 @@ var ts; var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : - instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); + instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func, /*contextFlags*/ undefined); if (isGenerator) { yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* IterationTypeKind.Yield */, isAsync); returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* IterationTypeKind.Return */, isAsync); @@ -77906,7 +78910,7 @@ var ts; nextType = iterationTypes && iterationTypes.nextType; } else { - nextType = getContextualType(yieldExpression); + nextType = getContextualType(yieldExpression, /*contextFlags*/ undefined); } if (nextType) ts.pushIfUnique(nextTypes, nextType); @@ -77921,45 +78925,12 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - /** - * Collect the TypeFacts learned from a typeof switch with - * total clauses `witnesses`, and the active clause ranging - * from `start` to `end`. Parameter `hasDefault` denotes - * whether the active clause contains a default clause. - */ - function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + // Return the combined not-equal type facts for all cases except those between the start and end indices. + function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) { var facts = 0 /* TypeFacts.None */; - // When in the default we only collect inequality facts - // because default is 'in theory' a set of infinite - // equalities. - if (hasDefault) { - // Value is not equal to any types after the active clause. - for (var i = end; i < witnesses.length; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - // Remove inequalities for types that appear in the - // active clause because they appear before other - // types collected so far. - for (var i = start; i < end; i++) { - facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); - } - // Add inequalities for types before the active clause unconditionally. - for (var i = 0; i < start; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - } - // When in an active clause without default the set of - // equalities is finite. - else { - // Add equalities for all types in the active clause. - for (var i = start; i < end; i++) { - facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeFacts.TypeofEQHostObject */; - } - // Remove equalities for types that appear before the - // active clause. - for (var i = 0; i < start; i++) { - facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); - } + for (var i = 0; i < witnesses.length; i++) { + var witness = i < start || i >= end ? witnesses[i] : undefined; + facts |= witness !== undefined ? typeofNEFacts.get(witness) || 32768 /* TypeFacts.TypeofNEHostObject */ : 0; } return facts; } @@ -77969,16 +78940,19 @@ var ts; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 216 /* SyntaxKind.TypeOfExpression */) { - var operandType = getTypeOfExpression(node.expression.expression); - var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); - // notEqualFacts states that the type of the switched value is not equal to every type in the switch. - var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_6 = getBaseConstraintOfType(operandType) || operandType; - // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_6.flags & 3 /* TypeFlags.AnyOrUnknown */) { - return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_1) === 556800 /* TypeFacts.AllTypeofNE */; + var witnesses = getSwitchClauseTypeOfWitnesses(node); + if (!witnesses) { + return false; } - return !!(filterType(type_6, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* TypeFlags.Never */); + var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(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 */) { + // We special case the top types to be exhaustive when all cases are handled. + return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_2) === 556800 /* TypeFacts.AllTypeofNE */; + } + // 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); if (!isLiteralType(type)) { @@ -78145,11 +79119,16 @@ var ts; if (isContextSensitive(node)) { if (contextualSignature) { var inferenceContext = getInferenceContext(node); + var instantiatedContextualSignature = void 0; if (checkMode && checkMode & 2 /* CheckMode.Inferential */) { inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); + var restType = getEffectiveRestType(contextualSignature); + if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { + instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper); + } } - var instantiatedContextualSignature = inferenceContext ? - instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature; + instantiatedContextualSignature || (instantiatedContextualSignature = inferenceContext ? + instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature); assignContextualParameterTypes(signature, instantiatedContextualSignature); } else { @@ -78339,7 +79318,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks && !(type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 131072 /* TypeFlags.Never */)) && - !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getTypeFacts(type) & 16777216 /* TypeFacts.IsUndefined */)) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); } } @@ -78448,7 +79427,7 @@ var ts; error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } if (node.operator === 39 /* SyntaxKind.PlusToken */) { - if (maybeTypeOfKind(operandType, 2112 /* TypeFlags.BigIntLike */)) { + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* TypeFlags.BigIntLike */)) { error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType))); } return numberType; @@ -78507,8 +79486,8 @@ var ts; } if (type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { - var t = types_21[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var t = types_20[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -78735,7 +79714,7 @@ var ts; // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* TypeFlags.Undefined */)) { + !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & 16777216 /* TypeFacts.IsUndefined */)) { sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -78748,6 +79727,10 @@ var ts; if (target.kind === 221 /* SyntaxKind.BinaryExpression */ && target.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; + // A default value is specified, so remove undefined from the final type. + if (strictNullChecks) { + sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); + } } if (target.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); @@ -78888,7 +79871,11 @@ var ts; var operator = operatorToken.kind; if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */ || operator === 56 /* SyntaxKind.BarBarToken */ || operator === 60 /* SyntaxKind.QuestionQuestionToken */) { if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); + var parent = node.parent; + while (parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */ + || ts.isBinaryExpression(parent) && (parent.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ || parent.operatorToken.kind === 56 /* SyntaxKind.BarBarToken */)) { + parent = parent.parent; + } checkTestingKnownTruthyCallableOrAwaitableType(node.left, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } checkTruthinessOfType(leftType, node.left); @@ -79112,6 +80099,10 @@ var ts; case 35 /* SyntaxKind.ExclamationEqualsToken */: case 36 /* SyntaxKind.EqualsEqualsEqualsToken */: case 37 /* SyntaxKind.ExclamationEqualsEqualsToken */: + if (ts.isLiteralExpressionOfObject(left) || ts.isLiteralExpressionOfObject(right)) { + var eqType = operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */; + error(errorNode, ts.Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); + } reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); }); return booleanType; case 102 /* SyntaxKind.InstanceOfKeyword */: @@ -79131,7 +80122,7 @@ var ts; case 56 /* SyntaxKind.BarBarToken */: case 75 /* SyntaxKind.BarBarEqualsToken */: { var resultType_3 = getTypeFacts(leftType) & 8388608 /* TypeFacts.Falsy */ ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* UnionReduction.Subtype */) : + getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* UnionReduction.Subtype */) : leftType; if (operator === 75 /* SyntaxKind.BarBarEqualsToken */) { checkAssignmentOperator(rightType); @@ -79383,7 +80374,7 @@ var ts; type = anyType; addLazyDiagnostic(function () { if (noImplicitAny && !ts.expressionResultIsUnused(node)) { - var contextualType = getContextualType(node); + var contextualType = getContextualType(node, /*contextFlags*/ undefined); if (!contextualType || isTypeAny(contextualType)) { error(node, ts.Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); } @@ -79424,7 +80415,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node, /*contextFlags*/ undefined) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; } function isTemplateLiteralContextualType(type) { return !!(type.flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */) || @@ -79452,7 +80443,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node, /*contextFlags*/ undefined)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -79567,7 +80558,7 @@ var ts; var type = checkExpression(node, checkMode, forceTuple); return isConstContext(node) || ts.isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : - getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node)); + getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node, /*contextFlags*/ undefined) : contextualType, node, /*contextFlags*/ undefined)); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. @@ -79677,8 +80668,8 @@ var ts; var result = []; var oldTypeParameters; var newTypeParameters; - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var tp = typeParameters_2[_i]; + for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { + var tp = typeParameters_3[_i]; var name = tp.symbol.escapedName; if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) { var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name); @@ -80000,12 +80991,14 @@ var ts; error(node, ts.Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); } else if (modifiers === 32768 /* ModifierFlags.In */ || modifiers === 65536 /* ModifierFlags.Out */) { - var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubType : markerSuperType); - var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperType : markerSubType); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); + var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck); + var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck); var saveVarianceTypeParameter = typeParameter; varianceTypeParameter = typeParameter; checkTypeAssignableTo(source, target, node, ts.Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation); varianceTypeParameter = saveVarianceTypeParameter; + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } } @@ -80026,7 +81019,7 @@ var ts; error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + if ((node.questionToken || isJSDocOptionalParameter(node)) && ts.isBindingPattern(node.name) && func.body) { error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { @@ -80355,7 +81348,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_27 = 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)); @@ -80370,7 +81363,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_27(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -80403,6 +81396,9 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); + if (ts.isMethodDeclaration(node) && node.asteriskToken && ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_a_generator); + } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // method signatures already report "implementation not allowed in ambient context" elsewhere @@ -80530,6 +81526,9 @@ var ts; return !!ts.forEachChild(node, nodeImmediatelyReferencesSuperOrThis); } function checkAccessorDeclaration(node) { + if (ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_an_accessor); + } addLazyDiagnostic(checkAccessorDeclarationDiagnostics); checkSourceElement(node.body); setNodeLinksForPrivateIdentifierScope(node); @@ -80587,6 +81586,12 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) { + if (index < typeParameters.length) { + return getTypeFromTypeNode(node.typeArguments[index]); + } + return getEffectiveTypeArguments(node, typeParameters)[index]; + } function getEffectiveTypeArguments(node, typeParameters) { return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } @@ -80828,8 +81833,11 @@ var ts; if (node.assertions) { var override = ts.getResolutionModeOverrideForClause(node.assertions.assertClause, grammarErrorOnNode); if (override) { + if (!ts.isNightly()) { + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } } } @@ -81214,7 +82222,7 @@ var ts; * @param type The type of the promise. * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. */ - function getPromisedTypeOfPromise(type, errorNode) { + function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) { // // { // type // then( // thenFunction @@ -81249,7 +82257,29 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); + var thisTypeForError; + var candidates; + for (var _i = 0, thenSignatures_1 = thenSignatures; _i < thenSignatures_1.length; _i++) { + var thenSignature = thenSignatures_1[_i]; + var thisType = getThisTypeOfSignature(thenSignature); + if (thisType && thisType !== voidType && !isTypeRelatedTo(type, thisType, subtypeRelation)) { + thisTypeForError = thisType; + } + else { + candidates = ts.append(candidates, thenSignature); + } + } + if (!candidates) { + ts.Debug.assertIsDefined(thisTypeForError); + if (thisTypeForErrorOut) { + thisTypeForErrorOut.value = thisTypeForError; + } + if (errorNode) { + error(errorNode, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError)); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(candidates, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -81303,6 +82333,34 @@ var ts; isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : type; } + function isAwaitedTypeNeeded(type) { + // If this is already an `Awaited`, we shouldn't wrap it. This helps to avoid `Awaited>` in higher-order. + if (isTypeAny(type) || isAwaitedTypeInstantiation(type)) { + return false; + } + // We only need `Awaited` if `T` contains possibly non-primitive types. + if (isGenericObjectType(type)) { + var baseConstraint = getBaseConstraintOfType(type); + // 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) : + maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { + return true; + } + } + return false; + } + function tryCreateAwaitedType(type) { + // Nothing to do if `Awaited` doesn't exist + var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); + if (awaitedSymbol) { + // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where + // an `Awaited` would suffice. + return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); + } + return undefined; + } function createAwaitedTypeIfNeeded(type) { // We wrap type `T` in `Awaited` based on the following conditions: // - `T` is not already an `Awaited`, and @@ -81311,26 +82369,10 @@ var ts; // - `T` has no base constraint, or // - The base constraint of `T` is `any`, `unknown`, `object`, or `{}`, or // - The base constraint of `T` is an object type with a callable `then` method. - if (isTypeAny(type)) { - return type; - } - // If this is already an `Awaited`, just return it. This helps to avoid `Awaited>` in higher-order. - if (isAwaitedTypeInstantiation(type)) { - return type; - } - // Only instantiate `Awaited` if `T` contains possibly non-primitive types. - if (isGenericObjectType(type)) { - var baseConstraint = getBaseConstraintOfType(type); - // Only instantiate `Awaited` if `T` 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)) { - // Nothing to do if `Awaited` doesn't exist - var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); - if (awaitedSymbol) { - // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where - // an `Awaited` would suffice. - return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); - } + if (isAwaitedTypeNeeded(type)) { + var awaitedType = tryCreateAwaitedType(type); + if (awaitedType) { + return awaitedType; } } ts.Debug.assert(getPromisedTypeOfPromise(type) === undefined, "type provided should not be a non-generic 'promise'-like."); @@ -81370,10 +82412,24 @@ var ts; } // For a union, get a union of the awaited types of each constituent. if (type.flags & 1048576 /* TypeFlags.Union */) { + if (awaitedTypeStack.lastIndexOf(type.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } var mapper = errorNode ? function (constituentType) { return getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeNoAlias; - return typeAsAwaitable.awaitedTypeOfType = mapType(type, mapper); + awaitedTypeStack.push(type.id); + var mapped = mapType(type, mapper); + awaitedTypeStack.pop(); + return typeAsAwaitable.awaitedTypeOfType = mapped; } - var promisedType = getPromisedTypeOfPromise(type); + // If `type` is generic and should be wrapped in `Awaited`, return it. + if (isAwaitedTypeNeeded(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + var thisTypeForErrorOut = { value: undefined }; + var promisedType = getPromisedTypeOfPromise(type, /*errorNode*/ undefined, thisTypeForErrorOut); if (promisedType) { if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose @@ -81442,7 +82498,12 @@ var ts; if (isThenableType(type)) { if (errorNode) { ts.Debug.assertIsDefined(diagnosticMessage); - error(errorNode, diagnosticMessage, arg0); + var chain = void 0; + if (thisTypeForErrorOut.value) { + chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value)); + } + chain = ts.chainDiagnosticMessages(chain, diagnosticMessage, arg0); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, chain)); } return undefined; } @@ -81638,8 +82699,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { - var typeNode = types_22[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */ || typeNode.kind === 197 /* SyntaxKind.NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } @@ -81679,18 +82740,18 @@ var ts; } /** Check the decorators of a node */ function checkDecorators(node) { - if (!node.decorators) { - return; - } // skip this check for nodes that cannot have decorators. These should have already had an error reported by // checkGrammarDecorators. - if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node) || !node.modifiers || !ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning); } - var firstDecorator = node.decorators[0]; + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (!firstDecorator) { + return; + } checkExternalEmitHelpers(firstDecorator, 8 /* ExternalEmitHelpers.Decorate */); if (node.kind === 164 /* SyntaxKind.Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* ExternalEmitHelpers.Param */); @@ -81734,7 +82795,12 @@ var ts; break; } } - ts.forEach(node.decorators, checkDecorator); + for (var _f = 0, _g = node.modifiers; _f < _g.length; _f++) { + var modifier = _g[_f]; + if (ts.isDecorator(modifier)) { + checkDecorator(modifier); + } + } } function checkFunctionDeclaration(node) { addLazyDiagnostic(checkFunctionDeclarationDiagnostics); @@ -81765,6 +82831,11 @@ var ts; function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } + function checkJSDocLinkLikeTag(node) { + if (node.name) { + resolveJSDocMemberName(node.name, /*ignoreErrors*/ true); + } + } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); } @@ -82004,8 +83075,8 @@ var ts; return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); - for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { - var typeParameter = typeParameters_3[_i]; + for (var _i = 0, typeParameters_4 = typeParameters; _i < typeParameters_4.length; _i++) { + var typeParameter = typeParameters_4[_i]; if (!isTypeParameterUnused(typeParameter)) continue; var name = ts.idText(typeParameter.name); @@ -82165,6 +83236,22 @@ var ts; } }); } + function checkPotentialUncheckedRenamedBindingElementsInTypes() { + var _a; + for (var _i = 0, potentialUnusedRenamedBindingElementsInTypes_1 = potentialUnusedRenamedBindingElementsInTypes; _i < potentialUnusedRenamedBindingElementsInTypes_1.length; _i++) { + var node = potentialUnusedRenamedBindingElementsInTypes_1[_i]; + if (!((_a = getSymbolOfNode(node)) === null || _a === void 0 ? void 0 : _a.isReferenced)) { + var wrappingDeclaration = ts.walkUpBindingElementsAndPatterns(node); + ts.Debug.assert(ts.isParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here"); + var diagnostic = ts.createDiagnosticForNode(node.name, ts.Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, ts.declarationNameToString(node.name), ts.declarationNameToString(node.propertyName)); + if (!wrappingDeclaration.type) { + // entire parameter does not have type annotation, suggest adding an annotation + ts.addRelatedInfo(diagnostic, ts.createFileDiagnostic(ts.getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, ts.Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, ts.declarationNameToString(node.propertyName))); + } + diagnostics.add(diagnostic); + } + } + } function bindingNameText(name) { switch (name.kind) { case 79 /* SyntaxKind.Identifier */: @@ -82461,11 +83548,22 @@ var ts; // well known symbols. if (node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.name); - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkExpressionCached(node.initializer); } } if (ts.isBindingElement(node)) { + if (node.propertyName && + ts.isIdentifier(node.name) && + ts.isParameterDeclaration(node) && + ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + // type F = ({a: string}) => void; + // ^^^^^^ + // variable renaming in function type notation is confusing, + // so we forbid it even if noUnusedLocals is not enabled + potentialUnusedRenamedBindingElementsInTypes.push(node); + return; + } if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ScriptTarget.ES2018 */) { checkExternalEmitHelpers(node, 4 /* ExternalEmitHelpers.Rest */); } @@ -82498,14 +83596,14 @@ var ts; ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (ts.isParameter(node) && node.initializer && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; - var needCheckWidenedType = node.name.elements.length === 0; + var needCheckInitializer = ts.hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; + var needCheckWidenedType = !ts.some(node.name.elements, ts.not(ts.isOmittedExpression)); if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error var widenedType = getWidenedTypeForVariableLikeDeclaration(node); @@ -82532,7 +83630,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.kind === 203 /* SyntaxKind.BindingElement */ ? node.parent.parent : node)) { checkAliasSymbol(node); return; } @@ -82540,7 +83638,7 @@ var ts; if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - var initializer = ts.getEffectiveInitializer(node); + var initializer = ts.hasOnlyExpressionInitializer(node) && ts.getEffectiveInitializer(node); if (initializer) { var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && @@ -82565,7 +83663,7 @@ var ts; !(symbol.flags & 67108864 /* SymbolFlags.Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); } - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { @@ -82658,7 +83756,7 @@ var ts; return; var type = checkTruthinessExpression(location); var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) && isTypeAssertion(location.expression); - if (getFalsyFlags(type) || isPropertyExpressionCast) + if (!(getTypeFacts(type) & 4194304 /* TypeFacts.Truthy */) || isPropertyExpressionCast) return; // While it technically should be invalid for any known-truthy value // to be tested, we de-scope to functions and Promises unreferenced in @@ -83124,17 +84222,28 @@ var ts; * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. */ function getIterationTypesOfIterable(type, use, errorNode) { + var _a, _b; if (isTypeAny(type)) { return anyIterationTypes; } if (!(type.flags & 1048576 /* TypeFlags.Union */)) { - var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode); + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); if (iterationTypes_1 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } return undefined; } + else if ((_a = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _a === void 0 ? void 0 : _a.length) { + for (var _i = 0, _c = errorOutputContainer.errors; _i < _c.length; _i++) { + var diag = _c[_i]; + diagnostics.add(diag); + } + } return iterationTypes_1; } var cacheKey = use & 2 /* IterationUse.AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; @@ -83142,19 +84251,27 @@ var ts; if (cachedTypes) return cachedTypes === noIterationTypes ? undefined : cachedTypes; var allIterationTypes; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituent = _a[_i]; - var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode); + for (var _d = 0, _e = type.types; _d < _e.length; _d++) { + var constituent = _e[_d]; + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer); if (iterationTypes_2 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } setCachedIterationTypes(type, cacheKey, noIterationTypes); return undefined; } - else { - allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); + else if ((_b = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _b === void 0 ? void 0 : _b.length) { + for (var _f = 0, _g = errorOutputContainer.errors; _f < _g.length; _f++) { + var diag = _g[_f]; + diagnostics.add(diag); + } } + allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); } var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes; setCachedIterationTypes(type, cacheKey, iterationTypes); @@ -83182,47 +84299,62 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableWorker(type, use, errorNode) { + function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) { if (isTypeAny(type)) { return anyIterationTypes; } + // If we are reporting errors and encounter a cached `noIterationTypes`, we should ignore the cached value and continue as if nothing was cached. + // In addition, we should not cache any new results for this call. + var noCache = false; if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver); if (iterationTypes) { - return use & 8 /* IterationUse.ForOfFlag */ ? - getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : - iterationTypes; + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; + } + else { + return use & 8 /* IterationUse.ForOfFlag */ ? + getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : + iterationTypes; + } } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver); if (iterationTypes) { - if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - // for a sync iterable in an async context, only use the cached types if they are valid. - if (iterationTypes !== noIterationTypes) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode)); - } + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; } else { - return iterationTypes; + if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { + // for a sync iterable in an async context, only use the cached types if they are valid. + if (iterationTypes !== noIterationTypes) { + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); + } + } + else { + return iterationTypes; + } } } } if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { return iterationTypes; } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes - ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) - : noIterationTypes); + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); } else { return iterationTypes; @@ -83243,7 +84375,7 @@ var ts; } function getIterationTypesOfGlobalIterableType(globalType, resolver) { var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || - getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; } /** @@ -83297,26 +84429,26 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableSlow(type, resolver, errorNode) { + function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var _a; var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* SymbolFlags.Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); + return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); } var signatures = methodType ? getSignaturesOfType(methodType, 0 /* SignatureKind.Call */) : undefined; if (!ts.some(signatures)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); + return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); } var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature)); - var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes; - return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); + var iterationTypes = (_a = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache)) !== null && _a !== void 0 ? _a : noIterationTypes; + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { 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; - errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. @@ -83324,13 +84456,29 @@ var ts; * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, `undefined` is returned. */ - function getIterationTypesOfIterator(type, resolver, errorNode) { + function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { + return getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, /*noCache*/ false); + } + /** + * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. + * + * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` + * record is returned. Otherwise, `undefined` is returned. + * + * NOTE: You probably don't want to call this directly and should be calling + * `getIterationTypesOfIterator` instead. + */ + function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) { if (isTypeAny(type)) { return anyIterationTypes; } var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || - getIterationTypesOfIteratorFast(type, resolver) || - getIterationTypesOfIteratorSlow(type, resolver, errorNode); + getIterationTypesOfIteratorFast(type, resolver); + if (iterationTypes === noIterationTypes && errorNode) { + iterationTypes = undefined; + noCache = true; + } + iterationTypes !== null && iterationTypes !== void 0 ? iterationTypes : (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache)); return iterationTypes === noIterationTypes ? undefined : iterationTypes; } /** @@ -83368,7 +84516,7 @@ var ts; // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any` // and `undefined` in our libs by default, a custom lib *could* use different definitions. var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || - getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType; return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } @@ -83438,8 +84586,8 @@ var ts; * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, we return `undefined`. */ - function getIterationTypesOfMethod(type, resolver, methodName, errorNode) { - var _a, _b, _c, _d; + function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) { + var _a, _b, _c, _d, _e, _f; var method = getPropertyOfType(type, methodName); // Ignore 'return' or 'throw' if they are missing. if (!method && methodName !== "next") { @@ -83459,9 +84607,15 @@ var ts; var diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic; - error(errorNode, diagnostic, methodName); + if (errorOutputContainer) { + (_a = errorOutputContainer.errors) !== null && _a !== void 0 ? _a : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, diagnostic, methodName)); + } + else { + error(errorNode, diagnostic, methodName); + } } - return methodName === "next" ? anyIterationTypes : undefined; + return methodName === "next" ? noIterationTypes : undefined; } // If the method signature comes exclusively from the global iterator or generator type, // create iteration types from its type arguments like `getIterationTypesOfIteratorFast` @@ -83473,8 +84627,8 @@ var ts; if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) { var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false); var globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false); - var isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) === null || _a === void 0 ? void 0 : _a.members) === null || _b === void 0 ? void 0 : _b.get(methodName)) === methodType.symbol; - var isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) === null || _c === void 0 ? void 0 : _c.members) === null || _d === void 0 ? void 0 : _d.get(methodName)) === methodType.symbol; + var isGeneratorMethod = ((_c = (_b = globalGeneratorType.symbol) === null || _b === void 0 ? void 0 : _b.members) === null || _c === void 0 ? void 0 : _c.get(methodName)) === methodType.symbol; + var isIteratorMethod = !isGeneratorMethod && ((_e = (_d = globalIteratorType.symbol) === null || _d === void 0 ? void 0 : _d.members) === null || _e === void 0 ? void 0 : _e.get(methodName)) === methodType.symbol; if (isGeneratorMethod || isIteratorMethod) { var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType; var mapper = methodType.mapper; @@ -83514,7 +84668,13 @@ var ts; var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType); if (iterationTypes === noIterationTypes) { if (errorNode) { - error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + if (errorOutputContainer) { + (_f = errorOutputContainer.errors) !== null && _f !== void 0 ? _f : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName)); + } + else { + error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + } } yieldType = anyType; returnTypes = ts.append(returnTypes, anyType); @@ -83535,13 +84695,13 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterator` instead. */ - function getIterationTypesOfIteratorSlow(type, resolver, errorNode) { + function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var iterationTypes = combineIterationTypes([ - getIterationTypesOfMethod(type, resolver, "next", errorNode), - getIterationTypesOfMethod(type, resolver, "return", errorNode), - getIterationTypesOfMethod(type, resolver, "throw", errorNode), + getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer), ]); - return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); } /** * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like, @@ -83562,7 +84722,7 @@ var ts; var use = isAsyncGenerator ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) || - getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined); } function checkBreakOrContinueStatement(node) { // Grammar checking @@ -83573,9 +84733,14 @@ var ts; function unwrapReturnType(returnType, functionFlags) { var isGenerator = !!(functionFlags & 1 /* FunctionFlags.Generator */); var isAsync = !!(functionFlags & 2 /* FunctionFlags.Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync) || errorType : - isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : - returnType; + if (isGenerator) { + var returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync); + if (!returnIterationType) { + return errorType; + } + return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType; + } + return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func)); @@ -83795,9 +84960,10 @@ var ts; } var indexInfos = getApplicableIndexInfos(type, propNameType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; - var localPropDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || - name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ || getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_28 = function (info) { + var propDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || + name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; + var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; + 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 @@ -83805,12 +84971,16 @@ var ts; var errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !ts.some(getBaseTypes(type), function (base) { return !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType); }) ? interfaceDeclaration : undefined); if (errorNode && !isTypeAssignableTo(propType, info.type)) { - error(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + var diagnostic = createError(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + if (propDeclaration && errorNode !== propDeclaration) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(propDeclaration, ts.Diagnostics._0_is_declared_here, symbolToString(prop))); + } + diagnostics.add(diagnostic); } }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_28(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -83818,7 +84988,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_29 = 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; @@ -83833,7 +85003,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_29(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -84022,8 +85192,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { - grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (firstDecorator && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(firstDecorator, ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -84152,7 +85323,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_30 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -84169,7 +85340,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_30(member); + _loop_32(member); } } /** @@ -84257,7 +85428,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_31 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -84276,7 +85447,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_31(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -84344,18 +85515,17 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. - var _a, _b; + var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { - continue; + return "continue"; } var baseSymbol = getPropertyOfObjectType(type, base.escapedName); if (!baseSymbol) { - continue; + return "continue"; } var derived = getTargetSymbol(baseSymbol); var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); @@ -84373,14 +85543,14 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { - var otherBaseType = _d[_c]; + for (var _e = 0, _f = getBaseTypes(type); _e < _f.length; _e++) { + var otherBaseType = _f[_e]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1); if (derivedElsewhere && derivedElsewhere !== base) { - continue basePropertyCheck; + return "continue-basePropertyCheck"; } } if (derivedClassDecl.kind === 226 /* SyntaxKind.ClassExpression */) { @@ -84395,20 +85565,19 @@ var ts; // derived overrides base. var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* ModifierFlags.Private */ || derivedDeclarationFlags & 8 /* ModifierFlags.Private */) { - // either base or derived property is private - not override, skip it - continue; + return "continue"; } var errorMessage = void 0; var basePropertyFlags = base.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; var derivedPropertyFlags = derived.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor - if (baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */ + if ((ts.getCheckFlags(base) & 6 /* CheckFlags.Synthetic */ + ? (_a = base.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); }) + : (_b = base.declarations) === null || _b === void 0 ? void 0 : _b.every(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); })) + || ts.getCheckFlags(base) & 262144 /* CheckFlags.Mapped */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { - // when the base property is abstract or from an interface, base/derived flags don't need to match - // same when the derived property is from an assignment - continue; + return "continue"; } var overriddenInstanceProperty = basePropertyFlags !== 4 /* SymbolFlags.Property */ && derivedPropertyFlags === 4 /* SymbolFlags.Property */; var overriddenInstanceAccessor = basePropertyFlags === 4 /* SymbolFlags.Property */ && derivedPropertyFlags !== 4 /* SymbolFlags.Property */; @@ -84419,12 +85588,12 @@ var ts; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { - var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); + var uninitialized = (_c = derived.declarations) === null || _c === void 0 ? void 0 : _c.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* SymbolFlags.Transient */) && !(baseDeclarationFlags & 128 /* ModifierFlags.Abstract */) && !(derivedDeclarationFlags & 128 /* ModifierFlags.Abstract */) - && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { + && !((_d = derived.declarations) === null || _d === void 0 ? void 0 : _d.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -84437,13 +85606,11 @@ var ts; } } } - // correct case - continue; + return "continue"; } else if (isPrototypeProperty(base)) { if (isPrototypeProperty(derived) || derived.flags & 4 /* SymbolFlags.Property */) { - // method is overridden with method or property -- correct case - continue; + return "continue"; } else { ts.Debug.assert(!!(derived.flags & 98304 /* SymbolFlags.Accessor */)); @@ -84458,9 +85625,20 @@ var ts; } error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } + }; + basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var state_10 = _loop_34(baseProperty); + switch (state_10) { + case "continue-basePropertyCheck": continue basePropertyCheck; + } } } - function getNonInterhitedProperties(type, baseTypes, properties) { + function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { + return baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && (!ts.isPropertyDeclaration(declaration) || !declaration.initializer) + || ts.isInterfaceDeclaration(declaration.parent); + } + function getNonInheritedProperties(type, baseTypes, properties) { if (!ts.length(baseTypes)) { return properties; } @@ -84529,7 +85707,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName) || ts.isComputedPropertyName(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || containsUndefinedType(type))) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -84554,7 +85732,7 @@ var ts; ts.setParent(reference, staticBlock); reference.flowNode = staticBlock.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - if (!(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */)) { + if (!containsUndefinedType(flowType)) { return true; } } @@ -84569,7 +85747,7 @@ var ts; ts.setParent(reference, constructor); reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */); + return !containsUndefinedType(flowType); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -85085,6 +86263,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a, _b, _c, _d, _e; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -85095,6 +86274,31 @@ var ts; // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). symbol = getMergedSymbol(symbol.exportSymbol || symbol); + // A type-only import/export will already have a grammar error in a JS file, so no need to issue more errors within + if (ts.isInJSFile(node) && !(target.flags & 111551 /* SymbolFlags.Value */) && !ts.isTypeOnlyImportOrExportDeclaration(node)) { + var errorNode = ts.isImportOrExportSpecifier(node) ? node.propertyName || node.name : + ts.isNamedDeclaration(node) ? node.name : + node; + ts.Debug.assert(node.kind !== 274 /* SyntaxKind.NamespaceExport */); + if (node.kind === 275 /* SyntaxKind.ExportSpecifier */) { + var diag = error(errorNode, ts.Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); + var alreadyExportedSymbol = (_b = (_a = ts.getSourceFileOfNode(node).symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.get((node.propertyName || node.name).escapedText); + if (alreadyExportedSymbol === target) { + var exportingDeclaration = (_c = alreadyExportedSymbol.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isJSDocNode); + if (exportingDeclaration) { + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(exportingDeclaration, ts.Diagnostics._0_is_automatically_exported_here, ts.unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName))); + } + } + } + else { + ts.Debug.assert(node.kind !== 254 /* SyntaxKind.VariableDeclaration */); + var importDeclaration = ts.findAncestor(node, ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration)); + var moduleSpecifier = (_e = (importDeclaration && ((_d = ts.tryGetModuleSpecifierFromDeclaration(importDeclaration)) === null || _d === void 0 ? void 0 : _d.text))) !== null && _e !== void 0 ? _e : "..."; + var importedIdentifier = ts.unescapeLeadingUnderscores(ts.isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); + error(errorNode, ts.Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, "import(\"".concat(moduleSpecifier, "\").").concat(importedIdentifier)); + } + return; + } 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); @@ -85200,10 +86404,10 @@ var ts; var override = ts.getResolutionModeOverrideForClause(declaration.assertClause, validForTypeAssertions ? grammarErrorOnNode : undefined); if (validForTypeAssertions && override) { if (!ts.isNightly()) { - grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } return; // Other grammar checks do not apply to type-only imports with resolution mode assertions } @@ -85410,7 +86614,9 @@ var ts; error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { - markExportAsReferenced(node); + if (!node.isTypeOnly && !node.parent.parent.isTypeOnly) { + markExportAsReferenced(node); + } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); @@ -85552,12 +86758,16 @@ var ts; } } function checkSourceElementWorker(node) { - if (ts.isInJSFile(node)) { - ts.forEach(node.jsDoc, function (_a) { - var tags = _a.tags; - return ts.forEach(tags, checkSourceElement); + ts.forEach(node.jsDoc, function (_a) { + var comment = _a.comment, tags = _a.tags; + checkJSDocCommentWorker(comment); + ts.forEach(tags, function (tag) { + checkJSDocCommentWorker(tag.comment); + if (ts.isInJSFile(node)) { + checkSourceElement(tag); + } }); - } + }); var kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessively @@ -85643,6 +86853,10 @@ var ts; return checkJSDocTemplateTag(node); case 343 /* SyntaxKind.JSDocTypeTag */: return checkJSDocTypeTag(node); + case 324 /* SyntaxKind.JSDocLink */: + case 325 /* SyntaxKind.JSDocLinkCode */: + case 326 /* SyntaxKind.JSDocLinkPlain */: + return checkJSDocLinkLikeTag(node); case 340 /* SyntaxKind.JSDocParameterTag */: return checkJSDocParameterTag(node); case 347 /* SyntaxKind.JSDocPropertyTag */: @@ -85737,6 +86951,15 @@ var ts; return checkMissingDeclaration(node); } } + function checkJSDocCommentWorker(node) { + if (ts.isArray(node)) { + ts.forEach(node, function (tag) { + if (ts.isJSDocLinkLike(tag)) { + checkSourceElement(tag); + } + }); + } + } function checkJSDocTypeIsInJsFile(node) { if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); @@ -85904,6 +87127,7 @@ var ts; ts.clear(potentialNewTargetCollisions); ts.clear(potentialWeakMapSetCollisions); ts.clear(potentialReflectCollisions); + ts.clear(potentialUnusedRenamedBindingElementsInTypes); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -85919,6 +87143,9 @@ var ts; } }); } + if (!node.isDeclarationFile) { + checkPotentialUncheckedRenamedBindingElementsInTypes(); + } }); if (compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ && !node.isDeclarationFile && @@ -86292,7 +87519,7 @@ var ts; if (!result && isJSDoc_1) { var container = ts.findAncestor(name, ts.or(ts.isClassLike, ts.isInterfaceDeclaration)); if (container) { - return resolveJSDocMemberName(name, getSymbolOfNode(container)); + return resolveJSDocMemberName(name, /*ignoreErrors*/ false, getSymbolOfNode(container)); } } return result; @@ -86338,11 +87565,11 @@ var ts; * * For unqualified names, a container K may be provided as a second argument. */ - function resolveJSDocMemberName(name, container) { + function resolveJSDocMemberName(name, ignoreErrors, container) { if (ts.isEntityName(name)) { // resolve static values first var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */ | 111551 /* SymbolFlags.Value */; - var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, ignoreErrors, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); if (!symbol && ts.isIdentifier(name) && container) { symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning)); } @@ -86350,7 +87577,7 @@ var ts; return symbol; } } - var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left); + var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container); var right = ts.isIdentifier(name) ? name.escapedText : name.right.escapedText; if (left) { var proto = left.flags & 111551 /* SymbolFlags.Value */ && getPropertyOfType(getTypeOfSymbol(left), "prototype"); @@ -87341,13 +88568,20 @@ var ts; if (!fileToDirective) { return undefined; } + // computed property name should use node as value // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; - if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + var meaning; + if (node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) { meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; } + else { + meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; + if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; + } + } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -87631,7 +88865,10 @@ var ts; return checkGrammarDecorators(node) || checkGrammarModifiers(node); } function checkGrammarDecorators(node) { - if (!node.decorators) { + if (ts.canHaveIllegalDecorators(node) && ts.some(node.illegalDecorators)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node)) { return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { @@ -87644,7 +88881,7 @@ var ts; } else if (node.kind === 172 /* SyntaxKind.GetAccessor */ || node.kind === 173 /* SyntaxKind.SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + if (ts.hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } } @@ -87659,6 +88896,8 @@ var ts; var flags = 0 /* ModifierFlags.None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; if (modifier.kind !== 145 /* SyntaxKind.ReadonlyKeyword */) { if (node.kind === 166 /* SyntaxKind.PropertySignature */ || node.kind === 168 /* SyntaxKind.MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); @@ -87944,6 +89183,13 @@ var ts; case 164 /* SyntaxKind.Parameter */: case 163 /* SyntaxKind.TypeParameter */: return false; + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 179 /* SyntaxKind.FunctionType */: + case 276 /* SyntaxKind.MissingDeclaration */: + return true; default: if (node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 305 /* SyntaxKind.SourceFile */) { return false; @@ -87954,20 +89200,26 @@ var ts; case 257 /* SyntaxKind.ClassDeclaration */: case 180 /* SyntaxKind.ConstructorType */: return nodeHasAnyModifiersExcept(node, 126 /* SyntaxKind.AbstractKeyword */); + case 226 /* SyntaxKind.ClassExpression */: case 258 /* SyntaxKind.InterfaceDeclaration */: case 237 /* SyntaxKind.VariableStatement */: case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: return true; case 260 /* SyntaxKind.EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 85 /* SyntaxKind.ConstKeyword */); default: - ts.Debug.fail(); + ts.Debug.assertNever(node); } } } function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; + return modifier.kind !== allowedModifier; + } + return false; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { @@ -88259,14 +89511,20 @@ var ts; grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration - if (prop.modifiers) { + if (ts.canHaveModifiers(prop) && prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */) { + if (ts.isModifier(mod) && (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */)) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } + else if (ts.canHaveIllegalModifiers(prop) && prop.modifiers) { + for (var _d = 0, _e = prop.modifiers; _d < _e.length; _d++) { + var mod = _e[_d]; + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and @@ -88278,10 +89536,9 @@ var ts; var currentKind = void 0; switch (prop.kind) { case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); - // falls through case 296 /* SyntaxKind.PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* SyntaxKind.NumericLiteral */) { checkGrammarNumericLiteral(name); @@ -88720,9 +89977,6 @@ var ts; else { return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (!isConstOrReadonly || isInvalidInitializer) { - return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } } } function checkGrammarVariableDeclaration(node) { @@ -88889,7 +90143,7 @@ var ts; } } function checkGrammarConstructorTypeAnnotation(node) { - var type = ts.getEffectiveReturnTypeNode(node); + var type = node.type || ts.getEffectiveReturnTypeNode(node); if (type) { return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } @@ -88913,6 +90167,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Interfaces cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } @@ -88921,6 +90177,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Type literals cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } @@ -89295,7 +90553,6 @@ var ts; if (nodes === undefined || visitor === undefined) { return nodes; } - var updated; // Ensure start and count have valid values var length = nodes.length; if (start === undefined || start < 0) { @@ -89308,12 +90565,49 @@ var ts; var pos = -1; var end = -1; if (start > 0 || count < length) { - // If we are not visiting all of the original nodes, we must always create a new array. // Since this is a fragment of a node array, we do not copy over the previous location // and will only copy over `hasTrailingComma` if we are including the last element. - updated = []; hasTrailingComma = nodes.hasTrailingComma && start + count === length; } + else { + pos = nodes.pos; + end = nodes.end; + hasTrailingComma = nodes.hasTrailingComma; + } + var updated = visitArrayWorker(nodes, visitor, test, start, count); + if (updated !== nodes) { + // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. + var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); + ts.setTextRangePosEnd(updatedArray, pos, end); + return updatedArray; + } + return nodes; + } + ts.visitNodes = visitNodes; + /* @internal */ + function visitArray(nodes, visitor, test, start, count) { + if (nodes === undefined) { + return nodes; + } + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + return visitArrayWorker(nodes, visitor, test, start, count); + } + ts.visitArray = visitArray; + /* @internal */ + function visitArrayWorker(nodes, visitor, test, start, count) { + var updated; + var length = nodes.length; + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + updated = []; + } // Visit each original node. for (var i = 0; i < count; i++) { var node = nodes[i + start]; @@ -89322,9 +90616,6 @@ var ts; if (updated === undefined) { // Ensure we have a copy of `nodes`, up to the current index. updated = nodes.slice(0, i); - hasTrailingComma = nodes.hasTrailingComma; - pos = nodes.pos; - end = nodes.end; } if (visited) { if (ts.isArray(visited)) { @@ -89341,15 +90632,8 @@ var ts; } } } - if (updated) { - // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. - var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); - ts.setTextRangePosEnd(updatedArray, pos, end); - return updatedArray; - } - return nodes; + return updated !== null && updated !== void 0 ? updated : nodes; } - ts.visitNodes = visitNodes; /** * Starts a new lexical environment and visits a statement list, ending the lexical environment * and merging hoisted declarations upon completion. @@ -89421,7 +90705,7 @@ var ts; /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) : factory.getGeneratedNameForNode(parameter)), ]))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, /*initializer*/ undefined); } function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { @@ -89429,7 +90713,7 @@ var ts; context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([ factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(ts.setEmitFlags(factory.cloneNode(name), 48 /* EmitFlags.NoSourceMap */), ts.setEmitFlags(initializer, 48 /* EmitFlags.NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* EmitFlags.NoComments */)), parameter), 1536 /* EmitFlags.NoComments */)) ]), parameter), 1 /* EmitFlags.SingleLine */ | 32 /* EmitFlags.NoTrailingSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */ | 1536 /* EmitFlags.NoComments */))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, /*initializer*/ undefined); } function visitFunctionBody(node, visitor, context, nodeVisitor) { @@ -89495,7 +90779,7 @@ var ts; return factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); case 164 /* SyntaxKind.Parameter */: ts.Debug.type(node); - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + return factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 165 /* SyntaxKind.Decorator */: ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -89505,7 +90789,7 @@ var ts; return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 167 /* SyntaxKind.PropertyDeclaration */: ts.Debug.type(node); - return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), + return factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 168 /* SyntaxKind.MethodSignature */: @@ -89513,21 +90797,21 @@ var ts; return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 169 /* SyntaxKind.MethodDeclaration */: ts.Debug.type(node); - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 171 /* SyntaxKind.Constructor */: ts.Debug.type(node); - return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 172 /* SyntaxKind.GetAccessor */: ts.Debug.type(node); - return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 173 /* SyntaxKind.SetAccessor */: ts.Debug.type(node); - return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: ts.Debug.type(node); context.startLexicalEnvironment(); context.suspendLexicalEnvironment(); - return factory.updateClassStaticBlockDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 174 /* SyntaxKind.CallSignature */: ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -89536,7 +90820,7 @@ var ts; return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 176 /* SyntaxKind.IndexSignature */: ts.Debug.type(node); - return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types case 177 /* SyntaxKind.TypePredicate */: ts.Debug.type(node); @@ -89582,13 +90866,13 @@ var ts; return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); case 200 /* SyntaxKind.ImportType */: ts.Debug.type(node); - return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); case 295 /* SyntaxKind.ImportTypeAssertionContainer */: ts.Debug.type(node); return factory.updateImportTypeAssertionContainer(node, nodeVisitor(node.assertClause, visitor, ts.isNode), node.multiLine); case 197 /* SyntaxKind.NamedTupleMember */: ts.Debug.type(node); - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + return factory.updateNamedTupleMember(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 191 /* SyntaxKind.ParenthesizedType */: ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -89653,7 +90937,7 @@ var ts; return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 210 /* SyntaxKind.TaggedTemplateExpression */: ts.Debug.type(node); - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); case 211 /* SyntaxKind.TypeAssertionExpression */: ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -89701,7 +90985,7 @@ var ts; return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 226 /* SyntaxKind.ClassExpression */: ts.Debug.type(node); - return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 228 /* SyntaxKind.ExpressionWithTypeArguments */: ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); @@ -89782,22 +91066,22 @@ var ts; return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 256 /* SyntaxKind.FunctionDeclaration */: ts.Debug.type(node); - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 257 /* SyntaxKind.ClassDeclaration */: ts.Debug.type(node); - return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 258 /* SyntaxKind.InterfaceDeclaration */: ts.Debug.type(node); - return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + return factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 259 /* SyntaxKind.TypeAliasDeclaration */: ts.Debug.type(node); - return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 260 /* SyntaxKind.EnumDeclaration */: ts.Debug.type(node); - return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + return factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 261 /* SyntaxKind.ModuleDeclaration */: ts.Debug.type(node); - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + return factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); case 262 /* SyntaxKind.ModuleBlock */: ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); @@ -89809,10 +91093,10 @@ var ts; return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); case 265 /* SyntaxKind.ImportEqualsDeclaration */: ts.Debug.type(node); - return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); + return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); case 266 /* SyntaxKind.ImportDeclaration */: ts.Debug.type(node); - return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 293 /* SyntaxKind.AssertClause */: ts.Debug.type(node); return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); @@ -89836,10 +91120,10 @@ var ts; return factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); case 271 /* SyntaxKind.ExportAssignment */: ts.Debug.type(node); - return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); + return factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); case 272 /* SyntaxKind.ExportDeclaration */: ts.Debug.type(node); - return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 273 /* SyntaxKind.NamedExports */: ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); @@ -90932,6 +92216,126 @@ var ts; return !ts.isStatic(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); } ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; + if (decorators || ts.hasDecorators(parameter)) { + if (!decorators) { + decorators = new Array(numParameters); + } + decorators[i] = ts.getDecorators(parameter); + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfClass(node) { + var decorators = ts.getDecorators(node); + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + ts.getAllDecoratorsOfClass = getAllDecoratorsOfClass; + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param parent The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(member, parent) { + switch (member.kind) { + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: + return getAllDecoratorsOfAccessors(member, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 167 /* SyntaxKind.PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + ts.getAllDecoratorsOfClassElement = getAllDecoratorsOfClassElement; + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param parent The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(accessor, parent) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(parent.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = ts.hasDecorators(firstAccessor) ? firstAccessor : + secondAccessor && ts.hasDecorators(secondAccessor) ? secondAccessor : + undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = ts.getDecorators(firstAccessorWithDecorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters, + getDecorators: getAccessor && ts.getDecorators(getAccessor), + setDecorators: setAccessor && ts.getDecorators(setAccessor) + }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = ts.getDecorators(method); + var parameters = getDecoratorsOfParameters(method); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = ts.getDecorators(property); + if (!ts.some(decorators)) { + return undefined; + } + return { decorators: decorators }; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -91205,8 +92609,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */ - && !(element.transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -91272,7 +92676,7 @@ var ts; if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -91494,8 +92898,6 @@ var ts; var USE_NEW_TYPE_METADATA_FORMAT = false; var TypeScriptSubstitutionFlags; (function (TypeScriptSubstitutionFlags) { - /** Enables substitutions for decorated classes. */ - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; /** Enables substitutions for namespace exports. */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; /* Enables substitutions for unqualified enum members */ @@ -91521,9 +92923,9 @@ var ts; var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); - var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var typeSerializer = compilerOptions.emitDecoratorMetadata ? ts.createRuntimeTypeSerializer(context) : undefined; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -91538,7 +92940,6 @@ var ts; var currentNamespace; var currentNamespaceContainerName; var currentLexicalScope; - var currentNameScope; var currentScopeFirstDeclarationsOfName; var currentClassHasParameterProperties; /** @@ -91546,11 +92947,6 @@ var ts; * They are persisted between each SourceFile transformation and should not be reset. */ var enabledSubstitutions; - /** - * A map that keeps track of aliases created for classes with decorators to avoid issues - * with the double-binding behavior of classes. - */ - var classAliases; /** * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. @@ -91594,7 +92990,6 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentLexicalScope; - var savedCurrentNameScope = currentNameScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties; // Handle state changes before visiting a node. @@ -91605,7 +93000,6 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } currentLexicalScope = savedCurrentScope; - currentNameScope = savedCurrentNameScope; currentClassHasParameterProperties = savedCurrentClassHasParameterProperties; return visited; } @@ -91621,7 +93015,6 @@ var ts; case 262 /* SyntaxKind.ModuleBlock */: case 235 /* SyntaxKind.Block */: currentLexicalScope = node; - currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; case 257 /* SyntaxKind.ClassDeclaration */: @@ -91639,10 +93032,6 @@ var ts; // programs may also have an undefined name. ts.Debug.assert(node.kind === 257 /* SyntaxKind.ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)); } - if (ts.isClassDeclaration(node)) { - // XXX: should probably also cover interfaces and type aliases that can have type variables? - currentNameScope = node; - } break; } } @@ -91744,40 +93133,73 @@ var ts; return node; } /** - * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * Gets a specialized visitor that visits the immediate children of a class with TypeScript syntax. * - * @param node The node to visit. + * @param parent The class containing the elements to visit. */ - function classElementVisitor(node) { - return saveStateAndInvoke(node, classElementVisitorWorker); + function getClassElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return classElementVisitorWorker(n, parent); }); }; } /** * Specialized visitor that visits the immediate children of a class with TypeScript syntax. * * @param node The node to visit. */ - function classElementVisitorWorker(node) { + function classElementVisitorWorker(node, parent) { switch (node.kind) { case 171 /* SyntaxKind.Constructor */: return visitConstructor(node); case 167 /* SyntaxKind.PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. - return visitPropertyDeclaration(node); - case 176 /* SyntaxKind.IndexSignature */: + return visitPropertyDeclaration(node, parent); case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - // Fallback to the default visit behavior. - return visitorWorker(node); + return ts.visitEachChild(node, visitor, context); case 234 /* SyntaxKind.SemicolonClassElement */: return node; + case 176 /* SyntaxKind.IndexSignature */: + // Index signatures are elided + return; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function getObjectLiteralElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return objectLiteralElementVisitorWorker(n, parent); }); }; + } + function objectLiteralElementVisitorWorker(node, parent) { + switch (node.kind) { + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 298 /* SyntaxKind.SpreadAssignment */: + return visitor(node); + case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); + case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { + if (ts.isDecorator(node)) + return undefined; if (ts.modifierToFlag(node.kind) & 116958 /* ModifierFlags.TypeScriptModifier */) { return undefined; } @@ -91845,22 +93267,14 @@ var ts; // TypeScript type nodes are elided. // falls through case 176 /* SyntaxKind.IndexSignature */: - // TypeScript index signatures are elided. - // falls through - case 165 /* SyntaxKind.Decorator */: - // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + // TypeScript index signatures are elided. return undefined; case 259 /* SyntaxKind.TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return factory.createNotEmittedStatement(node); - case 167 /* SyntaxKind.PropertyDeclaration */: - // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects - return visitPropertyDeclaration(node); case 264 /* SyntaxKind.NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 171 /* SyntaxKind.Constructor */: - return visitConstructor(node); case 258 /* SyntaxKind.InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. @@ -91894,16 +93308,15 @@ var ts; case 228 /* SyntaxKind.ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); + case 205 /* SyntaxKind.ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 171 /* SyntaxKind.Constructor */: + case 167 /* SyntaxKind.PropertyDeclaration */: case 169 /* SyntaxKind.MethodDeclaration */: - // TypeScript method declarations may have decorators, modifiers - // or type annotations. - return visitMethodDeclaration(node); case 172 /* SyntaxKind.GetAccessor */: - // Get Accessors can have TypeScript modifiers, decorators, and type annotations. - return visitGetAccessor(node); case 173 /* SyntaxKind.SetAccessor */: - // Set Accessors can have TypeScript modifiers and type annotations. - return visitSetAccessor(node); + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + return ts.Debug.fail("Class and object literal elements must be visited with their respective visitors"); case 256 /* SyntaxKind.FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); @@ -91969,6 +93382,9 @@ var ts; !ts.isJsonSourceFile(node); return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } + function visitObjectLiteralExpression(node) { + return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, getObjectLiteralElementVisitor(node), ts.isObjectLiteralElement)); + } function getClassFacts(node, staticProperties) { var facts = 0 /* ClassFacts.None */; if (ts.some(staticProperties)) @@ -91991,17 +93407,18 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { - return ts.some(node.decorators) + return ts.hasDecorators(node) || ts.some(node.typeParameters) || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) || ts.some(node.members, hasTypeScriptClassSyntax); } function visitClassDeclaration(node) { if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */))) { - return ts.visitEachChild(node, visitor, context); + return factory.updateClassDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); var facts = getClassFacts(node, staticProperties); @@ -92009,14 +93426,25 @@ var ts; context.startLexicalEnvironment(); } var name = node.name || (facts & 5 /* ClassFacts.NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined); - var classStatement = facts & 2 /* ClassFacts.HasConstructorDecorators */ - ? createClassDeclarationHeadWithDecorators(node, name) - : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : ts.elideNodes(factory, node.modifiers); // preserve positions, if available + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var classStatement = factory.updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { + emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; + } + ts.setEmitFlags(classStatement, emitFlags); var statements = [classStatement]; - // Write any decorators of the node. - addClassElementDecorationStatements(statements, node, /*isStatic*/ false); - addClassElementDecorationStatements(statements, node, /*isStatic*/ true); - addConstructorDecorationStatement(statements, node); if (facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) { // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the // 'es2015' transformer can properly nest static initializers and decorators. The result @@ -92076,164 +93504,13 @@ var ts; } return ts.singleOrMany(statements); } - /** - * Transforms a non-decorated class declaration and appends the resulting statements. - * - * @param node A ClassDeclaration node. - * @param name The name of the class. - * @param facts Precomputed facts about the class. - */ - function createClassDeclarationHeadWithoutDecorators(node, name, facts) { - // ${modifiers} class ${name} ${heritageClauses} { - // ${members} - // } - // we do not emit modifiers on the declaration if we are emitting an IIFE - var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) - ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) - : undefined; - var classDeclaration = factory.createClassDeclaration( - /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - // To better align with the old emitter, we should not emit a trailing source map - // entry if the class has static properties. - var emitFlags = ts.getEmitFlags(node); - if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { - emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; - } - ts.setTextRange(classDeclaration, node); - ts.setOriginalNode(classDeclaration, node); - ts.setEmitFlags(classDeclaration, emitFlags); - return classDeclaration; - } - /** - * Transforms a decorated class declaration and appends the resulting statements. If - * the class requires an alias to avoid issues with double-binding, the alias is returned. - */ - function createClassDeclarationHeadWithDecorators(node, name) { - // When we emit an ES6 class that has a class decorator, we must tailor the - // emit to certain specific cases. - // - // In the simplest case, we emit the class declaration as a let declaration, and - // evaluate decorators after the close of the class body: - // - // [Example 1] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // class C { | } - // } | C = __decorate([dec], C); - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | } - // } | C = __decorate([dec], C); - // | export { C }; - // --------------------------------------------------------------------- - // - // If a class declaration contains a reference to itself *inside* of the class body, - // this introduces two bindings to the class: One outside of the class body, and one - // inside of the class body. If we apply decorators as in [Example 1] above, there - // is the possibility that the decorator `dec` will return a new value for the - // constructor, which would result in the binding inside of the class no longer - // pointing to the same reference as the binding outside of the class. - // - // As a result, we must instead rewrite all references to the class *inside* of the - // class body to instead point to a local temporary alias for the class: - // - // [Example 2] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = C_1 = class C { - // class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | var C_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export { C }; - // | var C_1; - // --------------------------------------------------------------------- - // - // If a class declaration is the default export of a module, we instead emit - // the export after the decorated declaration: - // - // [Example 3] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let default_1 = class { - // export default class { | } - // } | default_1 = __decorate([dec], default_1); - // | export default default_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | } - // } | C = __decorate([dec], C); - // | export default C; - // --------------------------------------------------------------------- - // - // If the class declaration is the default export and a reference to itself - // inside of the class body, we must emit both an alias for the class *and* - // move the export after the declaration: - // - // [Example 4] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export default C; - // | var C_1; - // --------------------------------------------------------------------- - // - var location = ts.moveRangePastDecorators(node); - var classAlias = getClassAliasIfNeeded(node); - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - // ... = class ${name} ${heritageClauses} { - // ${members} - // } - var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node); - var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, location); - // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference - // or decoratedClassAlias if the class contain self-reference. - var statement = factory.createVariableStatement( - /*modifiers*/ undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(declName, - /*exclamationToken*/ undefined, - /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) - ], 1 /* NodeFlags.Let */)); - ts.setOriginalNode(statement, node); - ts.setTextRange(statement, location); - ts.setCommentRange(statement, node); - return statement; - } function visitClassExpression(node) { - if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { - return ts.visitEachChild(node, visitor, context); - } - var classExpression = factory.createClassExpression( - /*decorators*/ undefined, - /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, node); - return classExpression; + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + return factory.updateClassExpression(node, decorators, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), isClassLikeDeclarationWithTypeScriptSyntax(node) ? + transformClassMembers(node) : + ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } /** * Transforms the members of a class. @@ -92250,7 +93527,6 @@ var ts; var parameter = parametersWithPropertyAssignments_1[_i]; if (ts.isIdentifier(parameter.name)) { members.push(ts.setOriginalNode(factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameter.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -92258,159 +93534,9 @@ var ts; } } } - ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + ts.addRange(members, ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - /** - * Gets either the static or instance members of a class that are decorated, or have - * parameters that are decorated. - * - * @param node The class containing the member. - * @param isStatic A value indicating whether to retrieve static or instance members of - * the class. - */ - function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); - } - /** - * Determines whether a class member is a static member of a class that is decorated, or - * has parameters that are decorated. - * - * @param member The class member. - */ - function isStaticDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ true, parent); - } - /** - * Determines whether a class member is an instance member of a class that is decorated, - * or has parameters that are decorated. - * - * @param member The class member. - */ - function isInstanceDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ false, parent); - } - /** - * Determines whether a class member is either a static or an instance member of a class - * that is decorated, or has parameters that are decorated. - * - * @param member The class member. - */ - function isDecoratedClassElement(member, isStaticElement, parent) { - return ts.nodeOrChildIsDecorated(member, parent) - && isStaticElement === ts.isStatic(member); - } - /** - * Gets an array of arrays of decorators for the parameters of a function-like node. - * The offset into the result array should correspond to the offset of the parameter. - * - * @param node The function-like node. - */ - function getDecoratorsOfParameters(node) { - var decorators; - if (node) { - var parameters = node.parameters; - var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); - var firstParameterOffset = firstParameterIsThis ? 1 : 0; - var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i + firstParameterOffset]; - if (decorators || parameter.decorators) { - if (!decorators) { - decorators = new Array(numParameters); - } - decorators[i] = parameter.decorators; - } - } - } - return decorators; - } - /** - * Gets an AllDecorators object containing the decorators for the class and the decorators for the - * parameters of the constructor of the class. - * - * @param node The class node. - */ - function getAllDecoratorsOfConstructor(node) { - var decorators = node.decorators; - var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); - if (!decorators && !parameters) { - return undefined; - } - return { - decorators: decorators, - parameters: parameters - }; - } - /** - * Gets an AllDecorators object containing the decorators for the member and its parameters. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function getAllDecoratorsOfClassElement(node, member) { - switch (member.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - return getAllDecoratorsOfAccessors(node, member); - case 169 /* SyntaxKind.MethodDeclaration */: - return getAllDecoratorsOfMethod(member); - case 167 /* SyntaxKind.PropertyDeclaration */: - return getAllDecoratorsOfProperty(member); - default: - return undefined; - } - } - /** - * Gets an AllDecorators object containing the decorators for the accessor and its parameters. - * - * @param node The class node that contains the accessor. - * @param accessor The class accessor member. - */ - function getAllDecoratorsOfAccessors(node, accessor) { - if (!accessor.body) { - return undefined; - } - var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; - if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { - return undefined; - } - var decorators = firstAccessorWithDecorators.decorators; - var parameters = getDecoratorsOfParameters(setAccessor); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the method and its parameters. - * - * @param method The class method member. - */ - function getAllDecoratorsOfMethod(method) { - if (!method.body) { - return undefined; - } - var decorators = method.decorators; - var parameters = getDecoratorsOfParameters(method); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the property. - * - * @param property The class property member. - */ - function getAllDecoratorsOfProperty(property) { - var decorators = property.decorators; - if (!decorators) { - return undefined; - } - return { decorators: decorators }; - } /** * Transforms all of the decorators for a declaration into an array of expressions. * @@ -92418,212 +93544,89 @@ var ts; * @param allDecorators An object containing all of the decorators for the declaration. */ function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + var _a, _b, _c, _d; if (!allDecorators) { return undefined; } - var decoratorExpressions = []; - ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); - ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, container, decoratorExpressions); - return decoratorExpressions; - } - /** - * Generates statements used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate statements for static or - * instance members. - */ - function addClassElementDecorationStatements(statements, node, isStatic) { - ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); - } - /** - * Generates expressions used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate expressions for static or - * instance members. - */ - function generateClassElementDecorationExpressions(node, isStatic) { - var members = getDecoratedClassElements(node, isStatic); - var expressions; - for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { - var member = members_8[_i]; - var expression = generateClassElementDecorationExpression(node, member); - if (expression) { - if (!expressions) { - expressions = [expression]; - } - else { - expressions.push(expression); - } - } - } - return expressions; - } - /** - * Generates an expression used to evaluate class element decorators at runtime. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function generateClassElementDecorationExpression(node, member) { - var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - // Emit the call to __decorate. Given the following: - // - // class C { - // @dec method(@dec2 x) {} - // @dec get accessor() {} - // @dec prop; - // } - // - // The emit for a method is: - // - // __decorate([ - // dec, - // __param(0, dec2), - // __metadata("design:type", Function), - // __metadata("design:paramtypes", [Object]), - // __metadata("design:returntype", void 0) - // ], C.prototype, "method", null); - // - // The emit for an accessor is: - // - // __decorate([ - // dec - // ], C.prototype, "accessor", null); - // - // The emit for a property is: - // - // __decorate([ - // dec - // ], C.prototype, "prop"); - // - var prefix = getClassMemberPrefix(node, member); - var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); - var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ - ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ - // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it - // should not invoke `Object.getOwnPropertyDescriptor`. - ? factory.createVoidZero() - // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. - // We have this extra argument here so that we can inject an explicit property descriptor at a later date. - : factory.createNull() - : undefined; - var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); - ts.setTextRange(helper, ts.moveRangePastDecorators(member)); - ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - return helper; - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function addConstructorDecorationStatement(statements, node) { - var expression = generateConstructorDecorationExpression(node); - if (expression) { - statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); - } - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function generateConstructorDecorationExpression(node) { - var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); - var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); - ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); - ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); - return expression; - } - /** - * Transforms a decorator into an expression. - * - * @param decorator The decorator node. - */ - function transformDecorator(decorator) { - return ts.visitNode(decorator.expression, visitor, ts.isExpression); + var decorators = ts.visitArray(allDecorators.decorators, visitor, ts.isDecorator); + var parameterDecorators = ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter); + var metadataDecorators = ts.some(decorators) || ts.some(parameterDecorators) ? getTypeMetadata(node, container) : undefined; + var result = factory.createNodeArray(ts.concatenate(ts.concatenate(decorators, parameterDecorators), metadataDecorators)); + var pos = (_b = (_a = ts.firstOrUndefined(allDecorators.decorators)) === null || _a === void 0 ? void 0 : _a.pos) !== null && _b !== void 0 ? _b : -1; + var end = (_d = (_c = ts.lastOrUndefined(allDecorators.decorators)) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : -1; + ts.setTextRangePosEnd(result, pos, end); + return result; } /** - * Transforms the decorators of a parameter. + * Transforms the decorators of a parameter into decorators of the class/method. * - * @param decorators The decorators for the parameter at the provided offset. + * @param parameterDecorators The decorators for the parameter at the provided offset. * @param parameterOffset The offset of the parameter. */ - function transformDecoratorsOfParameter(decorators, parameterOffset) { - var expressions; - if (decorators) { - expressions = []; - for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { - var decorator = decorators_1[_i]; - var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); - ts.setTextRange(helper, decorator.expression); + function transformDecoratorsOfParameter(parameterDecorators, parameterOffset) { + if (parameterDecorators) { + var decorators = []; + for (var _i = 0, parameterDecorators_1 = parameterDecorators; _i < parameterDecorators_1.length; _i++) { + var parameterDecorator = parameterDecorators_1[_i]; + var expression = ts.visitNode(parameterDecorator.expression, visitor, ts.isExpression); + var helper = emitHelpers().createParamHelper(expression, parameterOffset); + ts.setTextRange(helper, parameterDecorator.expression); ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - expressions.push(helper); + var decorator = factory.createDecorator(helper); + ts.setSourceMapRange(decorator, parameterDecorator.expression); + ts.setCommentRange(decorator, parameterDecorator.expression); + ts.setEmitFlags(decorator, 1536 /* EmitFlags.NoComments */); + decorators.push(decorator); } + return decorators; } - return expressions; } /** - * Adds optional type metadata for a declaration. + * Gets optional type metadata for a declaration. * * @param node The declaration node. - * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node, container, decoratorExpressions) { - if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, container, decoratorExpressions); - } - else { - addOldTypeMetadata(node, container, decoratorExpressions); - } + function getTypeMetadata(node, container) { + return USE_NEW_TYPE_METADATA_FORMAT ? + getNewTypeMetadata(node, container) : + getOldTypeMetadata(node, container); } - function addOldTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getOldTypeMetadata(node, container) { + if (typeSerializer) { + var decorators = void 0; if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node))); + var typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(typeMetadata)); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container))); + var paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container)); + decorators = ts.append(decorators, factory.createDecorator(paramTypesMetadata)); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node))); + var returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(returnTypeMetadata)); } + return decorators; } } - function addNewTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getNewTypeMetadata(node, container) { + if (typeSerializer) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + var typeProperty = factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, typeProperty); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + var paramTypeProperty = factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container))); + properties = ts.append(properties, paramTypeProperty); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + var returnTypeProperty = factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, returnTypeProperty); } if (properties) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true))); + var typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)); + return [factory.createDecorator(typeInfoMetadata)]; } } } @@ -92670,347 +93673,6 @@ var ts; } return false; } - function getAccessorTypeNode(node) { - var accessors = resolver.getAllAccessorDeclarations(node); - return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) - || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); - } - /** - * Serializes the type of a node for use with decorator type metadata. - * - * @param node The node that should have its type serialized. - */ - function serializeTypeOfNode(node) { - switch (node.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 164 /* SyntaxKind.Parameter */: - return serializeTypeNode(node.type); - case 173 /* SyntaxKind.SetAccessor */: - case 172 /* SyntaxKind.GetAccessor */: - return serializeTypeNode(getAccessorTypeNode(node)); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - return factory.createIdentifier("Function"); - default: - return factory.createVoidZero(); - } - } - /** - * Serializes the types of the parameters of a node for use with decorator type metadata. - * - * @param node The node that should have its parameter types serialized. - */ - function serializeParameterTypesOfNode(node, container) { - var valueDeclaration = ts.isClassLike(node) - ? ts.getFirstConstructorWithBody(node) - : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) - ? node - : undefined; - var expressions = []; - if (valueDeclaration) { - var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); - var numParameters = parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { - continue; - } - if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); - } - else { - expressions.push(serializeTypeOfNode(parameter)); - } - } - } - return factory.createArrayLiteralExpression(expressions); - } - function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { - var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; - if (setAccessor) { - return setAccessor.parameters; - } - } - return node.parameters; - } - /** - * Serializes the return type of a node for use with decorator type metadata. - * - * @param node The node that should have its return type serialized. - */ - function serializeReturnTypeOfNode(node) { - if (ts.isFunctionLike(node) && node.type) { - return serializeTypeNode(node.type); - } - else if (ts.isAsyncFunction(node)) { - return factory.createIdentifier("Promise"); - } - return factory.createVoidZero(); - } - /** - * Serializes a type node for use with decorator type metadata. - * - * Types are serialized in the following fashion: - * - Void types point to "undefined" (e.g. "void 0") - * - Function and Constructor types point to the global "Function" constructor. - * - Interface types with a call or construct signature types point to the global - * "Function" constructor. - * - Array and Tuple types point to the global "Array" constructor. - * - Type predicates and booleans point to the global "Boolean" constructor. - * - String literal types and strings point to the global "String" constructor. - * - Enum and number types point to the global "Number" constructor. - * - Symbol types point to the global "Symbol" constructor. - * - Type references to classes (or class-like variables) point to the constructor for the class. - * - Anything else points to the global "Object" constructor. - * - * @param node The type node to serialize. - */ - function serializeTypeNode(node) { - if (node === undefined) { - return factory.createIdentifier("Object"); - } - switch (node.kind) { - case 114 /* SyntaxKind.VoidKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - return factory.createVoidZero(); - case 191 /* SyntaxKind.ParenthesizedType */: - return serializeTypeNode(node.type); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - return factory.createIdentifier("Function"); - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: - return factory.createIdentifier("Array"); - case 177 /* SyntaxKind.TypePredicate */: - case 133 /* SyntaxKind.BooleanKeyword */: - return factory.createIdentifier("Boolean"); - case 198 /* SyntaxKind.TemplateLiteralType */: - case 150 /* SyntaxKind.StringKeyword */: - return factory.createIdentifier("String"); - case 148 /* SyntaxKind.ObjectKeyword */: - return factory.createIdentifier("Object"); - case 196 /* SyntaxKind.LiteralType */: - switch (node.literal.kind) { - case 10 /* SyntaxKind.StringLiteral */: - case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: - return factory.createIdentifier("String"); - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 8 /* SyntaxKind.NumericLiteral */: - return factory.createIdentifier("Number"); - case 9 /* SyntaxKind.BigIntLiteral */: - return getGlobalBigIntNameWithFallback(); - case 110 /* SyntaxKind.TrueKeyword */: - case 95 /* SyntaxKind.FalseKeyword */: - return factory.createIdentifier("Boolean"); - case 104 /* SyntaxKind.NullKeyword */: - return factory.createVoidZero(); - default: - return ts.Debug.failBadSyntaxKind(node.literal); - } - case 147 /* SyntaxKind.NumberKeyword */: - return factory.createIdentifier("Number"); - case 158 /* SyntaxKind.BigIntKeyword */: - return getGlobalBigIntNameWithFallback(); - case 151 /* SyntaxKind.SymbolKeyword */: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case 178 /* SyntaxKind.TypeReference */: - return serializeTypeReferenceNode(node); - case 188 /* SyntaxKind.IntersectionType */: - case 187 /* SyntaxKind.UnionType */: - return serializeTypeList(node.types); - case 189 /* SyntaxKind.ConditionalType */: - return serializeTypeList([node.trueType, node.falseType]); - case 193 /* SyntaxKind.TypeOperator */: - if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { - return serializeTypeNode(node.type); - } - break; - case 181 /* SyntaxKind.TypeQuery */: - case 194 /* SyntaxKind.IndexedAccessType */: - case 195 /* SyntaxKind.MappedType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 192 /* SyntaxKind.ThisType */: - case 200 /* SyntaxKind.ImportType */: - break; - // handle JSDoc types from an invalid parse - case 312 /* SyntaxKind.JSDocAllType */: - case 313 /* SyntaxKind.JSDocUnknownType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 318 /* SyntaxKind.JSDocVariadicType */: - case 319 /* SyntaxKind.JSDocNamepathType */: - break; - case 314 /* SyntaxKind.JSDocNullableType */: - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 316 /* SyntaxKind.JSDocOptionalType */: - return serializeTypeNode(node.type); - default: - return ts.Debug.failBadSyntaxKind(node); - } - return factory.createIdentifier("Object"); - } - function serializeTypeList(types) { - // Note when updating logic here also update getEntityNameForDecoratorMetadata - // so that aliases can be marked as referenced - var serializedUnion; - for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { - var typeNode = types_23[_i]; - while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 196 /* SyntaxKind.LiteralType */ && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */ || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { - // One of the individual is global object, return immediately - return serializedIndividual; - } - // If there exists union that is not void 0 expression, check if the the common type is identifier. - // anything more complex and we will just default to Object - else if (serializedUnion) { - // Different types - if (!ts.isIdentifier(serializedUnion) || - !ts.isIdentifier(serializedIndividual) || - serializedUnion.escapedText !== serializedIndividual.escapedText) { - return factory.createIdentifier("Object"); - } - } - else { - // Initialize the union type - serializedUnion = serializedIndividual; - } - } - // If we were able to find common type, use it - return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never - } - /** - * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with - * decorator type metadata. - * - * @param node The type reference node. - */ - function serializeTypeReferenceNode(node) { - var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); - switch (kind) { - case ts.TypeReferenceSerializationKind.Unknown: - // From conditional type type reference that cannot be resolved is Similar to any or unknown - if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { - return factory.createIdentifier("Object"); - } - var serialized = serializeEntityNameAsExpressionFallback(node.typeName); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), - /*questionToken*/ undefined, temp, - /*colonToken*/ undefined, factory.createIdentifier("Object")); - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName); - case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: - return factory.createVoidZero(); - case ts.TypeReferenceSerializationKind.BigIntLikeType: - return getGlobalBigIntNameWithFallback(); - case ts.TypeReferenceSerializationKind.BooleanType: - return factory.createIdentifier("Boolean"); - case ts.TypeReferenceSerializationKind.NumberLikeType: - return factory.createIdentifier("Number"); - case ts.TypeReferenceSerializationKind.StringLikeType: - return factory.createIdentifier("String"); - case ts.TypeReferenceSerializationKind.ArrayLikeType: - return factory.createIdentifier("Array"); - case ts.TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - return factory.createIdentifier("Function"); - case ts.TypeReferenceSerializationKind.Promise: - return factory.createIdentifier("Promise"); - case ts.TypeReferenceSerializationKind.ObjectType: - return factory.createIdentifier("Object"); - default: - return ts.Debug.assertNever(kind); - } - } - function createCheckedValue(left, right) { - return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right); - } - /** - * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 79 /* SyntaxKind.Identifier */) { - // A -> typeof A !== undefined && A - var copied = serializeEntityNameAsExpression(node); - return createCheckedValue(copied, copied); - } - if (node.left.kind === 79 /* SyntaxKind.Identifier */) { - // A.B -> typeof A !== undefined && A.B - return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); - } - // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C - var left = serializeEntityNameAsExpressionFallback(node.left); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right)); - } - /** - * Serializes an entity name as an expression for decorator type metadata. - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpression(node) { - switch (node.kind) { - case 79 /* SyntaxKind.Identifier */: - // Create a clone of the name with a new parent, and treat it as if it were - // a source tree node for the purposes of the checker. - var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); - name.original = undefined; - ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. - return name; - case 161 /* SyntaxKind.QualifiedName */: - return serializeQualifiedNameAsExpression(node); - } - } - /** - * Serializes an qualified name as an expression for decorator type metadata. - * - * @param node The qualified name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * qualified name at runtime. - */ - function serializeQualifiedNameAsExpression(node) { - return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); - } - /** - * Gets an expression that points to the global "Symbol" constructor at runtime if it is - * available. - */ - function getGlobalSymbolNameWithFallback() { - return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("Symbol"), - /*colonToken*/ undefined, factory.createIdentifier("Object")); - } - /** - * Gets an expression that points to the global "BigInt" constructor at runtime if it is - * available. - */ - function getGlobalBigIntNameWithFallback() { - return languageVersion < 99 /* ScriptTarget.ESNext */ - ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("BigInt"), - /*colonToken*/ undefined, factory.createIdentifier("Object")) - : factory.createIdentifier("BigInt"); - } /** * Gets an expression that represents a property name (for decorated properties or enums). * For a computed property, a name is generated for the node. @@ -93047,7 +93709,7 @@ var ts; // The names are used more than once when: // - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments). // - the property has a decorator. - if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) { + if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.hasDecorators(member))) { var expression = ts.visitNode(name.expression, visitor, ts.isExpression); var innerExpression = ts.skipPartiallyEmittedExpressions(expression); if (!ts.isSimpleInlineableExpression(innerExpression)) { @@ -93095,28 +93757,29 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } - function visitPropertyDeclaration(node) { - if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)) { + function visitPropertyDeclaration(node, parent) { + var isAmbient = node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */); + if (isAmbient && !ts.hasDecorators(node)) { return undefined; } - var updated = factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), + var allDecorators = ts.getAllDecoratorsOfClassElement(node, parent); + var decorators = transformAllDecoratorsOfDeclaration(node, parent, allDecorators); + // Preserve a `declare x` property with decorators to be handled by the decorators transform + if (isAmbient) { + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, factory.createModifiersFromModifierFlags(2 /* ModifierFlags.Ambient */)), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } return factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node)); } function transformConstructorBody(body, constructor) { @@ -93155,7 +93818,8 @@ var ts; statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, prologueStatementCount), true), parameterPropertyAssignments, true), statements.slice(prologueStatementCount), true); } // Add remaining statements from the body, skipping the super() call if it was found and any (already added) prologue statements - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, superStatementIndex + 1 + prologueStatementCount)); + var start = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, start)); // End the lexical environment. statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true); @@ -93181,22 +93845,19 @@ var ts; ts.setEmitFlags(localName, 1536 /* EmitFlags.NoComments */); return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(factory.createExpressionStatement(factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1)))); } - function visitMethodDeclaration(node) { + function visitMethodDeclaration(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + var allDecorators = ts.isClassLike(parent) ? ts.getAllDecoratorsOfClassElement(node, parent) : undefined; + var decorators = ts.isClassLike(parent) ? transformAllDecoratorsOfDeclaration(node, parent, allDecorators) : undefined; + return factory.updateMethodDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), node.asteriskToken, visitPropertyNameOfClassElement(node), /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } /** * Determines whether to emit an accessor declaration. We should not emit the @@ -93207,41 +93868,36 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)); } - function visitGetAccessor(node) { + function visitGetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateGetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } - function visitSetAccessor(node) { + function visitSetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateSetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return factory.createNotEmittedStatement(node); } - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + var updated = factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); if (isExportOfNamespace(node)) { @@ -93270,9 +93926,8 @@ var ts; if (ts.parameterIsThisKeyword(node)) { return undefined; } - var updated = factory.updateParameterDeclaration(node, - /*decorators*/ undefined, - /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), // preserve positions, if available + node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); if (updated !== node) { @@ -93432,7 +94087,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); @@ -93662,7 +94317,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); @@ -93775,7 +94430,6 @@ var ts; compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ ? factory.updateImportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, importClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -93850,7 +94504,6 @@ var ts; var exportClause = ts.visitNode(node.exportClause, function (bindings) { return visitNamedExportBindings(bindings, allowEmpty); }, ts.isNamedExportBindings); return exportClause ? factory.updateExportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -93908,7 +94561,6 @@ var ts; // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'. if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */) { return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, node.moduleReference.expression, /*assertClause*/ undefined), node), node); @@ -93968,12 +94620,6 @@ var ts; return isExternalModuleExport(node) && ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */); } - /** - * Creates a statement for the provided expression. This is used in calls to `map`. - */ - function expressionToStatement(expression) { - return factory.createExpressionStatement(expression); - } function addExportMemberAssignment(statements, node) { var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); @@ -94005,44 +94651,12 @@ var ts; function getNamespaceContainerName(node) { return factory.getGeneratedNameForNode(node); } - /** - * Gets a local alias for a class declaration if it is a decorated class with an internal - * reference to the static side of the class. This is necessary to avoid issues with - * double-binding semantics for the class name. - */ - function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { - enableSubstitutionForClassAliases(); - var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - hoistVariableDeclaration(classAlias); - return classAlias; - } - } - function getClassPrototype(node) { - return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); - } - function getClassMemberPrefix(node, member) { - return ts.isStatic(member) - ? factory.getDeclarationName(node) - : getClassPrototype(node); - } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */; context.enableSubstitution(79 /* SyntaxKind.Identifier */); } } - function enableSubstitutionForClassAliases() { - if ((enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) === 0) { - enabledSubstitutions |= 1 /* TypeScriptSubstitutionFlags.ClassAliases */; - // We need to enable substitutions for identifiers. This allows us to - // substitute class names inside of a class declaration. - context.enableSubstitution(79 /* SyntaxKind.Identifier */); - // Keep track of class aliases. - classAliases = []; - } - } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2 /* TypeScriptSubstitutionFlags.NamespaceExports */) === 0) { enabledSubstitutions |= 2 /* TypeScriptSubstitutionFlags.NamespaceExports */; @@ -94127,32 +94741,9 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - return trySubstituteClassAlias(node) - || trySubstituteNamespaceExportedName(node) + return trySubstituteNamespaceExportedName(node) || node; } - function trySubstituteClassAlias(node) { - if (enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - // Also, when emitting statics for class expressions, we must substitute a class alias for - // constructor references in static property initializers. - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = classAliases[declaration.id]; // TODO: GH#18217 - if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; - } - } - } - } - return undefined; - } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { @@ -94290,7 +94881,7 @@ var ts; return visited; } function visitorWorker(node, valueIsDiscarded) { - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */) { + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */) { switch (node.kind) { case 226 /* SyntaxKind.ClassExpression */: case 257 /* SyntaxKind.ClassDeclaration */: @@ -94305,8 +94896,8 @@ var ts; return visitClassStaticBlockDeclaration(node); } } - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */ || - node.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */ && + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */ || + node.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */ && shouldTransformSuperInStaticInitializers && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { @@ -94446,7 +95037,7 @@ var ts; return node; } function visitMethodOrAccessorDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.isPrivateIdentifier(node.name)) { return ts.visitEachChild(node, classElementVisitor, context); } @@ -94458,7 +95049,7 @@ var ts; } var functionName = getHoistedFunctionName(node); if (functionName) { - getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return ts.isModifier(m) && !ts.isStaticModifier(m); }), node.asteriskToken, functionName, /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); } @@ -94482,7 +95073,7 @@ var ts; } } function visitPropertyDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (ts.isPrivateIdentifier(node.name)) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { if (ts.isStatic(node)) { @@ -94490,8 +95081,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + return factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); @@ -94513,9 +95103,7 @@ var ts; if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); if (initializerStatement) { - var staticBlock = factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([initializerStatement])); + var staticBlock = factory.createClassStaticBlockDeclaration(factory.createBlock([initializerStatement])); ts.setOriginalNode(staticBlock, node); ts.setCommentRange(staticBlock, node); // Set the comment range for the statement to an empty synthetic range @@ -94591,10 +95179,11 @@ var ts; } function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) { if (node.operator === 45 /* SyntaxKind.PlusPlusToken */ || node.operator === 46 /* SyntaxKind.MinusMinusToken */) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + var operand = ts.skipParentheses(node.operand); + if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(operand)) { var info = void 0; - if (info = accessPrivateIdentifier(node.operand.name)) { - var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression); + if (info = accessPrivateIdentifier(operand.name)) { + var receiver = ts.visitNode(operand.expression, visitor, ts.isExpression); var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; var expression = createPrivateIdentifierAccess(info, readExpression); var temp = ts.isPrefixUnaryExpression(node) || valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); @@ -94610,7 +95199,7 @@ var ts; } } else if (shouldTransformSuperInStaticInitializers && - ts.isSuperProperty(node.operand) && + ts.isSuperProperty(operand) && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { // converts `++super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = ++_a), _classTemp), _b)` @@ -94623,31 +95212,31 @@ var ts; // converts `super[f()]--` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = _b--), _classTemp), _c)` var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; if (facts & 1 /* ClassFacts.ClassWasDecorated */) { - var operand = visitInvalidSuperProperty(node.operand); + var expression = visitInvalidSuperProperty(operand); return ts.isPrefixUnaryExpression(node) ? - factory.updatePrefixUnaryExpression(node, operand) : - factory.updatePostfixUnaryExpression(node, operand); + factory.updatePrefixUnaryExpression(node, expression) : + factory.updatePostfixUnaryExpression(node, expression); } if (classConstructor && superClassReference) { var setterName = void 0; var getterName = void 0; - if (ts.isPropertyAccessExpression(node.operand)) { - if (ts.isIdentifier(node.operand.name)) { - getterName = setterName = factory.createStringLiteralFromNode(node.operand.name); + if (ts.isPropertyAccessExpression(operand)) { + if (ts.isIdentifier(operand.name)) { + getterName = setterName = factory.createStringLiteralFromNode(operand.name); } } else { - if (ts.isSimpleInlineableExpression(node.operand.argumentExpression)) { - getterName = setterName = node.operand.argumentExpression; + if (ts.isSimpleInlineableExpression(operand.argumentExpression)) { + getterName = setterName = operand.argumentExpression; } else { getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, ts.visitNode(node.operand.argumentExpression, visitor, ts.isExpression)); + setterName = factory.createAssignment(getterName, ts.visitNode(operand.argumentExpression, visitor, ts.isExpression)); } } if (setterName && getterName) { var expression = factory.createReflectGetCall(superClassReference, getterName, classConstructor); - ts.setTextRange(expression, node.operand); + ts.setTextRange(expression, operand); var temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); expression = ts.expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp); expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor); @@ -94880,13 +95469,13 @@ var ts; facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } if (ts.isPropertyDeclaration(member) || ts.isClassStaticBlockDeclaration(member)) { - if (shouldTransformThisInStaticInitializers && member.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */) { + if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */) { facts |= 8 /* ClassFacts.NeedsSubstitutionForThisInClassStaticField */; if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } } - if (shouldTransformSuperInStaticInitializers && member.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */) { + if (shouldTransformSuperInStaticInitializers && member.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */) { if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */ | 4 /* ClassFacts.NeedsClassSuperReference */; } @@ -94924,8 +95513,7 @@ var ts; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* SyntaxKind.NullKeyword */); var statements = [ - factory.updateClassDeclaration(node, - /*decorators*/ undefined, node.modifiers, node.name, + factory.updateClassDeclaration(node, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; if (pendingClassReferenceAssignment) { @@ -94977,7 +95565,7 @@ var ts; temp = createClassTempVar(); getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); } - var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, + var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || ts.isPrivateIdentifier(p.name); }); if (hasTransformableStatics || ts.some(pendingExpressions)) { @@ -95045,9 +95633,7 @@ var ts; members.push(constructor); } if (!shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(pendingExpressions)) { - members.push(factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([ + members.push(factory.createClassStaticBlockDeclaration(factory.createBlock([ factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)) ]))); pendingExpressions = undefined; @@ -95084,7 +95670,6 @@ var ts; return undefined; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { @@ -95471,10 +96056,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_3 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_3, node); - ts.setCommentRange(clone_3, node); - return clone_3; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -95836,6 +96421,1001 @@ var ts; })(ts || (ts = {})); /*@internal*/ var ts; +(function (ts) { + function createRuntimeTypeSerializer(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var currentLexicalScope; + var currentNameScope; + return { + serializeTypeNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeNode, node); }, + serializeTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeOfNode, node); }, + serializeParameterTypesOfNode: function (serializerContext, node, container) { return setSerializerContextAnd(serializerContext, serializeParameterTypesOfNode, node, container); }, + serializeReturnTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeReturnTypeOfNode, node); }, + }; + function setSerializerContextAnd(serializerContext, cb, node, arg) { + var savedCurrentLexicalScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + currentLexicalScope = serializerContext.currentLexicalScope; + currentNameScope = serializerContext.currentNameScope; + var result = arg === undefined ? cb(node) : cb(node, arg); + currentLexicalScope = savedCurrentLexicalScope; + currentNameScope = savedCurrentNameScope; + return result; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 167 /* SyntaxKind.PropertyDeclaration */: + case 164 /* SyntaxKind.Parameter */: + return serializeTypeNode(node.type); + case 173 /* SyntaxKind.SetAccessor */: + case 172 /* SyntaxKind.GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 169 /* SyntaxKind.MethodDeclaration */: + return ts.factory.createIdentifier("Function"); + default: + return ts.factory.createVoidZero(); + } + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.factory.createArrayLiteralExpression(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.factory.createIdentifier("Promise"); + } + return ts.factory.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.factory.createIdentifier("Object"); + } + node = ts.skipTypeParentheses(node); + switch (node.kind) { + case 114 /* SyntaxKind.VoidKeyword */: + case 153 /* SyntaxKind.UndefinedKeyword */: + case 143 /* SyntaxKind.NeverKeyword */: + return ts.factory.createVoidZero(); + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + return ts.factory.createIdentifier("Function"); + case 183 /* SyntaxKind.ArrayType */: + case 184 /* SyntaxKind.TupleType */: + return ts.factory.createIdentifier("Array"); + case 177 /* SyntaxKind.TypePredicate */: + return node.assertsModifier ? + ts.factory.createVoidZero() : + ts.factory.createIdentifier("Boolean"); + case 133 /* SyntaxKind.BooleanKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 198 /* SyntaxKind.TemplateLiteralType */: + case 150 /* SyntaxKind.StringKeyword */: + return ts.factory.createIdentifier("String"); + case 148 /* SyntaxKind.ObjectKeyword */: + return ts.factory.createIdentifier("Object"); + case 196 /* SyntaxKind.LiteralType */: + return serializeLiteralOfLiteralTypeNode(node.literal); + case 147 /* SyntaxKind.NumberKeyword */: + return ts.factory.createIdentifier("Number"); + case 158 /* SyntaxKind.BigIntKeyword */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 151 /* SyntaxKind.SymbolKeyword */: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case 178 /* SyntaxKind.TypeReference */: + return serializeTypeReferenceNode(node); + case 188 /* SyntaxKind.IntersectionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ true); + case 187 /* SyntaxKind.UnionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ false); + case 189 /* SyntaxKind.ConditionalType */: + return serializeUnionOrIntersectionConstituents([node.trueType, node.falseType], /*isIntersection*/ false); + case 193 /* SyntaxKind.TypeOperator */: + if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { + return serializeTypeNode(node.type); + } + break; + case 181 /* SyntaxKind.TypeQuery */: + case 194 /* SyntaxKind.IndexedAccessType */: + case 195 /* SyntaxKind.MappedType */: + case 182 /* SyntaxKind.TypeLiteral */: + case 130 /* SyntaxKind.AnyKeyword */: + case 155 /* SyntaxKind.UnknownKeyword */: + case 192 /* SyntaxKind.ThisType */: + case 200 /* SyntaxKind.ImportType */: + break; + // handle JSDoc types from an invalid parse + case 312 /* SyntaxKind.JSDocAllType */: + case 313 /* SyntaxKind.JSDocUnknownType */: + case 317 /* SyntaxKind.JSDocFunctionType */: + case 318 /* SyntaxKind.JSDocVariadicType */: + case 319 /* SyntaxKind.JSDocNamepathType */: + break; + case 314 /* SyntaxKind.JSDocNullableType */: + case 315 /* SyntaxKind.JSDocNonNullableType */: + case 316 /* SyntaxKind.JSDocOptionalType */: + return serializeTypeNode(node.type); + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.factory.createIdentifier("Object"); + } + function serializeLiteralOfLiteralTypeNode(node) { + switch (node.kind) { + case 10 /* SyntaxKind.StringLiteral */: + case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: + return ts.factory.createIdentifier("String"); + case 219 /* SyntaxKind.PrefixUnaryExpression */: { + var operand = node.operand; + switch (operand.kind) { + case 8 /* SyntaxKind.NumericLiteral */: + case 9 /* SyntaxKind.BigIntLiteral */: + return serializeLiteralOfLiteralTypeNode(operand); + default: + return ts.Debug.failBadSyntaxKind(operand); + } + } + case 8 /* SyntaxKind.NumericLiteral */: + return ts.factory.createIdentifier("Number"); + case 9 /* SyntaxKind.BigIntLiteral */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 110 /* SyntaxKind.TrueKeyword */: + case 95 /* SyntaxKind.FalseKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 104 /* SyntaxKind.NullKeyword */: + return ts.factory.createVoidZero(); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function serializeUnionOrIntersectionConstituents(types, isIntersection) { + // Note when updating logic here also update `getEntityNameForDecoratorMetadata` in checker.ts so that aliases can be marked as referenced + var serializedType; + for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { + var typeNode = types_22[_i]; + typeNode = ts.skipTypeParentheses(typeNode); + if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { + if (isIntersection) + return ts.factory.createVoidZero(); // Reduce to `never` in an intersection + continue; // Elide `never` in a union + } + if (typeNode.kind === 155 /* SyntaxKind.UnknownKeyword */) { + if (!isIntersection) + return ts.factory.createIdentifier("Object"); // Reduce to `unknown` in a union + continue; // Elide `unknown` in an intersection + } + if (typeNode.kind === 130 /* SyntaxKind.AnyKeyword */) { + return ts.factory.createIdentifier("Object"); // Reduce to `any` in a union or intersection + } + if (!strictNullChecks && ((ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */) || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedConstituent = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedConstituent; + } + // If there exists union that is not `void 0` expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + if (serializedType) { + // Different types + if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) { + return ts.factory.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedType = serializedConstituent; + } + } + // If we were able to find common type, use it + return serializedType !== null && serializedType !== void 0 ? serializedType : (ts.factory.createVoidZero()); // Fallback is only hit if all union constituents are null/undefined/never + } + function equateSerializedTypeNodes(left, right) { + return ( + // temp vars used in fallback + ts.isGeneratedIdentifier(left) ? ts.isGeneratedIdentifier(right) : + // entity names + ts.isIdentifier(left) ? ts.isIdentifier(right) + && left.escapedText === right.escapedText : + ts.isPropertyAccessExpression(left) ? ts.isPropertyAccessExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) + && equateSerializedTypeNodes(left.name, right.name) : + // `void 0` + ts.isVoidExpression(left) ? ts.isVoidExpression(right) + && ts.isNumericLiteral(left.expression) && left.expression.text === "0" + && ts.isNumericLiteral(right.expression) && right.expression.text === "0" : + // `"undefined"` or `"function"` in `typeof` checks + ts.isStringLiteral(left) ? ts.isStringLiteral(right) + && left.text === right.text : + // used in `typeof` checks for fallback + ts.isTypeOfExpression(left) ? ts.isTypeOfExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // parens in `typeof` checks with temps + ts.isParenthesizedExpression(left) ? ts.isParenthesizedExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // conditionals used in fallback + ts.isConditionalExpression(left) ? ts.isConditionalExpression(right) + && equateSerializedTypeNodes(left.condition, right.condition) + && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) + && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : + // logical binary and assignments used in fallback + ts.isBinaryExpression(left) ? ts.isBinaryExpression(right) + && left.operatorToken.kind === right.operatorToken.kind + && equateSerializedTypeNodes(left.left, right.left) + && equateSerializedTypeNodes(left.right, right.right) : + false); + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with decorator type metadata. + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope !== null && currentNameScope !== void 0 ? currentNameScope : currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.factory.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createAssignment(temp, serialized), "function"), + /*questionToken*/ undefined, temp, + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.factory.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.factory.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.factory.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.factory.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.factory.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.factory.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.factory.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.factory.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + /** + * Produces an expression that results in `right` if `left` is not undefined at runtime: + * + * ``` + * typeof left !== "undefined" && right + * ``` + * + * We use `typeof L !== "undefined"` (rather than `L !== undefined`) since `L` may not be declared. + * It's acceptable for this expression to result in `false` at runtime, as the result is intended to be + * further checked by any containing expression. + */ + function createCheckedValue(left, right) { + return ts.factory.createLogicalAnd(ts.factory.createStrictInequality(ts.factory.createTypeOfExpression(left), ts.factory.createStringLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 79 /* SyntaxKind.Identifier */) { + // A -> typeof A !== "undefined" && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 79 /* SyntaxKind.Identifier */) { + // A.B -> typeof A !== "undefined" && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== "undefined" && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createLogicalAnd(ts.factory.createLogicalAnd(left.left, ts.factory.createStrictInequality(ts.factory.createAssignment(temp, left.right), ts.factory.createVoidZero())), ts.factory.createPropertyAccessExpression(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); + name.original = undefined; + ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. + return name; + case 161 /* SyntaxKind.QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * @param node The qualified name to serialize. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); + } + function getGlobalConstructorWithFallback(name) { + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createIdentifier(name), "function"), + /*questionToken*/ undefined, ts.factory.createIdentifier(name), + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + } + function getGlobalConstructor(name, minLanguageVersion) { + return languageVersion < minLanguageVersion ? + getGlobalConstructorWithFallback(name) : + ts.factory.createIdentifier(name); + } + } + ts.createRuntimeTypeSerializer = createRuntimeTypeSerializer; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformLegacyDecorators(context) { + var factory = context.factory, emitHelpers = context.getEmitHelperFactory, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + // Save the previous transformation hooks. + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onSubstituteNode = onSubstituteNode; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function modifierVisitor(node) { + return ts.isDecorator(node) ? undefined : node; + } + function visitor(node) { + if (!(node.transformFlags & 33554432 /* TransformFlags.ContainsDecorators */)) { + return node; + } + switch (node.kind) { + case 165 /* SyntaxKind.Decorator */: + // Decorators are elided. They will be emitted as part of `visitClassDeclaration`. + return undefined; + case 257 /* SyntaxKind.ClassDeclaration */: + return visitClassDeclaration(node); + case 226 /* SyntaxKind.ClassExpression */: + return visitClassExpression(node); + case 171 /* SyntaxKind.Constructor */: + return visitConstructorDeclaration(node); + case 169 /* SyntaxKind.MethodDeclaration */: + return visitMethodDeclaration(node); + case 173 /* SyntaxKind.SetAccessor */: + return visitSetAccessorDeclaration(node); + case 172 /* SyntaxKind.GetAccessor */: + return visitGetAccessorDeclaration(node); + case 167 /* SyntaxKind.PropertyDeclaration */: + return visitPropertyDeclaration(node); + case 164 /* SyntaxKind.Parameter */: + return visitParameterDeclaration(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitClassDeclaration(node) { + if (!(ts.classOrConstructorParameterIsDecorated(node) || ts.childIsDecorated(node))) + return ts.visitEachChild(node, visitor, context); + var statements = ts.hasDecorators(node) ? + transformClassDeclarationWithClassDecorators(node, node.name) : + transformClassDeclarationWithoutClassDecorators(node, node.name); + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(factory.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statements[0], ts.getEmitFlags(statements[0]) | 4194304 /* EmitFlags.HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + function decoratorContainsPrivateIdentifierInExpression(decorator) { + return !!(decorator.transformFlags & 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); + } + function parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators) { + return ts.some(parameterDecorators, decoratorContainsPrivateIdentifierInExpression); + } + function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.canHaveDecorators(member)) + continue; + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) + return true; + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) + return true; + } + return false; + } + function transformDecoratorsOfClassElements(node, members) { + var decorationStatements = []; + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ false); + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ true); + if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { + members = ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], members, true), [ + factory.createClassStaticBlockDeclaration(factory.createBlock(decorationStatements, /*multiLine*/ true)) + ], false)), members); + decorationStatements = undefined; + } + return { decorationStatements: decorationStatements, members: members }; + } + /** + * Transforms a non-decorated class declaration. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + */ + function transformClassDeclarationWithoutClassDecorators(node, name) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var _a; + var modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var updated = factory.updateClassDeclaration(node, modifiers, name, + /*typeParameters*/ undefined, heritageClauses, members); + return ts.addRange([updated], decorationStatements); + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function transformClassDeclarationWithClassDecorators(node, name) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var _a; + var location = ts.moveRangePastModifiers(node); + var classAlias = getClassAliasIfNeeded(node); + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var classExpression = factory.createClassExpression( + /*modifiers*/ undefined, name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(declName, + /*exclamationToken*/ undefined, + /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* NodeFlags.Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + var statements = [statement]; + ts.addRange(statements, decorationStatements); + addConstructorDecorationStatement(statements, node); + return statements; + } + function visitClassExpression(node) { + // Legacy decorators were not supported on class expressions + return factory.updateClassExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)); + } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)); + } + function finishClassElement(updated, original) { + if (updated !== original) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, original); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(original)); + } + return updated; + } + function visitMethodDeclaration(node) { + return finishClassElement(factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitGetAccessorDeclaration(node) { + return finishClassElement(factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitSetAccessorDeclaration(node) { + return finishClassElement(factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitPropertyDeclaration(node) { + if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */)) { + return undefined; + } + return finishClassElement(factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function visitParameterDeclaration(node) { + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* EmitFlags.NoTrailingSourceMap */); + } + return updated; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), function (expr) { return factory.createExpressionStatement(expr); })); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStaticElement, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStaticElement === ts.isStatic(member); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, function (m) { return isDecoratedClassElement(m, isStatic, node); }); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { + var member = members_8[_i]; + expressions = ts.append(expressions, generateClassElementDecorationExpression(node, member)); + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); + var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ + ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? factory.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : factory.createNull() + : undefined; + var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(helper, ts.moveRangePastModifiers(member)); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); + var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); + ts.setTextRange(helper, decorator.expression); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Gets an expression that represents a property name (for decorated properties or enums). + * For a computed property, a name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isPrivateIdentifier(name)) { + return factory.createIdentifier(""); + } + else if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression) + ? factory.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return factory.createStringLiteral(ts.idText(name)); + } + else { + return factory.cloneNode(name); + } + } + function enableSubstitutionForClassAliases() { + if (!classAliases) { + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(79 /* SyntaxKind.Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + /** + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. + */ + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; + } + } + function getClassPrototype(node) { + return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); + } + function getClassMemberPrefix(node, member) { + return ts.isStatic(member) + ? factory.getDeclarationName(node) + : getClassPrototype(node); + } + /** + * Hooks node substitutions. + * + * @param hint A hint as to the intended usage of the node. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* EmitHint.Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + return substituteExpressionIdentifier(node); + } + return node; + } + function substituteExpressionIdentifier(node) { + var _a; + return (_a = trySubstituteClassAlias(node)) !== null && _a !== void 0 ? _a : node; + } + function trySubstituteClassAlias(node) { + if (classAliases) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; + } + } + } + } + return undefined; + } + } + ts.transformLegacyDecorators = transformLegacyDecorators; +})(ts || (ts = {})); +/*@internal*/ +var ts; (function (ts) { var ES2017SubstitutionFlags; (function (ES2017SubstitutionFlags) { @@ -96054,8 +97634,7 @@ var ts; * @param node The node to visit. */ function visitMethodDeclaration(node) { - return factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ @@ -96071,8 +97650,7 @@ var ts; * @param node The node to visit. */ function visitFunctionDeclaration(node) { - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96087,7 +97665,7 @@ var ts; * @param node The node to visit. */ function visitFunctionExpression(node) { - return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96102,7 +97680,7 @@ var ts; * @param node The node to visit. */ function visitArrowFunction(node) { - return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96404,7 +97982,6 @@ var ts; /* typeParameters */ undefined, /* parameters */ [ factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "v", /* questionToken */ undefined, @@ -96684,7 +98261,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -96757,7 +98334,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* SyntaxKind.CommaToken */) { @@ -96788,7 +98365,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* FlattenLevel.ObjectRest */); @@ -96829,7 +98406,7 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } @@ -96848,7 +98425,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* HierarchyFacts.IterationStatementExcludes */, 2 /* HierarchyFacts.IterationStatementIncludes */); - if (node.initializer.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -96955,17 +98532,15 @@ var ts; function visitParameter(node) { if (parametersWithPrecedingObjectRestOrSpread === null || parametersWithPrecedingObjectRestOrSpread === void 0 ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); } - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); @@ -96979,7 +98554,7 @@ var ts; if (parameters) { parameters.add(parameter); } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { parameters = new ts.Set(); } } @@ -96990,8 +98565,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateConstructorDeclaration(node, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -97001,8 +98575,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), + var updated = factory.updateGetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -97013,8 +98586,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateSetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -97024,9 +98596,8 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ - ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + var updated = factory.updateMethodDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifierLike) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), @@ -97043,8 +98614,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + var updated = factory.updateFunctionDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined @@ -97202,7 +98772,7 @@ var ts; statements = ts.append(statements, statement); } } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { containsPrecedingObjectRestOrSpread = true; var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* FlattenLevel.ObjectRest */, factory.getGeneratedNameForNode(parameter), /*doNotRecordTempVariablesInLine*/ false, @@ -97699,7 +99269,7 @@ var ts; var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1]; if (ts.isExternalModule(node)) { // Add `import` statement - var importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); + var importStatement = factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); ts.setParentRecursive(importStatement, /*incremental*/ false); statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement); } @@ -97930,22 +99500,29 @@ var ts; if (node === undefined) { return factory.createTrue(); } - else if (node.kind === 10 /* SyntaxKind.StringLiteral */) { + if (node.kind === 10 /* SyntaxKind.StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 288 /* SyntaxKind.JsxExpression */) { + if (node.kind === 288 /* SyntaxKind.JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } return ts.visitNode(node.expression, visitor, ts.isExpression); } - else { - return ts.Debug.failBadSyntaxKind(node); + if (ts.isJsxElement(node)) { + return visitJsxElement(node, /*isChild*/ false); } + if (ts.isJsxSelfClosingElement(node)) { + return visitJsxSelfClosingElement(node, /*isChild*/ false); + } + if (ts.isJsxFragment(node)) { + return visitJsxFragment(node, /*isChild*/ false); + } + return ts.Debug.failBadSyntaxKind(node); } function visitJsxText(node) { var fixed = fixupWhitespaceAndDecodeEntities(node.text); @@ -98567,7 +100144,7 @@ var ts; && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -98940,7 +100517,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], + /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], /*type*/ undefined, transformClassBody(node, extendsClauseElement)); // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier @@ -99018,7 +100595,6 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), @@ -99131,7 +100707,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass || superCallExpression) { - if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */)) { + if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -99283,7 +100859,6 @@ var ts; // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, @@ -99295,7 +100870,6 @@ var ts; else if (node.initializer) { // Initializers are elided return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.name, /*questionToken*/ undefined, @@ -99676,7 +101250,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { + if (node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { hierarchyFacts |= 65536 /* HierarchyFacts.CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -99735,8 +101309,7 @@ var ts; : node.name; exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -99962,7 +101535,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */) { + if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */) { if (node.flags & 3 /* NodeFlags.BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -99975,7 +101548,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */ + if (node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -100299,7 +101872,7 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 524288 /* TransformFlags.ContainsYield */ && + if ((property.transformFlags & 1048576 /* TransformFlags.ContainsYield */ && hierarchyFacts & 4 /* HierarchyFacts.AsyncFunctionBody */) || (hasComputed = ts.Debug.checkDefined(property.name).kind === 162 /* SyntaxKind.ComputedPropertyName */)) { numInitialProperties = i; @@ -100572,7 +102145,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 0 /* EmitFlags.None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -100687,7 +102260,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 524288 /* EmitFlags.ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -100830,7 +102403,7 @@ var ts; } } else { - loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + loopParameters.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); var checkFlags = resolver.getNodeCheckFlags(decl); if (checkFlags & 4194304 /* NodeCheckFlags.NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { var outParamName = factory.createUniqueName("out_" + ts.idText(name)); @@ -100987,10 +102560,10 @@ var ts; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); if (node.kind === 172 /* SyntaxKind.GetAccessor */) { - updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + updated = factory.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); } else { - updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body); + updated = factory.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; @@ -101169,7 +102742,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */ || + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */ || node.expression.kind === 106 /* SyntaxKind.SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -101177,7 +102750,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* EmitFlags.NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -102019,10 +103592,10 @@ var ts; case 247 /* SyntaxKind.ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -102086,8 +103659,7 @@ var ts; function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. if (node.asteriskToken) { - node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, node.modifiers, + node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(node.modifiers, /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body)), @@ -102227,7 +103799,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -103285,7 +104857,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + return !!node && (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -103916,7 +105488,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], /*type*/ undefined, factory.createBlock(buildResult, /*multiLine*/ buildResult.length > 0)), 524288 /* EmitFlags.ReuseTempVariableScope */)); } @@ -104334,7 +105906,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */ || + node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -104435,8 +106007,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ], false))) @@ -104457,7 +106029,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], /*type*/ undefined, ts.setTextRange(factory.createBlock([ factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([ factory.createVariableStatement( @@ -104506,8 +106078,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ])) @@ -104536,7 +106108,7 @@ var ts; var amdDependency = _a[_i]; if (amdDependency.name) { aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); } else { unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); @@ -104557,7 +106129,7 @@ var ts; // This is so that when printer will not substitute the identifier ts.setEmitFlags(importAliasName, 4 /* EmitFlags.NoSubstitution */); aliasedModuleNames.push(externalModuleName); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); } else { unaliasedModuleNames.push(externalModuleName); @@ -104671,7 +106243,7 @@ var ts; function visitorWorker(node, valueIsDiscarded) { // This visitor does not need to descend into the tree if there is no dynamic import, destructuring assignment, or update expression // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & (4194304 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (8388608 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -104822,7 +106394,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), visitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -104877,8 +106449,8 @@ var ts; var resolve = factory.createUniqueName("resolve"); var reject = factory.createUniqueName("reject"); var parameters = [ - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) ]; var body = factory.createBlock([ factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), @@ -105166,8 +106738,7 @@ var ts; function visitFunctionDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor), /*type*/ undefined, ts.visitEachChild(node.body, visitor, context)), /*location*/ node), @@ -105194,8 +106765,7 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor), ts.visitNodes(node.members, visitor)), node), node)); } else { @@ -105809,7 +107379,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -105842,8 +107412,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) ], /*type*/ undefined, moduleBodyBlock); // Write the call to `System.register` @@ -105978,7 +107548,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 1048576 /* TransformFlags.ContainsAwait */ ? + var modifiers = node.transformFlags & 2097152 /* TransformFlags.ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* ModifierFlags.Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -106065,10 +107635,9 @@ var ts; /*typeArguments*/ undefined, [n]))); } return factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, exportStarFunction, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], /*type*/ undefined, factory.createBlock([ factory.createVariableStatement( /*modifiers*/ undefined, factory.createVariableDeclarationList([ @@ -106159,7 +107728,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true))); } return factory.createArrayLiteralExpression(setters, /*multiLine*/ true); @@ -106257,7 +107826,7 @@ var ts; */ function visitFunctionDeclaration(node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock))); } @@ -106285,8 +107854,7 @@ var ts; var name = factory.getLocalName(node); hoistVariableDeclaration(name); // Rewrite the class declaration into an assignment of a class expression. - statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, visitor, ts.isDecorator), - /*modifiers*/ undefined, node.name, + statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -106887,7 +108455,7 @@ var ts; * @param node The node to visit. */ function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 4194304 /* TransformFlags.ContainsDynamicImport */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 8388608 /* TransformFlags.ContainsDynamicImport */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -107334,7 +108902,7 @@ var ts; // Though an error in es2020 modules, in node-flavor es2020 modules, we can helpfully transform this to a synthetic `require` call // To give easy access to a synchronous `require` in node-flavor esm. We do the transform even in scenarios where we error, but `import.meta.url` // is available, just because the output is reasonable for a node-like runtime. - return ts.getEmitScriptTarget(compilerOptions) >= ts.ModuleKind.ES2020 ? visitImportEqualsDeclaration(node) : undefined; + return ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.Node16 ? visitImportEqualsDeclaration(node) : undefined; case 271 /* SyntaxKind.ExportAssignment */: return visitExportAssignment(node); case 272 /* SyntaxKind.ExportDeclaration */: @@ -107357,7 +108925,6 @@ var ts; if (!importRequireStatements) { var createRequireName = factory.createUniqueName("_createRequire", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */); var importStatement = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamedImports([ @@ -107400,7 +108967,6 @@ var ts; function appendExportsOfImportEqualsDeclaration(statements, node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { statements = ts.append(statements, factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, ts.idText(node.name))]))); } return statements; @@ -107421,13 +108987,11 @@ var ts; var oldIdentifier = node.exportClause.name; var synthName = factory.getGeneratedNameForNode(oldIdentifier); var importDecl = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier, node.assertClause); ts.setOriginalNode(importDecl, node.exportClause); var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, synthName, oldIdentifier)])); ts.setOriginalNode(exportDecl, node); @@ -107679,7 +109243,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.SyntaxKind[node.kind])); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(node.kind))); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 254 /* SyntaxKind.VariableDeclaration */ || node.kind === 203 /* SyntaxKind.BindingElement */) { @@ -107890,7 +109454,7 @@ var ts; ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1; default: - return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.SyntaxKind[node.parent.kind])); + return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind))); } } function getTypeParameterConstraintVisibilityError() { @@ -108055,7 +109619,8 @@ var ts; trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, reportNonlocalAugmentation: reportNonlocalAugmentation, - reportNonSerializableProperty: reportNonSerializableProperty + reportNonSerializableProperty: reportNonSerializableProperty, + reportImportTypeNodeResolutionModeOverride: reportImportTypeNodeResolutionModeOverride, }; var errorNameNode; var errorFallbackNode; @@ -108182,6 +109747,11 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName)); } } + function reportImportTypeNodeResolutionModeOverride() { + if (!ts.isNightly() && (errorNameNode || errorFallbackNode)) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ @@ -108221,7 +109791,7 @@ var ts; resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -108364,7 +109934,7 @@ var ts; }); return ret; } - function filterBindingPatternInitializers(name) { + function filterBindingPatternInitializersAndRenamings(name) { if (name.kind === 79 /* SyntaxKind.Identifier */) { return name; } @@ -108380,7 +109950,12 @@ var ts; if (elem.kind === 227 /* SyntaxKind.OmittedExpression */) { return elem; } - return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + if (elem.propertyName && ts.isIdentifier(elem.propertyName) && ts.isIdentifier(elem.name) && !elem.symbol.isReferenced) { + // Unnecessary property renaming is forbidden in types, so remove renaming + return factory.updateBindingElement(elem, elem.dotDotDotToken, + /* propertyName */ undefined, elem.propertyName, shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializersAndRenamings(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); } } function ensureParameter(p, modifierMask, type) { @@ -108389,8 +109964,7 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } - var newParam = factory.updateParameterDeclaration(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + var newParam = factory.updateParameterDeclaration(p, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -108441,7 +110015,7 @@ var ts; if (node.kind === 164 /* SyntaxKind.Parameter */ || node.kind === 167 /* SyntaxKind.PropertyDeclaration */ || node.kind === 166 /* SyntaxKind.PropertySignature */) { - if (!node.initializer) + if (ts.isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } @@ -108527,7 +110101,6 @@ var ts; } if (!newValueParameter) { newValueParameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "value"); } @@ -108585,8 +110158,7 @@ var ts; if (decl.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); - return factory.updateImportEqualsDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + return factory.updateImportEqualsDeclaration(decl, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } else { var oldDiag = getSymbolAccessibilityDiagnostic; @@ -108599,31 +110171,28 @@ var ts; function transformImportDeclaration(decl) { if (!decl.importClause) { // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // The `importClause` visibility corresponds to the default's visibility. var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; if (!decl.importClause.namedBindings) { // No named bindings (either namespace or list), meaning the import is just default or should be elided - return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, + return visibleDefaultBinding && factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } if (decl.importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; - return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; + return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; } // Named imports (optionally with visible default) var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); if ((bindingList && bindingList.length) || visibleDefaultBinding) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Augmentation of export depends on import if (resolver.isImportRequiredByAugmentation(decl)) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, + return factory.updateImportDeclaration(decl, decl.modifiers, /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Nothing visible @@ -108632,7 +110201,7 @@ var ts; var mode = ts.getResolutionModeOverrideForClause(assertClause); if (mode !== undefined) { if (!ts.isNightly()) { - context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); } return assertClause; } @@ -108656,7 +110225,7 @@ var ts; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.Debug.formatSyntaxKind(i.kind))); } var priorNeedsDeclare = needsDeclare; needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); @@ -108720,7 +110289,7 @@ var ts; if (ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)) { if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; // Elide all but the first overload - return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + return cleanup(factory.createPropertyDeclaration(ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); } } if (canProduceDiagnostic && !suppressNewDiagnosticContexts) { @@ -108752,7 +110321,6 @@ var ts; case 171 /* SyntaxKind.Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* ModifierFlags.None */), /*body*/ undefined); return cleanup(ctor); @@ -108761,8 +110329,7 @@ var ts; if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - var sig = factory.createMethodDeclaration( - /*decorators*/ undefined, ensureModifiers(input), + var sig = factory.createMethodDeclaration(ensureModifiers(input), /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined); return cleanup(sig); @@ -108772,24 +110339,21 @@ var ts; return cleanup(/*returnValue*/ undefined); } var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); - return cleanup(factory.updateGetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), + return cleanup(factory.updateGetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), /*body*/ undefined)); } case 173 /* SyntaxKind.SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updateSetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), + return cleanup(factory.updateSetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), /*body*/ undefined)); } case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updatePropertyDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); + return cleanup(factory.updatePropertyDeclaration(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); case 166 /* SyntaxKind.PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); @@ -108805,8 +110369,7 @@ var ts; return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } case 176 /* SyntaxKind.IndexSignature */: { - return cleanup(factory.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); + return cleanup(factory.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); } case 254 /* SyntaxKind.VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { @@ -108845,7 +110408,7 @@ var ts; return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.assertions, input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); } - default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.SyntaxKind[input.kind])); + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(input.kind))); } } if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) { @@ -108889,8 +110452,7 @@ var ts; resultHasScopeMarker = true; // Always visible if the parent node isn't dropped for being not visible // Rewrite external module names if necessary - return factory.updateExportDeclaration(input, - /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); + return factory.updateExportDeclaration(input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); } case 271 /* SyntaxKind.ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible @@ -108913,7 +110475,7 @@ var ts; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* NodeFlags.Const */)); preserveJsDoc(statement, input); ts.removeAllComments(input); - return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + return [statement, factory.updateExportAssignment(input, input.modifiers, newId)]; } } } @@ -108928,7 +110490,7 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (125951 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (257023 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { @@ -108964,22 +110526,19 @@ var ts; var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 259 /* SyntaxKind.TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all - return cleanup(factory.updateTypeAliasDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + return cleanup(factory.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 258 /* SyntaxKind.InterfaceDeclaration */: { - return cleanup(factory.updateInterfaceDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + return cleanup(factory.updateInterfaceDeclaration(input, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 256 /* SyntaxKind.FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - var clean = cleanup(factory.updateFunctionDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), + var clean = cleanup(factory.updateFunctionDeclaration(input, ensureModifiers(input), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); if (clean && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { var props = resolver.getPropertiesOfContainerFunction(input); // Use parseNodeFactory so it is usable as an enclosing declaration - var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace_1, enclosingDeclaration); fakespace_1.locals = ts.createSymbolTable(props); fakespace_1.symbol = props[0].parent; @@ -109005,26 +110564,22 @@ var ts; } else { declarations.push(factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) { var gen = _a[0], exp = _a[1]; return factory.createExportSpecifier(/*isTypeOnly*/ false, gen, exp); })))); } - var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); + var namespaceDecl = factory.createModuleDeclaration(ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); if (!ts.hasEffectiveModifier(clean, 512 /* ModifierFlags.Default */)) { return [clean, namespaceDecl]; } var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ModifierFlags.ExportDefault */) | 2 /* ModifierFlags.Ambient */); - var cleanDeclaration = factory.updateFunctionDeclaration(clean, - /*decorators*/ undefined, modifiers, + var cleanDeclaration = factory.updateFunctionDeclaration(clean, modifiers, /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, /*body*/ undefined); - var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, - /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body); + var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, modifiers, namespaceDecl.name, namespaceDecl.body); var exportDefaultDeclaration = factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, namespaceDecl.name); if (ts.isSourceFile(input.parent)) { @@ -109067,8 +110622,7 @@ var ts; needsScopeFixMarker = oldNeedsScopeFix; resultHasScopeMarker = oldHasScopeFix; var mods = ensureModifiers(input); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; @@ -109079,8 +110633,7 @@ var ts; var id = ts.getOriginalNodeId(inner); // TODO: GH#18217 var body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, input.name, body)); } } case 257 /* SyntaxKind.ClassDeclaration */: { @@ -109097,8 +110650,7 @@ var ts; return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 79 /* SyntaxKind.Identifier */) { - return preserveJsDoc(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + return preserveJsDoc(factory.createPropertyDeclaration(ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } else { // Pattern - this is currently an error, but we emit declarations for it somewhat correctly @@ -109114,8 +110666,7 @@ var ts; elems = ts.concatenate(elems, walkBindingPattern(elem.name)); } elems = elems || []; - elems.push(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), elem.name, + elems.push(factory.createPropertyDeclaration(ensureModifiers(param), elem.name, /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), /*initializer*/ undefined)); } @@ -109129,7 +110680,6 @@ var ts; // Prevents other classes with the same public members from being used in place of the current class var privateIdentifier = hasPrivateIdentifier ? [ factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"), /*questionToken*/ undefined, /*type*/ undefined, @@ -109159,20 +110709,18 @@ var ts; } return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 104 /* SyntaxKind.NullKeyword */; })), visitDeclarationSubtree)); })); - return [statement, cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + return [statement, cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 } else { var heritageClauses = transformHeritageClauses(input.heritageClauses); - return cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + return cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members)); } } case 237 /* SyntaxKind.VariableStatement */: { return cleanup(transformVariableStatement(input)); } case 260 /* SyntaxKind.EnumDeclaration */: { - return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(factory.updateEnumDeclaration(input, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; // Rewrite enum values to their constants, if available @@ -109182,7 +110730,7 @@ var ts; } } // Anything left unhandled is an error, so this should be unreachable - return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.SyntaxKind[input.kind])); + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.Debug.formatSyntaxKind(input.kind))); function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; @@ -109256,12 +110804,12 @@ var ts; var currentFlags = ts.getEffectiveModifierFlags(node); var newFlags = ensureModifierFlags(node); if (currentFlags === newFlags) { - return node.modifiers; + return ts.visitArray(node.modifiers, function (n) { return ts.tryCast(n, ts.isModifier); }, ts.isModifier); } return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 125951 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files + var mask = 257023 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* ModifierFlags.Ambient */ : 0 /* ModifierFlags.None */; var parentIsFile = node.parent.kind === 305 /* SyntaxKind.SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { @@ -109302,7 +110850,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 125951 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } + if (modifierMask === void 0) { modifierMask = 257023 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* ModifierFlags.None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* ModifierFlags.Default */ && !(flags & 1 /* ModifierFlags.Export */)) { @@ -109424,6 +110972,7 @@ var ts; var transformers = []; ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory)); transformers.push(ts.transformTypeScript); + transformers.push(ts.transformLegacyDecorators); transformers.push(ts.transformClassFields); if (ts.getJSXTransformEnabled(compilerOptions)) { transformers.push(ts.transformJsx); @@ -110184,7 +111733,6 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; - var exportedModulesFromDeclarationEmit; // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); @@ -110194,7 +111742,6 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, - exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath; @@ -110248,14 +111795,16 @@ var ts; return; } var version = ts.version; // Extracted into a const so the form is stable between namespace and module - ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false); + var buildInfo = { bundle: bundle, program: program, version: version }; + // Pass buildinfo as additional data to avoid having to reparse + ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText(buildInfo), /*writeByteOrderMark*/ false, /*sourceFiles*/ undefined, { buildInfo: buildInfo }); } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) { if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) { return; } // Make sure not to write js file and source map file if any of them cannot be written - if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit) { emitSkipped = true; return; } @@ -110284,7 +111833,7 @@ var ts; substituteNode: transform.substituteNode, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); if (bundleBuildInfo) @@ -110320,7 +111869,7 @@ var ts; noEmitHelpers: true, module: compilerOptions.module, target: compilerOptions.target, - sourceMap: compilerOptions.sourceMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, inlineSourceMap: compilerOptions.inlineSourceMap, extendedDiagnostics: compilerOptions.extendedDiagnostics, onlyPrintJsDocStyle: true, @@ -110340,17 +111889,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: !forceDtsEmit && compilerOptions.declarationMap, + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform, declarationPrinter, { + sourceMap: printerOptions.sourceMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 305 /* SyntaxKind.SourceFile */) { - var sourceFile = declarationTransform.transformed[0]; - exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; - } } declarationTransform.dispose(); if (bundleBuildInfo) @@ -110369,7 +111914,8 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, mapOptions) { + var sourceFileOrBundle = transform.transformed[0]; var bundle = sourceFileOrBundle.kind === 306 /* SyntaxKind.Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 305 /* SyntaxKind.SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; @@ -110402,13 +111948,20 @@ var ts; if (sourceMapFilePath) { var sourceMap = sourceMapGenerator.toString(); ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + if (printer.bundleFileInfo) + printer.bundleFileInfo.mapHash = ts.computeSignature(sourceMap, ts.maybeBind(host, host.createHash)); } } else { writer.writeLine(); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos }); + var text = writer.getText(); + ts.writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos, diagnostics: transform.diagnostics }); + // We store the hash of the text written in the buildinfo to ensure that text of the referenced d.ts file is same as whats in the buildinfo + // This is needed because incremental can be toggled between two runs and we might use stale file text to do text manipulation in prepend mode + if (printer.bundleFileInfo) + printer.bundleFileInfo.hash = ts.computeSignature(text, ts.maybeBind(host, host.createHash)); // Reset state writer.clear(); } @@ -110551,34 +112104,56 @@ var ts; } /*@internal*/ function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) { + var createHash = ts.maybeBind(host, host.createHash); var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath)); - if (!buildInfoText) + var buildInfo; + if (host.getBuildInfo) { + // If host directly provides buildinfo we can get it directly. This allows host to cache the buildinfo + var hostBuildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); + if (!hostBuildInfo) + return buildInfoPath; + buildInfo = hostBuildInfo; + } + else { + var buildInfoText = host.readFile(buildInfoPath); + if (!buildInfoText) + return buildInfoPath; + buildInfo = getBuildInfo(buildInfoText); + } + if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationFilePath && !buildInfo.bundle.dts)) return buildInfoPath; var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath)); if (!jsFileText) return jsFilePath; + // If the jsFileText is not same has what it was created with, tsbuildinfo is stale so dont use it + if (ts.computeSignature(jsFileText, createHash) !== buildInfo.bundle.js.hash) + return jsFilePath; var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); // error if no source map or for now if inline sourcemap if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap) return sourceMapFilePath || "inline sourcemap decoding"; + if (sourceMapFilePath && ts.computeSignature(sourceMapText, createHash) !== buildInfo.bundle.js.mapHash) + return sourceMapFilePath; // read declaration text var declarationText = declarationFilePath && host.readFile(declarationFilePath); if (declarationFilePath && !declarationText) return declarationFilePath; + if (declarationFilePath && ts.computeSignature(declarationText, createHash) !== buildInfo.bundle.dts.hash) + return declarationFilePath; var declarationMapText = declarationMapPath && host.readFile(declarationMapPath); // error if no source map or for now if inline sourcemap if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding"; - var buildInfo = getBuildInfo(buildInfoText); - if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts)) - return buildInfoPath; + if (declarationMapPath && ts.computeSignature(declarationMapText, createHash) !== buildInfo.bundle.dts.mapHash) + return declarationMapPath; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, /*onlyOwnText*/ true); var outputFiles = []; var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); }); var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host); + var changedDtsText; + var changedDtsData; var emitHost = { getPrependNodes: ts.memoize(function () { return __spreadArray(__spreadArray([], prependNodes, true), [ownPrependInput], false); }), getCanonicalFileName: host.getCanonicalFileName, @@ -110594,7 +112169,7 @@ var ts; getResolvedProjectReferenceToRedirect: ts.returnUndefined, getProjectReferenceRedirect: ts.returnUndefined, isSourceOfProjectReferenceRedirect: ts.returnFalse, - writeFile: function (name, text, writeByteOrderMark) { + writeFile: function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { switch (name) { case jsFilePath: if (jsFileText === text) @@ -110605,8 +112180,12 @@ var ts; return; break; case buildInfoPath: - var newBuildInfo = getBuildInfo(text); + var newBuildInfo = data.buildInfo; newBuildInfo.program = buildInfo.program; + if (newBuildInfo.program && changedDtsText !== undefined && config.options.composite) { + // Update the output signature + newBuildInfo.program.outSignature = ts.computeSignature(changedDtsText, createHash, changedDtsData); + } // Update sourceFileInfo var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles; newBuildInfo.bundle.js.sources = js.sources; @@ -110614,11 +112193,13 @@ var ts; newBuildInfo.bundle.dts.sources = dts.sources; } newBuildInfo.bundle.sourceFiles = sourceFiles; - outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark }); + outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark, buildInfo: newBuildInfo }); return; case declarationFilePath: if (declarationText === text) return; + changedDtsText = text; + changedDtsData = data; break; case declarationMapPath: if (declarationMapText === text) @@ -110637,6 +112218,7 @@ var ts; getSourceFileFromReference: ts.returnUndefined, redirectTargetsMap: ts.createMultiMap(), getFileIncludeReasons: ts.notImplemented, + createHash: createHash, }; emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers)); @@ -111724,8 +113306,7 @@ var ts; } } function emitParameter(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); @@ -111736,7 +113317,7 @@ var ts; emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); @@ -111746,7 +113327,6 @@ var ts; // Type members // function emitPropertySignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); @@ -111754,8 +113334,7 @@ var ts; writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); emit(node.exclamationToken); @@ -111765,7 +113344,6 @@ var ts; } function emitMethodSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); @@ -111776,16 +113354,13 @@ var ts; popNameGenerationScope(node); } function emitMethodDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.asteriskToken); emit(node.name); emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitClassStaticBlockDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("static"); emitBlockFunctionBody(node.body); } @@ -111795,8 +113370,7 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword(node.kind === 172 /* SyntaxKind.GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); @@ -111804,8 +113378,6 @@ var ts; } function emitCallSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); @@ -111814,8 +113386,6 @@ var ts; } function emitConstructSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -111825,7 +113395,6 @@ var ts; popNameGenerationScope(node); } function emitIndexSignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); @@ -112218,7 +113787,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitSignatureAndBody(node, emitArrowFunctionHead); } @@ -112699,7 +114267,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitFunctionDeclarationOrExpression(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); emit(node.asteriskToken); @@ -112757,8 +114324,8 @@ var ts; if (!ts.nodeIsSynthesized(body) && currentSourceFile && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { return false; } - if (getLeadingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */) - || getClosingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */)) { + if (getLeadingLineTerminatorCount(body, ts.firstOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */) + || getClosingLineTerminatorCount(body, ts.lastOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */, body.statements)) { return false; } var previousStatement; @@ -112806,8 +114373,7 @@ var ts; } function emitClassDeclarationOrExpression(node) { ts.forEach(node.members, generateMemberNames); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword("class"); if (node.name) { writeSpace(); @@ -112828,7 +114394,6 @@ var ts; } } function emitInterfaceDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("interface"); writeSpace(); @@ -112841,7 +114406,6 @@ var ts; writePunctuation("}"); } function emitTypeAliasDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("type"); writeSpace(); @@ -113468,8 +115032,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* BundleFileSectionKind.Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_24 = types; _d < types_24.length; _d++) { - var directive = types_24[_d]; + for (var _d = 0, types_23 = types; _d < types_23.length; _d++) { + var directive = types_23[_d]; var pos = writer.getTextPos(); var resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.impliedNodeFormat) ? "resolution-mode=\"".concat(directive.resolutionMode === ts.ModuleKind.ESNext ? "import" : "require", "\"") @@ -113643,12 +115207,52 @@ var ts; emit(node); write = savedWrite; } - function emitModifiers(node, modifiers) { - if (modifiers && modifiers.length) { - emitList(node, modifiers, 262656 /* ListFormat.Modifiers */); - writeSpace(); + function emitDecoratorsAndModifiers(node, modifiers) { + if (modifiers === null || modifiers === void 0 ? void 0 : modifiers.length) { + if (ts.every(modifiers, ts.isModifier)) { + // if all modifier-likes are `Modifier`, simply emit the array as modifiers. + return emitModifiers(node, modifiers); + } + if (ts.every(modifiers, ts.isDecorator)) { + // if all modifier-likes are `Decorator`, simply emit the array as decorators. + return emitDecorators(node, modifiers); + } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(modifiers); + // partition modifiers into contiguous chunks of `Modifier` or `Decorator` + var lastMode = void 0; + var mode = void 0; + var start = 0; + var pos = 0; + while (start < modifiers.length) { + while (pos < modifiers.length) { + var modifier = modifiers[pos]; + mode = ts.isDecorator(modifier) ? "decorators" : "modifiers"; + if (lastMode === undefined) { + lastMode = mode; + } + else if (mode !== lastMode) { + break; + } + pos++; + } + var textRange = { pos: -1, end: -1 }; + if (start === 0) + textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) + textRange.end = modifiers.end; + emitNodeListItems(emit, node, modifiers, lastMode === "modifiers" ? 2359808 /* ListFormat.Modifiers */ : 2146305 /* ListFormat.Decorators */, + /*parenthesizerRule*/ undefined, start, pos - start, + /*hasTrailingComma*/ false, textRange); + start = pos; + lastMode = mode; + pos++; + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(modifiers); } } + function emitModifiers(node, modifiers) { + emitList(node, modifiers, 2359808 /* ListFormat.Modifiers */); + } function emitTypeAnnotation(node) { if (node) { writePunctuation(":"); @@ -113726,11 +115330,9 @@ var ts; && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head && !parentNode.type // arrow function may not have return type annotation - && !ts.some(parentNode.decorators) // parent may not have decorators - && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.modifiers) // parent may not have decorators or modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters - && !ts.some(parameter.decorators) // parameter may not have decorators - && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !ts.some(parameter.modifiers) // parameter may not have decorators or modifiers && !parameter.dotDotDotToken // parameter may not be rest && !parameter.questionToken // parameter may not be optional && !parameter.type // parameter may not have a type annotation @@ -113785,12 +115387,8 @@ var ts; } var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 32768 /* ListFormat.OptionalIfEmpty */) { - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); return; } if (format & 15360 /* ListFormat.BracketsMask */) { @@ -113799,9 +115397,7 @@ var ts; emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); if (isEmpty) { // Write a line terminator if the parent node was multi-line if (format & 1 /* ListFormat.MultiLine */ && !(preserveSourceNewlines && (!parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { @@ -113812,123 +115408,128 @@ var ts; } } else { - ts.Debug.type(children); - // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; - var shouldEmitInterveningComments = mayEmitInterveningComments; - var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217 - if (leadingLineTerminatorCount) { - writeLine(leadingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { - writeSpace(); - } - // Increase the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { - increaseIndent(); + emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, children.hasTrailingComma, children); + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); + if (format & 15360 /* ListFormat.BracketsMask */) { + if (isEmpty && children) { + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } - var emitListItem = getEmitListItem(emit, parenthesizerRule); - // Emit each child. - var previousSibling = void 0; - var previousSourceFileTextKind = void 0; - var shouldDecreaseIndentAfterEmit = false; - for (var i = 0; i < count; i++) { - var child = children[start + i]; - // Write the delimiter if this is not the first node. - if (format & 32 /* ListFormat.AsteriskDelimited */) { - // always write JSDoc in the format "\n *" - writeLine(); - writeDelimiter(format); - } - else if (previousSibling) { - // i.e - // function commentedParameters( - // /* Parameter a */ - // a - // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline - // , - if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { - emitLeadingCommentsOfPosition(previousSibling.end); - } - writeDelimiter(format); - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write either a line terminator or whitespace to separate the elements. - var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); - if (separatingLineTerminatorCount > 0) { - // If a synthesized node in a single-line list starts on a new - // line, we should increase the indent. - if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { - increaseIndent(); - shouldDecreaseIndentAfterEmit = true; - } - writeLine(separatingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { - writeSpace(); - } - } - // Emit this child. - previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); - if (shouldEmitInterveningComments) { - var commentRange = ts.getCommentRange(child); - emitTrailingCommentsOfPosition(commentRange.pos); - } - else { - shouldEmitInterveningComments = mayEmitInterveningComments; - } - nextListElementPos = child.pos; - emitListItem(child, emit, parenthesizerRule, i); - if (shouldDecreaseIndentAfterEmit) { - decreaseIndent(); - shouldDecreaseIndentAfterEmit = false; + writePunctuation(getClosingBracket(format)); + } + } + /** + * Emits a list without brackets or raising events. + * + * NOTE: You probably don't want to call this directly and should be using `emitList` or `emitExpressionList` instead. + */ + function emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, hasTrailingComma, childrenTextRange) { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children[start], format); + if (leadingLineTerminatorCount) { + writeLine(leadingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + increaseIndent(); + } + var emitListItem = getEmitListItem(emit, parenthesizerRule); + // Emit each child. + var previousSibling; + var previousSourceFileTextKind; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* ListFormat.AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write either a line terminator or whitespace to separate the elements. + var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); + if (separatingLineTerminatorCount > 0) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(separatingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { + writeSpace(); } - previousSibling = child; } - // Write a trailing comma, if requested. - var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; - var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); - var hasTrailingComma = (children === null || children === void 0 ? void 0 : children.hasTrailingComma) && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); - if (hasTrailingComma) { - if (previousSibling && !skipTrailingComments) { - emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); - } - else { - writePunctuation(","); - } + // Emit this child. + previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); + if (shouldEmitInterveningComments) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); } - // Emit any trailing comment of the last element in the list - // i.e - // var array = [... - // 2 - // /* end of element 2 */ - // ]; - if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { - emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); - } - // Decrease the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + nextListElementPos = child.pos; + emitListItem(child, emit, parenthesizerRule, i); + if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; } - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write the closing line terminator or closing whitespace. - var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format); - if (closingLineTerminatorCount) { - writeLine(closingLineTerminatorCount); + previousSibling = child; + } + // Write a trailing comma, if requested. + var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; + var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); + var emitTrailingComma = hasTrailingComma && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); + if (emitTrailingComma) { + if (previousSibling && !skipTrailingComments) { + emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); } - else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { - writeSpace(); + else { + writePunctuation(","); } } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { + emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange === null || childrenTextRange === void 0 ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end); } - if (format & 15360 /* ListFormat.BracketsMask */) { - if (isEmpty && children) { - emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists - } - writePunctuation(getClosingBracket(format)); + // Decrease the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + decreaseIndent(); + } + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write the closing line terminator or closing whitespace. + var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children[start + count - 1], format, childrenTextRange); + if (closingLineTerminatorCount) { + writeLine(closingLineTerminatorCount); + } + else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { + writeSpace(); } } // Writers @@ -114058,16 +115659,15 @@ var ts; decreaseIndent(); } } - function getLeadingLineTerminatorCount(parentNode, children, format) { + function getLeadingLineTerminatorCount(parentNode, firstChild, format) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var firstChild_1 = children[0]; - if (firstChild_1 === undefined) { + if (firstChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (firstChild_1.pos === nextListElementPos) { + if (firstChild.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading // line terminators have already been written as the separating line terminators of the // parent list. Example: @@ -114085,20 +115685,20 @@ var ts; // leading newline to start the modifiers. return 0; } - if (firstChild_1.kind === 11 /* SyntaxKind.JsxText */) { + if (firstChild.kind === 11 /* SyntaxKind.JsxText */) { // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && - !ts.nodeIsSynthesized(firstChild_1) && - (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { + !ts.nodeIsSynthesized(firstChild) && + (!firstChild.parent || ts.getOriginalNode(firstChild.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild.pos, parentNode.pos, currentSourceFile, includeComments); }); } - return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; + return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; } - if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) { + if (synthesizedNodeStartsOnNewLine(firstChild, format)) { return 1; } } @@ -114138,18 +115738,17 @@ var ts; } return format & 1 /* ListFormat.MultiLine */ ? 1 : 0; } - function getClosingLineTerminatorCount(parentNode, children, format) { + function getClosingLineTerminatorCount(parentNode, lastChild, format, childrenTextRange) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { - var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; + var end_1 = childrenTextRange && !ts.positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; @@ -114187,14 +115786,14 @@ var ts; return lines; } function writeLineSeparatorsAndIndentBefore(node, parent) { - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, node, 0 /* ListFormat.None */); if (leadingNewlines) { writeLinesAndIndent(leadingNewlines, /*writeSpaceIfNotIndenting*/ false); } return !!leadingNewlines; } function writeLineSeparatorsAfter(node, parent) { - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, node, 0 /* ListFormat.None */, /*childrenTextRange*/ undefined); if (trailingNewlines) { writeLine(trailingNewlines); } @@ -115721,12 +117320,10 @@ var ts; } ts.createCompilerHost = createCompilerHost; /*@internal*/ - // TODO(shkamat): update this after reworking ts build API function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = new ts.Map(); var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); - var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash; function getSourceFile(fileName, languageVersionOrOptions, onError) { var text; try { @@ -115759,7 +117356,7 @@ var ts; // NOTE: If patchWriteFileEnsuringDirectory has been called, // the system.writeFile will do its own directory creation and // the ensureDirectoriesExist call will always be redundant. - ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -115769,35 +117366,6 @@ var ts; } } } - var outputFingerprints; - function writeFileWorker(fileName, data, writeByteOrderMark) { - if (!ts.isWatchSet(options) || !system.getModifiedTime) { - system.writeFile(fileName, data, writeByteOrderMark); - return; - } - if (!outputFingerprints) { - outputFingerprints = new ts.Map(); - } - var hash = computeHash(data); - var mtimeBefore = system.getModifiedTime(fileName); - if (mtimeBefore) { - var fingerprint = outputFingerprints.get(fileName); - // If output has not been changed, and the file has no external modification - if (fingerprint && - fingerprint.byteOrderMark === writeByteOrderMark && - fingerprint.hash === hash && - fingerprint.mtime.getTime() === mtimeBefore.getTime()) { - return; - } - } - system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; - outputFingerprints.set(fileName, { - hash: hash, - byteOrderMark: writeByteOrderMark, - mtime: mtimeAfter - }); - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -115904,7 +117472,7 @@ var ts; }; } // directoryExists - if (originalDirectoryExists && originalCreateDirectory) { + if (originalDirectoryExists) { host.directoryExists = function (directory) { var key = toPath(directory); var value = directoryExistsCache.get(key); @@ -115914,11 +117482,13 @@ var ts; directoryExistsCache.set(key, !!newValue); return newValue; }; - host.createDirectory = function (directory) { - var key = toPath(directory); - directoryExistsCache.delete(key); - originalCreateDirectory.call(host, directory); - }; + if (originalCreateDirectory) { + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } } return { originalReadFile: originalReadFile, @@ -116139,12 +117709,14 @@ var ts; } ts.loadWithTypeDirectiveCache = loadWithTypeDirectiveCache; ; - /* @internal */ + /** + * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly + * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. + */ function getModeForFileReference(ref, containingFileMode) { return (ts.isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode; } ts.getModeForFileReference = getModeForFileReference; - /* @internal */ function getModeForResolutionAtIndex(file, index) { if (file.impliedNodeFormat === undefined) return undefined; @@ -116165,7 +117737,15 @@ var ts; return false; } ts.isExclusivelyTypeOnlyImportOrExport = isExclusivelyTypeOnlyImportOrExport; - /* @internal */ + /** + * Calculates the final resolution mode for a given module reference node. This is generally the explicitly provided resolution mode, if + * one exists, or the mode of the containing source file. (Excepting import=require, which is always commonjs, and dynamic import, which is always esm). + * Notably, this function always returns `undefined` if the containing file has an `undefined` `impliedNodeFormat` - this field is only set when + * `moduleResolution` is `node16`+. + * @param file The file the import or import-like reference is contained within + * @param usage The module reference string + * @returns The final resolution mode of the import + */ function getModeForUsageLocation(file, usage) { var _a, _b; if (file.impliedNodeFormat === undefined) @@ -116411,6 +117991,12 @@ var ts; * @returns `undefined` if the path has no relevant implied format, `ModuleKind.ESNext` for esm format, and `ModuleKind.CommonJS` for cjs format */ function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, options) { + var result = getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options); + return typeof result === "object" ? result.impliedNodeFormat : result; + } + ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + /*@internal*/ + function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) { switch (ts.getEmitModuleResolutionKind(options)) { case ts.ModuleResolutionKind.Node16: case ts.ModuleResolutionKind.NodeNext: @@ -116422,11 +118008,16 @@ var ts; return undefined; } function lookupFromPackageJson() { - var scope = ts.getPackageScopeForPath(fileName, packageJsonInfoCache, host, options); - return (scope === null || scope === void 0 ? void 0 : scope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + var state = ts.getTemporaryModuleResolutionState(packageJsonInfoCache, host, options); + var packageJsonLocations = []; + state.failedLookupLocations = packageJsonLocations; + state.affectingLocations = packageJsonLocations; + var packageJsonScope = ts.getPackageScopeForPath(fileName, state); + var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope }; } } - ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + ts.getImpliedNodeFormatForFileWorker = getImpliedNodeFormatForFileWorker; /** @internal */ ts.plainJSErrors = new ts.Set([ // binder errors @@ -116519,6 +118110,9 @@ var ts; ts.Diagnostics.extends_clause_already_seen.code, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + ts.Diagnostics.Class_constructor_may_not_be_a_generator.code, + ts.Diagnostics.Class_constructor_may_not_be_an_accessor.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]); /** * Determine if source file needs to be re-created even if its text hasn't changed @@ -116748,7 +118342,7 @@ var ts; for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); - if (shouldCreateNewSourceFile || !newFile || + if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // old file wasn't redirect but new file is (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); @@ -117085,7 +118679,7 @@ var ts; // `result[i]` is either a `ResolvedModuleFull` or a marker. // If it is the former, we can leave it as is. if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; // TODO: GH#18217 + result[i] = undefined; } } else { @@ -117141,7 +118735,7 @@ var ts; }); } function tryReuseStructureFromOldProgram() { - var _a; + var _a, _b; if (!oldProgram) { return 0 /* StructureIsReused.Not */; } @@ -117182,12 +118776,15 @@ var ts; var seenPackageNames = new ts.Map(); for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; + var sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options); var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat) + : host.getSourceFile(oldSourceFile.fileName, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat); // TODO: GH#18217 if (!newSourceFile) { return 0 /* StructureIsReused.Not */; } + newSourceFile.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope; ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); var fileChanged = void 0; if (oldSourceFile.redirectInfo) { @@ -117227,38 +118824,43 @@ var ts; seenPackageNames.set(packageName, newKind); } if (fileChanged) { + if (oldSourceFile.impliedNodeFormat !== newSourceFile.impliedNodeFormat) { + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } // The `newSourceFile` object was created for the new program. - if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { // 'lib' references has changed. Matches behavior in changesAffectModuleResolution structureIsReused = 1 /* StructureIsReused.SafeModules */; } - if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + else if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files structureIsReused = 1 /* StructureIsReused.SafeModules */; } // check tripleslash references - if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed structureIsReused = 1 /* StructureIsReused.SafeModules */; } - // check imports and module augmentations - collectExternalModuleReferences(newSourceFile); - if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - // imports has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - // moduleAugmentations has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { - // dynamicImport has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - // 'types' references has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; + else { + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); @@ -117276,18 +118878,18 @@ var ts; return structureIsReused; } var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); - for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) { - var oldFile = oldSourceFiles_3[_b]; + for (var _c = 0, oldSourceFiles_3 = oldSourceFiles; _c < oldSourceFiles_3.length; _c++) { + var oldFile = oldSourceFiles_3[_c]; if (!ts.contains(modifiedFiles, oldFile)) { - for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) { - var moduleName = _d[_c]; + for (var _d = 0, _e = oldFile.ambientModuleNames; _d < _e.length; _d++) { + var moduleName = _e[_d]; ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); } } } // try to verify results of module resolution - for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) { - var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile; + for (var _f = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _f < modifiedSourceFiles_1.length; _f++) { + var _g = modifiedSourceFiles_1[_f], oldSourceFile = _g.oldFile, newSourceFile = _g.newFile; var moduleNames = getModuleNames(newSourceFile); var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); // ensure that module resolution results are still correct @@ -117314,14 +118916,14 @@ var ts; if (structureIsReused !== 2 /* StructureIsReused.Completely */) { return structureIsReused; } - if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host))) { + if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_b = host.hasChangedAutomaticTypeDirectiveNames) === null || _b === void 0 ? void 0 : _b.call(host))) { return 1 /* StructureIsReused.SafeModules */; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); - for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) { - var newSourceFile = newSourceFiles_1[_g]; + for (var _h = 0, newSourceFiles_1 = newSourceFiles; _h < newSourceFiles_1.length; _h++) { + var newSourceFile = newSourceFiles_1[_h]; filesByName.set(newSourceFile.path, newSourceFile); } var oldFilesByNameMap = oldProgram.getFilesByNameMap(); @@ -117383,6 +118985,7 @@ var ts; getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); }, redirectTargetsMap: redirectTargetsMap, getFileIncludeReasons: program.getFileIncludeReasons, + createHash: ts.maybeBind(host, host.createHash), }; } function writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data) { @@ -117736,7 +119339,7 @@ var ts; } } function walkArray(nodes, parent) { - if (parent.decorators === nodes && !options.experimentalDecorators) { + if (ts.canHaveModifiers(parent) && parent.modifiers === nodes && ts.some(nodes, ts.isDecorator) && !options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { @@ -117767,7 +119370,7 @@ var ts; if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { + if (ts.isModifier(modifier) && modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); } } @@ -117776,7 +119379,7 @@ var ts; break; case 164 /* SyntaxKind.Parameter */: // Check modifiers of parameter declaration - if (nodes === parent.modifiers) { + if (nodes === parent.modifiers && ts.some(nodes, ts.isModifier)) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -117895,7 +119498,7 @@ var ts; } function createSyntheticImport(text, file) { var externalHelpersModuleReference = ts.factory.createStringLiteral(text); - var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); + var importDecl = ts.factory.createImportDeclaration(/*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); ts.addEmitFlags(importDecl, 67108864 /* EmitFlags.NeverApplyImportHelper */); ts.setParent(externalHelpersModuleReference, importDecl); ts.setParent(importDecl, file); @@ -118103,13 +119706,16 @@ var ts; addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) { + var _a; var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; redirect.resolvedPath = resolvedPath; redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + redirect.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + redirect.packageJsonScope = sourceFileOptions.packageJsonScope; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { @@ -118138,14 +119744,14 @@ var ts; // It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache // and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way // to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront. - var impliedNodeFormat = getImpliedNodeFormatForFile(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); - return { - languageVersion: ts.getEmitScriptTarget(options), - impliedNodeFormat: impliedNodeFormat, - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(options) - }; + var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); + var languageVersion = ts.getEmitScriptTarget(options); + var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options); + return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) : + { languageVersion: languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator }; } function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { + var _a, _b; var path = toPath(fileName); if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(path); @@ -118232,14 +119838,15 @@ var ts; } } // We haven't looked for this file, do so now and cache result - var file = host.getSourceFile(fileName, getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options), function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile); + var sourceFileOptions = getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options); + var file = host.getSourceFile(fileName, sourceFileOptions, function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile || (((_a = oldProgram === null || oldProgram === void 0 ? void 0 : oldProgram.getSourceFileByPath(toPath(fileName))) === null || _a === void 0 ? void 0 : _a.impliedNodeFormat) !== sourceFileOptions.impliedNodeFormat)); if (packageId) { var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName, sourceFileOptions); redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, redirectedPath); addFileIncludeReason(dupFile, reason); @@ -118260,6 +119867,8 @@ var ts; file.path = path; file.resolvedPath = toPath(fileName); file.originalFileName = originalFileName; + file.packageJsonLocations = ((_b = sourceFileOptions.packageJsonLocations) === null || _b === void 0 ? void 0 : _b.length) ? sourceFileOptions.packageJsonLocations : undefined; + file.packageJsonScope = sourceFileOptions.packageJsonScope; addFileIncludeReason(file, reason); if (host.useCaseSensitiveFileNames()) { var pathLowerCase = ts.toFileNameLowerCase(path); @@ -118399,13 +120008,13 @@ var ts; ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); var mode = ref.resolutionMode || file.impliedNodeFormat; if (mode && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { - programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); + programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); } processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, }); } } function processTypeReferenceDirective(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -118890,7 +120499,7 @@ var ts; fileIncludeReasons = undefined; var location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason); var fileIncludeReasonDetails = fileIncludeReasons && ts.chainDiagnosticMessages(fileIncludeReasons, ts.Diagnostics.The_file_is_in_the_program_because_Colon); - var redirectInfo = file && ts.explainIfFileIsRedirect(file); + var redirectInfo = file && ts.explainIfFileIsRedirectAndImpliedFormat(file); var chain = ts.chainDiagnosticMessages.apply(void 0, __spreadArray([redirectInfo ? fileIncludeReasonDetails ? __spreadArray([fileIncludeReasonDetails], redirectInfo, true) : redirectInfo : fileIncludeReasonDetails, diagnostic], args || ts.emptyArray, false)); return location && isReferenceFileLocation(location) ? ts.createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : @@ -118960,7 +120569,7 @@ var ts; } var matchedByInclude = ts.getMatchedIncludeSpec(program, fileName); // Could be additional files specified as roots - if (!matchedByInclude) + if (!matchedByInclude || !ts.isString(matchedByInclude)) return undefined; configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude); message = ts.Diagnostics.File_is_matched_by_include_pattern_specified_here; @@ -119484,8 +121093,8 @@ var ts; (function (ts) { function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) { var outputFiles = []; - var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit; - return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; + var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics; + return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -119496,13 +121105,9 @@ var ts; function createManyToManyPathMap() { function create(forward, reverse, deleted) { var map = { - clone: function () { return create(new ts.Map(forward), new ts.Map(reverse), deleted && new ts.Set(deleted)); }, - forEach: function (fn) { return forward.forEach(fn); }, getKeys: function (v) { return reverse.get(v); }, getValues: function (k) { return forward.get(k); }, - hasKey: function (k) { return forward.has(k); }, keys: function () { return forward.keys(); }, - deletedKeys: function () { return deleted; }, deleteKey: function (k) { (deleted || (deleted = new ts.Set())).add(k); var set = forward.get(k); @@ -119529,11 +121134,6 @@ var ts; }); return map; }, - clear: function () { - forward.clear(); - reverse.clear(); - deleted === null || deleted === void 0 ? void 0 : deleted.clear(); - } }; return map; } @@ -119661,18 +121261,21 @@ var ts; * Creates the state of file references and signature for the new program from oldState if it is safe */ function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b, _c; var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? createManyToManyPathMap() : undefined; var exportedModulesMap = referencedMap ? createManyToManyPathMap() : undefined; - var hasCalledUpdateShapeSignature = new ts.Set(); var useOldState = canReuseOldState(referencedMap, oldState); // Ensure source files have parent pointers set newProgram.getTypeChecker(); // Create the reference map, and set the file infos - for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + for (var _i = 0, _d = newProgram.getSourceFiles(); _i < _d.length; _i++) { + var sourceFile = _d[_i]; var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); - var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined; + var oldUncommittedSignature = useOldState ? (_a = oldState.oldSignatures) === null || _a === void 0 ? void 0 : _a.get(sourceFile.resolvedPath) : undefined; + var signature = oldUncommittedSignature === undefined ? + useOldState ? (_b = oldState.fileInfos.get(sourceFile.resolvedPath)) === null || _b === void 0 ? void 0 : _b.signature : undefined : + oldUncommittedSignature || undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -119680,19 +121283,26 @@ var ts; } // Copy old visible to outside files map if (useOldState) { - var exportedModules = oldState.exportedModulesMap.getValues(sourceFile.resolvedPath); + var oldUncommittedExportedModules = (_c = oldState.oldExportedModulesMap) === null || _c === void 0 ? void 0 : _c.get(sourceFile.resolvedPath); + var exportedModules = oldUncommittedExportedModules === undefined ? + oldState.exportedModulesMap.getValues(sourceFile.resolvedPath) : + oldUncommittedExportedModules || undefined; if (exportedModules) { exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, impliedFormat: sourceFile.impliedNodeFormat }); + fileInfos.set(sourceFile.resolvedPath, { + version: version_2, + signature: signature, + affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, + impliedFormat: sourceFile.impliedNodeFormat + }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } @@ -119706,120 +121316,95 @@ var ts; } BuilderState.releaseCache = releaseCache; /** - * Creates a clone of the state + * Gets the files affected by the path from the program */ - function clone(state) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var _a, _b; - // Dont need to backup allFiles info since its cache anyway - return { - fileInfos: new ts.Map(state.fileInfos), - referencedMap: (_a = state.referencedMap) === null || _a === void 0 ? void 0 : _a.clone(), - exportedModulesMap: (_b = state.exportedModulesMap) === null || _b === void 0 ? void 0 : _b.clone(), - hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), - useFileVersionAsSignature: state.useFileVersionAsSignature, - }; + var result = getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); + return result; } - BuilderState.clone = clone; - /** - * Gets the files affected by the path from the program - */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { - // Since the operation could be cancelled, the signatures are always stored in the cache - // They will be committed once it is safe to use them - // eg when calling this api from tsserver, if there is no cancellation of the operation - // In the other cases the affected files signatures are committed only after the iteration through the result is complete - var signatureCache = cacheToUpdateSignature || new ts.Map(); + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var sourceFile = programOfThisState.getSourceFileByPath(path); if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); - if (!cacheToUpdateSignature) { - // Commit all the signatures in the signature cache - updateSignaturesFromCache(state, signatureCache); - } - return result; - } - BuilderState.getFilesAffectedBy = getFilesAffectedBy; - /** - * Updates the signatures from the cache into state's fileinfo signatures - * This should be called whenever it is safe to commit the state of the builder - */ - function updateSignaturesFromCache(state, signatureCache) { - signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); }); + return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName); } - BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + BuilderState.getFilesAffectedByWithOldState = getFilesAffectedByWithOldState; function updateSignatureOfFile(state, signature, path) { state.fileInfos.get(path).signature = signature; - state.hasCalledUpdateShapeSignature.add(path); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(path); } BuilderState.updateSignatureOfFile = updateSignatureOfFile; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache, useFileVersionAsSignature) { + function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName, useFileVersionAsSignature) { + var _a; if (useFileVersionAsSignature === void 0) { useFileVersionAsSignature = state.useFileVersionAsSignature; } - ts.Debug.assert(!!sourceFile); - ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) { + if ((_a = state.hasCalledUpdateShapeSignature) === null || _a === void 0 ? void 0 : _a.has(sourceFile.resolvedPath)) return false; - } var info = state.fileInfos.get(sourceFile.resolvedPath); - if (!info) - return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) { - var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, - /*emitOnlyDtsFiles*/ true, cancellationToken, + programOfThisState.emit(sourceFile, function (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) { + ts.Debug.assert(ts.isDeclarationFileName(fileName), "File extension for signature expected to be dts: Got:: ".concat(fileName)); + latestSignature = ts.computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data); + if (latestSignature !== prevSignature) { + updateExportedModules(state, sourceFile, sourceFiles[0].exportedModulesFromDeclarationEmit); + } + }, cancellationToken, + /*emitOnlyDtsFiles*/ true, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); - if (firstDts_1) { - ts.Debug.assert(ts.isDeclarationFileName(firstDts_1.name), "File extension for signature expected to be dts", function () { return "Found: ".concat(ts.getAnyExtensionFromPath(firstDts_1.name), " for ").concat(firstDts_1.name, ":: All output files: ").concat(JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; }))); }); - latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); - if (exportedModulesMapCache && latestSignature !== prevSignature) { - updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); - } - } } // Default is to use file version as signature if (latestSignature === undefined) { latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { + if (state.exportedModulesMap && latestSignature !== prevSignature) { + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); // All the references in this file are exported var references = state.referencedMap ? state.referencedMap.getValues(sourceFile.resolvedPath) : undefined; if (references) { - exportedModulesMapCache.set(sourceFile.resolvedPath, references); + state.exportedModulesMap.set(sourceFile.resolvedPath, references); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } } } - cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); + (state.oldSignatures || (state.oldSignatures = new ts.Map())).set(sourceFile.resolvedPath, prevSignature || false); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(sourceFile.resolvedPath); + info.signature = latestSignature; return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** * Coverts the declaration emit result into exported modules map */ - function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + function updateExportedModules(state, sourceFile, exportedModulesFromDeclarationEmit) { + if (!state.exportedModulesMap) + return; + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); if (!exportedModulesFromDeclarationEmit) { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); return; } var exportedModules; exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFilesFromImportedModuleSymbol(symbol)); }); if (exportedModules) { - exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules); + state.exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } function addExportedModule(exportedModulePaths) { if (exportedModulePaths === null || exportedModulePaths === void 0 ? void 0 : exportedModulePaths.length) { @@ -119831,19 +121416,6 @@ var ts; } } BuilderState.updateExportedModules = updateExportedModules; - /** - * Updates the exported modules from cache into state's exported modules map - * This should be called whenever it is safe to commit the state of the builder - */ - function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { - var _a; - if (exportedModulesMapCache) { - ts.Debug.assert(!!state.exportedModulesMap); - (_a = exportedModulesMapCache.deletedKeys()) === null || _a === void 0 ? void 0 : _a.forEach(function (path) { return state.exportedModulesMap.deleteKey(path); }); - exportedModulesMapCache.forEach(function (exportedModules, path) { return state.exportedModulesMap.set(path, exportedModules); }); - } - } - BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -119964,7 +121536,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cancellationToken, computeHash, getCanonicalFileName) { if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -119984,7 +121556,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, computeHash, getCanonicalFileName)) { queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } @@ -120010,32 +121582,33 @@ var ts; * Create the state so that we can iterate on changedFiles/affected files */ function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; + var outFilePath = ts.outFile(compilerOptions); // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them - if (!ts.outFile(compilerOptions)) { + if (!outFilePath) { state.semanticDiagnosticsPerFile = new ts.Map(); } + else if (compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.outSignature) && outFilePath === ts.outFile(oldState === null || oldState === void 0 ? void 0 : oldState.compilerOptions)) { + state.outSignature = oldState === null || oldState === void 0 ? void 0 : oldState.outSignature; + } state.changedFilesSet = new ts.Set(); + state.latestChangedDtsFile = compilerOptions.composite ? oldState === null || oldState === void 0 ? void 0 : oldState.latestChangedDtsFile : undefined; var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + var canCopyEmitSignatures = compilerOptions.composite && + (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && + !outFilePath && + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); if (useOldState) { - // Verify the sanity of old state - if (!oldState.currentChangedFilePath) { - var affectedSignatures = oldState.currentAffectedFilesSignatures; - ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); - } - var changedFilesSet = oldState.changedFilesSet; - if (canCopySemanticDiagnostics) { - ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); - } // Copy old state's changed files set - changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); }); - if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) { + (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); + if (!outFilePath && oldState.affectedFilesPendingEmit) { state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice(); state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind); state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; @@ -120056,6 +121629,8 @@ var ts; !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || // versions dont match oldInfo.version !== info.version || + // Implied formats dont match + oldInfo.impliedFormat !== info.impliedFormat || // Referenced files changed !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || // Referenced file was deleted in the new program @@ -120079,27 +121654,25 @@ var ts; state.semanticDiagnosticsFromOldState.add(sourceFilePath); } } + if (canCopyEmitSignatures) { + var oldEmitSignature = oldState.emitSignatures.get(sourceFilePath); + if (oldEmitSignature) + (state.emitSignatures || (state.emitSignatures = new ts.Map())).set(sourceFilePath, oldEmitSignature); + } }); // If the global file is removed, add all files as changed if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) { ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined) .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); }); } - else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { + else if (oldCompilerOptions && !outFilePath && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { // Add all files to affectedFilesPendingEmit since emit changed newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* BuilderFileEmit.Full */); }); ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set(); } - if (useOldState) { - // Any time the interpretation of a source file changes, mark it as changed - ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { - if (state.fileInfos.has(sourceFilePath) && state.fileInfos.get(sourceFilePath).impliedFormat !== info.impliedFormat) { - state.changedFilesSet.add(sourceFilePath); - } - }); - } - state.buildInfoEmitPending = !!state.changedFilesSet.size; + // Since old states change files set is copied, any additional change means we would need to emit build info + state.buildInfoEmitPending = !useOldState || state.changedFilesSet.size !== (((_b = oldState.changedFilesSet) === null || _b === void 0 ? void 0 : _b.size) || 0); return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -120135,30 +121708,35 @@ var ts; ts.BuilderState.releaseCache(state); state.program = undefined; } - /** - * Creates a clone of the state - */ - function cloneBuilderProgramState(state) { - var _a; - var newState = ts.BuilderState.clone(state); - newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile); - newState.changedFilesSet = new ts.Set(state.changedFilesSet); - newState.affectedFiles = state.affectedFiles; - newState.affectedFilesIndex = state.affectedFilesIndex; - newState.currentChangedFilePath = state.currentChangedFilePath; - newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures); - newState.currentAffectedFilesExportedModulesMap = (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clone(); - newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles); - newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; - newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState); - newState.program = state.program; - newState.compilerOptions = state.compilerOptions; - newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(); - newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind); - newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; - newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles); - newState.programEmitComplete = state.programEmitComplete; - return newState; + function backupBuilderProgramEmitState(state) { + var outFilePath = ts.outFile(state.compilerOptions); + // Only in --out changeFileSet is kept around till emit + ts.Debug.assert(!state.changedFilesSet.size || outFilePath); + return { + affectedFilesPendingEmit: state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(), + affectedFilesPendingEmitKind: state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind), + affectedFilesPendingEmitIndex: state.affectedFilesPendingEmitIndex, + seenEmittedFiles: state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles), + programEmitComplete: state.programEmitComplete, + emitSignatures: state.emitSignatures && new ts.Map(state.emitSignatures), + outSignature: state.outSignature, + latestChangedDtsFile: state.latestChangedDtsFile, + hasChangedEmitSignature: state.hasChangedEmitSignature, + changedFilesSet: outFilePath ? new ts.Set(state.changedFilesSet) : undefined, + }; + } + function restoreBuilderProgramEmitState(state, savedEmitState) { + state.affectedFilesPendingEmit = savedEmitState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitKind = savedEmitState.affectedFilesPendingEmitKind; + state.affectedFilesPendingEmitIndex = savedEmitState.affectedFilesPendingEmitIndex; + state.seenEmittedFiles = savedEmitState.seenEmittedFiles; + state.programEmitComplete = savedEmitState.programEmitComplete; + state.emitSignatures = savedEmitState.emitSignatures; + state.outSignature = savedEmitState.outSignature; + state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile; + state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; + if (savedEmitState.changedFilesSet) + state.changedFilesSet = savedEmitState.changedFilesSet; } /** * Verifies that source file is ok to be used in calls that arent handled by next @@ -120172,8 +121750,8 @@ var ts; * This is to allow the callers to be able to actually remove affected file only when the operation is complete * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained */ - function getNextAffectedFile(state, cancellationToken, computeHash, host) { - var _a; + function getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { @@ -120184,7 +121762,7 @@ var ts; if (!seenAffectedFiles.has(affectedFile.resolvedPath)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); return affectedFile; } affectedFilesIndex++; @@ -120193,10 +121771,8 @@ var ts; state.changedFilesSet.delete(state.currentChangedFilePath); state.currentChangedFilePath = undefined; // Commit the changes in file signature - ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); - state.currentAffectedFilesSignatures.clear(); - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); - (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clear(); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); state.affectedFiles = undefined; } // Get next changed file @@ -120214,12 +121790,7 @@ var ts; return program; } // Get next batch of affected files - if (!state.currentAffectedFilesSignatures) - state.currentAffectedFilesSignatures = new ts.Map(); - if (state.exportedModulesMap) { - state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap()); - } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedByWithOldState(state, program, nextKey.value, cancellationToken, computeHash, getCanonicalFileName); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; if (!state.seenAffectedFiles) @@ -120270,8 +121841,7 @@ var ts; * Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ - function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -120279,19 +121849,18 @@ var ts; // When a change affects the global scope, all files are considered to be affected without updating their signature // That means when affected file is handled, its signature can be out of date // To avoid this, ensure that we update the signature for any affected file in this scenario. - ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, cancellationToken, computeHash, getCanonicalFileName); return; } - ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: ".concat(affectedFile.fileName)); if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; - handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); } /** * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled, * Also we need to make sure signature is updated for these files */ - function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, host) { + function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { var program = ts.Debug.checkDefined(state.program); @@ -120302,7 +121871,7 @@ var ts; // This ensures that we dont later during incremental builds considering wrong signature. // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build // But we avoid expensive full shape computation, as using file version as shape is enough for correctness. - ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap, !host.disableUseFileVersionAsSignature); + ts.BuilderState.updateShapeSignature(state, program, sourceFile, cancellationToken, computeHash, getCanonicalFileName, !host.disableUseFileVersionAsSignature); // If not dts emit, nothing more to do if (ts.getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, 0 /* BuilderFileEmit.DtsOnly */); @@ -120323,41 +121892,25 @@ var ts; return !state.semanticDiagnosticsFromOldState.size; } function isChangedSignature(state, path) { - var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path); - var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; + var oldSignature = ts.Debug.checkDefined(state.oldSignatures).get(path) || undefined; + var newSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; return newSignature !== oldSignature; } - function forEachKeyOfExportedModulesMap(state, filePath, fn) { - // Go through exported modules from cache first - var keys = state.currentAffectedFilesExportedModulesMap.getKeys(filePath); - var result = keys && ts.forEachKey(keys, fn); - if (result) - return result; - // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - keys = state.exportedModulesMap.getKeys(filePath); - return keys && ts.forEachKey(keys, function (exportedFromPath) { - var _a; - // If the cache had an updated value, skip - return !state.currentAffectedFilesExportedModulesMap.hasKey(exportedFromPath) && - !((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(exportedFromPath)) ? - fn(exportedFromPath) : - undefined; - }); - } - function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host) { var _a; if (!((_a = state.fileInfos.get(filePath)) === null || _a === void 0 ? void 0 : _a.affectsGlobalScope)) return false; // Every file needs to be handled ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, state.program, /*firstSourceFile*/ undefined) - .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, host); }); + .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, getCanonicalFileName, host); }); removeDiagnosticsOfLibraryFiles(state); return true; } /** * Iterate on referencing modules that export entities from affected file and delete diagnostics and add pending emit */ - function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a; // If there was change in signature (dts output) for the changed file, // then only we need to handle pending file emit if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) @@ -120374,9 +121927,9 @@ var ts; var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { seenFileNamesMap.set(currentPath, true); - if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host)) return; - handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, host); + handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host); if (isChangedSignature(state, currentPath)) { var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath); queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); @@ -120384,16 +121937,15 @@ var ts; } } } - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); var seenFileAndExportsOfFile = new ts.Set(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, affectedFile.resolvedPath, function (exportedFromPath) { - if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, host)) + (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; var references = state.referencedMap.getKeys(exportedFromPath); return references && ts.forEachKey(references, function (filePath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); }); } @@ -120401,23 +121953,22 @@ var ts; * handle dts and semantic diagnostics on file and iterate on anything that exports this file * return true when all work is done and we can exit handling dts emit and semantic diagnostics */ - function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) return undefined; - if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; - handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, host); - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host); // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, filePath, function (exportedFromPath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + (_a = state.exportedModulesMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); // Remove diagnostics of files that import this file (without going to exports of referencing files) - (_a = state.referencedMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (referencingFilePath) { + (_b = state.referencedMap.getKeys(filePath)) === null || _b === void 0 ? void 0 : _b.forEach(function (referencingFilePath) { return !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file handleDtsMayChangeOf(// Dont add to seen since this is not yet done with the export removal - state, referencingFilePath, cancellationToken, computeHash, host); + state, referencingFilePath, cancellationToken, computeHash, getCanonicalFileName, host); }); return undefined; } @@ -120435,12 +121986,13 @@ var ts; } else { state.seenAffectedFiles.add(affected.resolvedPath); + // Change in changeSet/affectedFilesPendingEmit, buildInfo needs to be emitted + state.buildInfoEmitPending = true; if (emitKind !== undefined) { (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind); } if (isPendingEmit) { state.affectedFilesPendingEmitIndex++; - state.buildInfoEmitPending = true; } else { state.affectedFilesIndex++; @@ -120488,25 +122040,62 @@ var ts; } return ts.filterSemanticDiagnostics(diagnostics, state.compilerOptions); } + function isProgramBundleEmitBuildInfo(info) { + return !!ts.outFile(info.options || {}); + } + ts.isProgramBundleEmitBuildInfo = isProgramBundleEmitBuildInfo; /** * Gets the program information to be emitted in buildInfo so that we can use it to create new program */ function getProgramBuildInfo(state, getCanonicalFileName) { - if (ts.outFile(state.compilerOptions)) - return undefined; + var outFilePath = ts.outFile(state.compilerOptions); + if (outFilePath && !state.compilerOptions.composite) + return; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); + // Convert the file name to Path here if we set the fileName instead to optimize multiple d.ts file emits and having to compute Canonical path + var latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : undefined; + if (outFilePath) { + var fileNames_1 = []; + var fileInfos_1 = []; + state.program.getRootFileNames().forEach(function (f) { + var sourceFile = state.program.getSourceFile(f); + if (!sourceFile) + return; + fileNames_1.push(relativeToBuildInfo(sourceFile.resolvedPath)); + fileInfos_1.push(sourceFile.version); + }); + var result_15 = { + fileNames: fileNames_1, + fileInfos: fileInfos_1, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsBundleEmitBuildInfo"), + outSignature: state.outSignature, + latestChangedDtsFile: latestChangedDtsFile, + }; + return result_15; + } var fileNames = []; var fileNameToFileId = new ts.Map(); var fileIdsList; var fileNamesToFileIdListId; + var emitSignatures; var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var _b, _c; var key = _a[0], value = _a[1]; // Ensure fileId var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); - var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + var oldSignature = (_b = state.oldSignatures) === null || _b === void 0 ? void 0 : _b.get(key); + var actualSignature = oldSignature !== undefined ? oldSignature || undefined : value.signature; + if (state.compilerOptions.composite) { + var file = state.program.getSourceFileByPath(key); + if (!ts.isJsonSourceFile(file) && ts.sourceFileMayBeEmitted(file, state.program)) { + var emitSignature = (_c = state.emitSignatures) === null || _c === void 0 ? void 0 : _c.get(key); + if (emitSignature !== actualSignature) { + (emitSignatures || (emitSignatures = [])).push(emitSignature === undefined ? fileId : [fileId, emitSignature]); + } + } + } return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? // If file version is same as signature, dont serialize signature @@ -120514,11 +122103,11 @@ var ts; // If file info only contains version and signature and both are same we can just write string value.version : actualSignature !== undefined ? // If signature is not same as version, encode signature in the fileInfo - signature === undefined ? + oldSignature === undefined ? // If we havent computed signature, use fileInfo as is value : // Serialize fileInfo with new updated signature - { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : + { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : // Signature of the FileInfo is undefined, serialize it as false { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }; }); @@ -120533,17 +122122,13 @@ var ts; if (state.exportedModulesMap) { exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var _a; - if (state.currentAffectedFilesExportedModulesMap) { - if ((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(key)) { - return undefined; - } - var newValue = state.currentAffectedFilesExportedModulesMap.getValues(key); - if (newValue) { - return [toFileId(key), toFileIdListId(newValue)]; - } - } + var oldValue = (_a = state.oldExportedModulesMap) === null || _a === void 0 ? void 0 : _a.get(key); // Not in temporary cache, use existing value - return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue === undefined) + return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue) + return [toFileId(key), toFileIdListId(oldValue)]; + return undefined; }); } var semanticDiagnosticsPerFile; @@ -120554,9 +122139,7 @@ var ts; (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ toFileId(key), - state.hasReusableDiagnostic ? - value : - convertToReusableDiagnostics(value, relativeToBuildInfo) + convertToReusableDiagnostics(value, relativeToBuildInfo) ] : toFileId(key)); } @@ -120571,16 +122154,27 @@ var ts; } } } - return { + var changeFileSet; + if (state.changedFilesSet.size) { + for (var _d = 0, _e = ts.arrayFrom(state.changedFilesSet.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { + var path = _e[_d]; + (changeFileSet || (changeFileSet = [])).push(toFileId(path)); + } + } + var result = { fileNames: fileNames, fileInfos: fileInfos, - options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsMultiFileEmitBuildInfo"), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, affectedFilesPendingEmit: affectedFilesPendingEmit, + changeFileSet: changeFileSet, + emitSignatures: emitSignatures, + latestChangedDtsFile: latestChangedDtsFile, }; + return result; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } @@ -120605,24 +122199,21 @@ var ts; } return fileIdListId; } - } - function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { - var result; - var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var name = _a[_i]; - var optionKey = name.toLowerCase(); - var optionInfo = optionsNameMap.get(optionKey); - if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || - // We need to store `strict`, even though it won't be examined directly, so that the - // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly from the buildinfo - optionKey === "strict" || - // We need to store these to determine whether `lib` files need to be rechecked. - optionKey === "skiplibcheck" || optionKey === "skipdefaultlibcheck") { - (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); + /** + * @param optionKey key of CommandLineOption to use to determine if the option should be serialized in tsbuildinfo + */ + function convertToProgramBuildInfoCompilerOptions(options, optionKey) { + var result; + var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo[optionKey]) { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfoEnsuringAbsolutePath); + } } + return result; } - return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { if (option) { @@ -120696,6 +122287,41 @@ var ts; return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; } ts.getBuilderCreationParameters = getBuilderCreationParameters; + function getTextHandlingSourceMapForSignature(text, data) { + return (data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text; + } + function computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data) { + var _a; + text = getTextHandlingSourceMapForSignature(text, data); + var sourceFileDirectory; + if ((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length) { + text += data.diagnostics.map(function (diagnostic) { + return "".concat(locationInfo(diagnostic)).concat(ts.DiagnosticCategory[diagnostic.category]).concat(diagnostic.code, ": ").concat(flattenDiagnosticMessageText(diagnostic.messageText)); + }).join("\n"); + } + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(text); + function flattenDiagnosticMessageText(diagnostic) { + return ts.isString(diagnostic) ? + diagnostic : + diagnostic === undefined ? + "" : + !diagnostic.next ? + diagnostic.messageText : + diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText).join("\n"); + } + function locationInfo(diagnostic) { + if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) + return "(".concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + if (sourceFileDirectory === undefined) + sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath); + return "".concat(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceFileDirectory, diagnostic.file.resolvedPath, getCanonicalFileName)), "(").concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + } + } + ts.computeSignatureWithDiagnostics = computeSignatureWithDiagnostics; + function computeSignature(text, computeHash, data) { + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); + } + ts.computeSignature = computeSignature; function createBuilderProgram(kind, _a) { var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; // Return same program if underlying program doesnt change @@ -120714,7 +122340,6 @@ var ts; */ var computeHash = ts.maybeBind(host, host.createHash); var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); - var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 @@ -120723,21 +122348,13 @@ var ts; var getState = function () { return state; }; var builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics); builderProgram.getState = getState; - builderProgram.backupState = function () { - ts.Debug.assert(backupState === undefined); - backupState = cloneBuilderProgramState(state); - }; - builderProgram.restoreState = function () { - state = ts.Debug.checkDefined(backupState); - backupState = undefined; - }; + builderProgram.saveEmitState = function () { return backupBuilderProgramEmitState(state); }; + builderProgram.restoreEmitState = function (saved) { return restoreBuilderProgramEmitState(state, saved); }; + builderProgram.hasChangedEmitSignature = function () { return !!state.hasChangedEmitSignature; }; builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); }; builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; builderProgram.emit = emit; - builderProgram.releaseProgram = function () { - releaseCache(state); - backupState = undefined; - }; + builderProgram.releaseProgram = function () { return releaseCache(state); }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; } @@ -120764,7 +122381,7 @@ var ts; * in that order would be used to write the files */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); var emitKind = 1 /* BuilderFileEmit.Full */; var isPendingEmitFile = false; if (!affected) { @@ -120795,34 +122412,68 @@ var ts; return toAffectedFileEmitResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, affected !== state.program && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* BuilderFileEmit.DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile); } - function getWriteFileUpdatingSignatureCallback(writeFile) { + function getWriteFileCallback(writeFile, customTransformers) { return function (fileName, text, writeByteOrderMark, onError, sourceFiles, data) { - var _a; + var _a, _b, _c, _d, _e, _f, _g; if (ts.isDeclarationFileName(fileName)) { - ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); - var file = sourceFiles[0]; - var info = state.fileInfos.get(file.resolvedPath); - var signature = ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.get(file.resolvedPath)) || info.signature; - if (signature === file.version) { - var newSignature = (computeHash || ts.generateDjb2Hash)((data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text); - if (newSignature !== file.version) { // Update it - if (host.storeFilesChangingSignatureDuringEmit) - (state.filesChangingSignature || (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); - if (state.exportedModulesMap) - ts.BuilderState.updateExportedModules(file, file.exportedModulesFromDeclarationEmit, state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap())); - if (state.affectedFiles && state.affectedFilesIndex < state.affectedFiles.length) { - state.currentAffectedFilesSignatures.set(file.resolvedPath, newSignature); - } - else { - info.signature = newSignature; - if (state.exportedModulesMap) - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + if (!ts.outFile(state.compilerOptions)) { + ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); + var emitSignature = void 0; + if (!customTransformers) { + var file = sourceFiles[0]; + var info = state.fileInfos.get(file.resolvedPath); + if (info.signature === file.version) { + var signature = computeSignatureWithDiagnostics(file, text, computeHash, getCanonicalFileName, data); + // With d.ts diagnostics they are also part of the signature so emitSignature will be different from it since its just hash of d.ts + if (!((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length)) + emitSignature = signature; + if (signature !== file.version) { // Update it + if (host.storeFilesChangingSignatureDuringEmit) + ((_b = state.filesChangingSignature) !== null && _b !== void 0 ? _b : (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); + if (state.exportedModulesMap) + ts.BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit); + if (state.affectedFiles) { + // Keep old signature so we know what to undo if cancellation happens + var existing = (_c = state.oldSignatures) === null || _c === void 0 ? void 0 : _c.get(file.resolvedPath); + if (existing === undefined) + ((_d = state.oldSignatures) !== null && _d !== void 0 ? _d : (state.oldSignatures = new ts.Map())).set(file.resolvedPath, info.signature || false); + info.signature = signature; + } + else { + // These are directly commited + info.signature = signature; + (_e = state.oldExportedModulesMap) === null || _e === void 0 ? void 0 : _e.clear(); + } + } } } + // Store d.ts emit hash so later can be compared to check if d.ts has changed. + // Currently we do this only for composite projects since these are the only projects that can be referenced by other projects + // and would need their d.ts change time in --build mode + if (state.compilerOptions.composite) { + var filePath = sourceFiles[0].resolvedPath; + var oldSignature = (_f = state.emitSignatures) === null || _f === void 0 ? void 0 : _f.get(filePath); + emitSignature !== null && emitSignature !== void 0 ? emitSignature : (emitSignature = computeSignature(text, computeHash, data)); + // Dont write dts files if they didn't change + if (emitSignature === oldSignature) + return; + ((_g = state.emitSignatures) !== null && _g !== void 0 ? _g : (state.emitSignatures = new ts.Map())).set(filePath, emitSignature); + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; + } + } + else if (state.compilerOptions.composite) { + var newSignature = computeSignature(text, computeHash, data); + // Dont write dts files if they didn't change + if (newSignature === state.outSignature) + return; + state.outSignature = newSignature; + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; } } if (writeFile) @@ -120888,8 +122539,8 @@ var ts; } } } - return ts.Debug.checkDefined(state.program).emit(targetSourceFile, !ts.outFile(state.compilerOptions) && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + return ts.Debug.checkDefined(state.program).emit(targetSourceFile, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers); } /** @@ -120898,7 +122549,7 @@ var ts; */ function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { while (true) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); if (!affected) { // Done return undefined; @@ -120978,29 +122629,59 @@ var ts; { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; } ts.toBuilderStateFileInfo = toBuilderStateFileInfo; - function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { - var _a; + function createBuilderProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a, _b, _c, _d; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var filePaths = program.fileNames.map(toPath); - var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); - var fileInfos = new ts.Map(); - program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); - var state = { - fileInfos: fileInfos, - compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, - referencedMap: toManyToManyPathMap(program.referencedMap), - exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), - hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), - affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, - }; + var state; + var filePaths; + var filePathsSetList; + var latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : undefined; + if (isProgramBundleEmitBuildInfo(program)) { + state = { + fileInfos: new ts.Map(), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + latestChangedDtsFile: latestChangedDtsFile, + outSignature: program.outSignature, + }; + } + else { + filePaths = (_a = program.fileNames) === null || _a === void 0 ? void 0 : _a.map(toPath); + filePathsSetList = (_b = program.fileIdsList) === null || _b === void 0 ? void 0 : _b.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); + var fileInfos_2 = new ts.Map(); + var emitSignatures_1 = ((_c = program.options) === null || _c === void 0 ? void 0 : _c.composite) && !ts.outFile(program.options) ? new ts.Map() : undefined; + program.fileInfos.forEach(function (fileInfo, index) { + var path = toFilePath(index + 1); + var stateFileInfo = toBuilderStateFileInfo(fileInfo); + fileInfos_2.set(path, stateFileInfo); + if (emitSignatures_1 && stateFileInfo.signature) + emitSignatures_1.set(path, stateFileInfo.signature); + }); + (_d = program.emitSignatures) === null || _d === void 0 ? void 0 : _d.forEach(function (value) { + if (ts.isNumber(value)) + emitSignatures_1.delete(toFilePath(value)); + else + emitSignatures_1.set(toFilePath(value[0]), value[1]); + }); + state = { + fileInfos: fileInfos_2, + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toManyToManyPathMap(program.referencedMap), + exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), + hasReusableDiagnostic: true, + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, + changedFilesSet: new ts.Set(ts.map(program.changeFileSet, toFilePath)), + latestChangedDtsFile: latestChangedDtsFile, + emitSignatures: (emitSignatures_1 === null || emitSignatures_1 === void 0 ? void 0 : emitSignatures_1.size) ? emitSignatures_1 : undefined, + }; + } return { getState: function () { return state; }, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: ts.notImplemented, getProgramOrUndefined: ts.returnUndefined, releaseProgram: ts.noop, @@ -121020,6 +122701,7 @@ var ts; getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented, emitBuildInfo: ts.notImplemented, close: ts.noop, + hasChangedEmitSignature: ts.returnFalse, }; function toPath(path) { return ts.toPath(path, buildInfoDirectory, getCanonicalFileName); @@ -121045,12 +122727,24 @@ var ts; return map; } } - ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; + ts.createBuilderProgramUsingProgramBuildInfo = createBuilderProgramUsingProgramBuildInfo; + function getBuildInfoFileVersionMap(program, buildInfoPath, host) { + var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var fileInfos = new ts.Map(); + program.fileInfos.forEach(function (fileInfo, index) { + var path = ts.toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName); + var version = ts.isString(fileInfo) ? fileInfo : fileInfo.version; // eslint-disable-line @typescript-eslint/no-unnecessary-type-assertion + fileInfos.set(path, version); + }); + return fileInfos; + } + ts.getBuildInfoFileVersionMap = getBuildInfoFileVersionMap; function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { return { getState: ts.notImplemented, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: getProgram, getProgramOrUndefined: function () { return getState().program; }, releaseProgram: function () { return getState().program = undefined; }, @@ -121110,7 +122804,7 @@ var ts; * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" * @param dirPath */ - function canWatchDirectory(dirPath) { + function canWatchDirectoryOrFile(dirPath) { var rootLength = ts.getRootLength(dirPath); if (dirPath.length === rootLength) { // Ignore "/", "c:/" @@ -121147,15 +122841,19 @@ var ts; } return true; } - ts.canWatchDirectory = canWatchDirectory; + ts.canWatchDirectoryOrFile = canWatchDirectoryOrFile; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var resolutionsWithFailedLookups = []; + var resolutionsWithOnlyAffectingLocations = []; var resolvedFileToResolution = ts.createMultiMap(); + var impliedFormatPackageJsons = new ts.Map(); var hasChangedAutomaticTypeDirectiveNames = false; + var affectingPathChecksForFile; + var affectingPathChecks; var failedLookupChecks; var startsWithPathChecks; var isInDirectoryChecks; @@ -121182,6 +122880,7 @@ var ts; var failedLookupDefaultExtensions = [".ts" /* Extension.Ts */, ".tsx" /* Extension.Tsx */, ".js" /* Extension.Js */, ".jsx" /* Extension.Jsx */, ".json" /* Extension.Json */]; var customFailedLookupPaths = new ts.Map(); var directoryWatchesOfFailedLookups = new ts.Map(); + var fileWatchesOfAffectingLocations = new ts.Map(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0; @@ -121193,7 +122892,7 @@ var ts; finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + startCachingPerDirectoryResolution: startCachingPerDirectoryResolution, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -121224,6 +122923,7 @@ var ts; } function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + ts.clearMap(fileWatchesOfAffectingLocations, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); @@ -121231,12 +122931,15 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; + resolutionsWithOnlyAffectingLocations.length = 0; failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; - // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update - // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - clearPerDirectoryResolutions(); + affectingPathChecks = undefined; + affectingPathChecksForFile = undefined; + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); + impliedFormatPackageJsons.clear(); hasChangedAutomaticTypeDirectiveNames = false; } function startRecordingFilesWithChangedResolutions() { @@ -121268,25 +122971,60 @@ var ts; return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } - function clearPerDirectoryResolutions() { - moduleResolutionCache.clear(); - typeReferenceDirectiveResolutionCache.clear(); + function startCachingPerDirectoryResolution() { + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } - function finishCachingPerDirectoryResolution() { + function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = undefined; - clearPerDirectoryResolutions(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + // Update file watches + if (newProgram !== oldProgram) { + newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFiles().forEach(function (newFile) { + var _a, _b, _c; + var expected = ts.isExternalOrCommonJsModule(newFile) ? (_b = (_a = newFile.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0 : 0; + var existing = (_c = impliedFormatPackageJsons.get(newFile.path)) !== null && _c !== void 0 ? _c : ts.emptyArray; + for (var i = existing.length; i < expected; i++) { + createFileWatcherOfAffectingLocation(newFile.packageJsonLocations[i], /*forResolution*/ false); + } + if (existing.length > expected) { + for (var i = expected; i < existing.length; i++) { + fileWatchesOfAffectingLocations.get(existing[i]).files--; + } + } + if (expected) + impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations); + else + impliedFormatPackageJsons.delete(newFile.path); + }); + impliedFormatPackageJsons.forEach(function (existing, path) { + if (!(newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFileByPath(path))) { + existing.forEach(function (location) { return fileWatchesOfAffectingLocations.get(location).files--; }); + impliedFormatPackageJsons.delete(path); + } + }); + } directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); + fileWatchesOfAffectingLocations.forEach(function (watcher, path) { + if (watcher.files === 0 && watcher.resolutions === 0) { + fileWatchesOfAffectingLocations.delete(path); + watcher.watcher.close(); + } + }); hasChangedAutomaticTypeDirectiveNames = false; } function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference, _containingSourceFile, mode) { - var _a; + var _a, _b; var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { @@ -121297,11 +123035,12 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _c = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _c.resolvedModule, failedLookupLocations = _c.failedLookupLocations, affectingLocations = _c.affectingLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = primaryResult.affectingLocations).push.apply(_b, affectingLocations); return primaryResult; } } @@ -121506,7 +123245,7 @@ var ts; } // If the directory is node_modules use it to watch, always watch it recursively if (ts.isNodeModulesDirectory(dirPath)) { - return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + return canWatchDirectoryOrFile(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -121524,7 +123263,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + return canWatchDirectoryOrFile(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -121552,10 +123291,11 @@ var ts; } function watchFailedLookupLocationOfResolution(resolution) { ts.Debug.assert(!!resolution.refCount); - var failedLookupLocations = resolution.failedLookupLocations; - if (!failedLookupLocations.length) + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (!failedLookupLocations.length && !affectingLocations.length) return; - resolutionsWithFailedLookups.push(resolution); + if (failedLookupLocations.length) + resolutionsWithFailedLookups.push(resolution); var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; @@ -121582,12 +123322,87 @@ var ts; // This is always non recursive setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } + watchAffectingLocationsOfResolution(resolution, !failedLookupLocations.length); + } + function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { + ts.Debug.assert(!!resolution.refCount); + var affectingLocations = resolution.affectingLocations; + if (!affectingLocations.length) + return; + if (addToResolutionsWithOnlyAffectingLocations) + resolutionsWithOnlyAffectingLocations.push(resolution); + // Watch package json + for (var _i = 0, affectingLocations_1 = affectingLocations; _i < affectingLocations_1.length; _i++) { + var affectingLocation = affectingLocations_1[_i]; + createFileWatcherOfAffectingLocation(affectingLocation, /*forResolution*/ true); + } + } + function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) { + var fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation); + if (fileWatcher) { + if (forResolution) + fileWatcher.resolutions++; + else + fileWatcher.files++; + return; + } + var locationToWatch = affectingLocation; + if (resolutionHost.realpath) { + locationToWatch = resolutionHost.realpath(affectingLocation); + if (affectingLocation !== locationToWatch) { + var fileWatcher_1 = fileWatchesOfAffectingLocations.get(locationToWatch); + if (fileWatcher_1) { + if (forResolution) + fileWatcher_1.resolutions++; + else + fileWatcher_1.files++; + fileWatcher_1.paths.add(affectingLocation); + fileWatchesOfAffectingLocations.set(affectingLocation, fileWatcher_1); + return; + } + } + } + var paths = new ts.Set(); + paths.add(locationToWatch); + var actualWatcher = canWatchDirectoryOrFile(resolutionHost.toPath(locationToWatch)) ? + resolutionHost.watchAffectingFileLocation(locationToWatch, function (fileName, eventKind) { + cachedDirectoryStructureHost === null || cachedDirectoryStructureHost === void 0 ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + paths.forEach(function (path) { + if (watcher.resolutions) + (affectingPathChecks !== null && affectingPathChecks !== void 0 ? affectingPathChecks : (affectingPathChecks = new ts.Set())).add(path); + if (watcher.files) + (affectingPathChecksForFile !== null && affectingPathChecksForFile !== void 0 ? affectingPathChecksForFile : (affectingPathChecksForFile = new ts.Set())).add(path); + packageJsonMap === null || packageJsonMap === void 0 ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); + }); + resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); + }) : ts.noopFileWatcher; + var watcher = { + watcher: actualWatcher !== ts.noopFileWatcher ? { + close: function () { + actualWatcher.close(); + // Ensure when watching symlinked package.json, we can close the actual file watcher only once + actualWatcher = ts.noopFileWatcher; + } + } : actualWatcher, + resolutions: forResolution ? 1 : 0, + files: forResolution ? 0 : 1, + paths: paths, + }; + fileWatchesOfAffectingLocations.set(locationToWatch, watcher); + if (affectingLocation !== locationToWatch) { + fileWatchesOfAffectingLocations.set(affectingLocation, watcher); + paths.add(affectingLocation); + } } function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { var program = resolutionHost.getCurrentProgram(); if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) { resolutions.forEach(watchFailedLookupLocationOfResolution); } + else { + resolutions.forEach(function (resolution) { return watchAffectingLocationsOfResolution(resolution, /*addToResolutionWithOnlyAffectingLocations*/ true); }); + } } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); @@ -121609,38 +123424,44 @@ var ts; if (resolved && resolved.resolvedFileName) { resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution); } - if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { - // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups - return; - } - var failedLookupLocations = resolution.failedLookupLocations; - var removeAtRoot = false; - for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { - var failedLookupLocation = failedLookupLocations_2[_i]; - var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (toWatch) { - var dirPath = toWatch.dirPath; - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - if (dirPath === rootPath) { - removeAtRoot = true; - } - else { - removeDirectoryWatcher(dirPath); - } } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + else if (affectingLocations.length) { + ts.unorderedRemoveItem(resolutionsWithOnlyAffectingLocations, resolution); } - if (removeAtRoot) { - removeDirectoryWatcher(rootPath); + for (var _a = 0, affectingLocations_2 = affectingLocations; _a < affectingLocations_2.length; _a++) { + var affectingLocation = affectingLocations_2[_a]; + var watcher = fileWatchesOfAffectingLocations.get(affectingLocation); + watcher.resolutions--; } } function removeDirectoryWatcher(dirPath) { @@ -121694,7 +123515,7 @@ var ts; resolution.isInvalidated = invalidated = true; for (var _a = 0, _b = ts.Debug.checkDefined(resolution.files); _a < _b.length; _a++) { var containingFilePath = _b[_a]; - (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); // When its a file with inferred types resolution, invalidate type reference directive resolution hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile); } @@ -121719,7 +123540,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = new ts.Set())).add(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -121737,7 +123558,7 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { @@ -121749,7 +123570,7 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); // If the invalidated file is from a node_modules package, invalidate everything else // in the package since we might not get notifications for other files in the package. // This hardens our logic against unreliable file watchers. @@ -121761,22 +123582,46 @@ var ts; resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { - return false; + var _a; + var invalidated = false; + if (affectingPathChecksForFile) { + (_a = resolutionHost.getCurrentProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFiles().forEach(function (f) { + if (ts.some(f.packageJsonLocations, function (location) { return affectingPathChecksForFile.has(location); })) { + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(f.path); + invalidated = true; + } + }); + affectingPathChecksForFile = undefined; + } + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks && !affectingPathChecks) { + return invalidated; + } + invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach(function (_value, path) { return isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : undefined; }); } - var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; + invalidated = invalidateResolutions(resolutionsWithOnlyAffectingLocations, canInvalidatedFailedLookupResolutionWithAffectingLocation) || invalidated; + affectingPathChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { - return resolution.failedLookupLocations.some(function (location) { - var locationPath = resolutionHost.toPath(location); - return ts.contains(failedLookupChecks, locationPath) || - ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || - (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); - }); + if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) + return true; + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) + return false; + return resolution.failedLookupLocations.some(function (location) { return isInvalidatedFailedLookup(resolutionHost.toPath(location)); }); + } + function isInvalidatedFailedLookup(locationPath) { + return (failedLookupChecks === null || failedLookupChecks === void 0 ? void 0 : failedLookupChecks.has(locationPath)) || + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + ts.firstDefinedIterator((isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath) ? true : undefined; }); + } + function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) { + return !!affectingPathChecks && resolution.affectingLocations.some(function (location) { return affectingPathChecks.has(location); }); } function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); @@ -121842,7 +123687,7 @@ var ts; function directoryExistsForTypeRootWatch(nodeTypesDirectory) { var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); var dirPath = resolutionHost.toPath(dir); - return dirPath === rootPath || canWatchDirectory(dirPath); + return dirPath === rootPath || canWatchDirectoryOrFile(dirPath); } } ts.createResolutionCache = createResolutionCache; @@ -121953,7 +123798,7 @@ var ts; var info = getInfo(importingSourceFileName, host); var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences, options); return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode); }) || - getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences); + getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences, options) { if (options === void 0) { options = {}; } @@ -122036,7 +123881,7 @@ var ts; return nodeModulesSpecifiers; } if (!specifier && !modulePath.isRedirect) { - var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences); + var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); if (ts.pathIsBareSpecifier(local)) { pathsSpecifiers = ts.append(pathsSpecifiers, local); } @@ -122064,7 +123909,7 @@ var ts; var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); return { getCanonicalFileName: getCanonicalFileName, importingSourceFileName: importingSourceFileName, sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, _a) { + function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, _a) { var ending = _a.ending, relativePreference = _a.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var sourceDirectory = info.sourceDirectory, getCanonicalFileName = info.getCanonicalFileName; @@ -122078,9 +123923,8 @@ var ts; if (!relativeToBaseUrl) { return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); - var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths; + var fromPaths = paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, getAllowedEndings(ending, compilerOptions, importMode), host, compilerOptions); + var nonRelative = fromPaths === undefined && baseUrl !== undefined ? removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) : fromPaths; if (!nonRelative) { return relativePath; } @@ -122166,9 +124010,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -122188,10 +124032,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_17 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_17) + return result_17; } }); }); @@ -122233,7 +124077,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_32 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -122257,9 +124101,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_10 = _loop_32(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_10 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -122315,28 +124159,102 @@ var ts; return ambientModuleDeclare.name.text; } } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + function getAllowedEndings(preferredEnding, compilerOptions, importMode) { + if (ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && importMode === ts.ModuleKind.ESNext) { + return [2 /* Ending.JsExtension */]; + } + switch (preferredEnding) { + case 2 /* Ending.JsExtension */: return [2 /* Ending.JsExtension */, 0 /* Ending.Minimal */, 1 /* Ending.Index */]; + case 1 /* Ending.Index */: return [1 /* Ending.Index */, 0 /* Ending.Minimal */, 2 /* Ending.JsExtension */]; + case 0 /* Ending.Minimal */: return [0 /* Ending.Minimal */, 1 /* Ending.Index */, 2 /* Ending.JsExtension */]; + default: ts.Debug.assertNever(preferredEnding); + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(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, + // meaning a '.ts' or '.d.ts' extension is allowed to resolve. This is distinct from the case where a '*' substitution + // causes a module specifier to have an extension, i.e. the extension comes from the module specifier in a JS/TS file + // and matches the '*'. For example: + // + // Module Specifier | Path Mapping (key: [pattern]) | Interpolation | Resolution Action + // ---------------------->------------------------------->--------------------->--------------------------------------------------------------- + // import "@app/foo" -> "@app/*": ["./src/app/*.ts"] -> "./src/app/foo.ts" -> tryFile("./src/app/foo.ts") || [continue resolution algorithm] + // import "@app/foo.ts" -> "@app/*": ["./src/app/*"] -> "./src/app/foo.ts" -> [continue resolution algorithm] + // + // (https://github.com/microsoft/TypeScript/blob/ad4ded80e1d58f0bf36ac16bea71bc10d9f09895/src/compiler/moduleNameResolver.ts#L2509-L2516) + // + // The interpolation produced by both scenarios is identical, but only in the former, where the extension is encoded in + // the path mapping rather than in the module specifier, will we prioritize a file lookup on the interpolation result. + // (In fact, currently, the latter scenario will necessarily fail since no resolution mode recognizes '.ts' as a valid + // extension for a module specifier.) + // + // Here, this means we need to be careful about whether we generate a match from the target filename (typically with a + // .ts extension) or the possible relative module specifiers representing that file: + // + // Filename | Relative Module Specifier Candidates | Path Mapping | Filename Result | Module Specifier Results + // --------------------<----------------------------------------------<------------------------------<-------------------||---------------------------- + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*.d.ts"] <- @app/haha || (none) + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*"] <- (none) || @app/haha, @app/haha.js + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*.d.ts"] <- @app/foo/index || (none) + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*"] <- (none) || @app/foo, @app/foo/index, @app/foo/index.js + // dist/wow.js.js <- dist/wow.js, dist/wow.js.js <- "@app/*": ["./dist/*.js"] <- @app/wow.js || @app/wow, @app/wow.js + // + // The "Filename Result" can be generated only if `pattern` has an extension. Care must be taken that the list of + // relative module specifiers to run the interpolation (a) is actually valid for the module resolution mode, (b) takes + // into account the existence of other files (e.g. 'dist/wow.js' cannot refer to 'dist/wow.js.js' if 'dist/wow.js' + // exists) and (c) that they are ordered by preference. The last row shows that the filename result and module + // specifier results are not mutually exclusive. Note that the filename result is a higher priority in module + // resolution, but as long criteria (b) above is met, I don't think its result needs to be the highest priority result + // in module specifier generation. I have included it last, as it's difficult to tell exactly where it should be + // sorted among the others for a particular value of `importModuleSpecifierEnding`. + var candidates = allowedEndings.map(function (ending) { return ({ + ending: ending, + value: removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) + }); }); + if (ts.tryGetExtensionFromPath(pattern)) { + candidates.push({ ending: undefined, value: relativeToBaseUrl }); + } if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix) || - !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); - return key.replace("*", matchedStar); + var prefix = pattern.substring(0, indexOfStar); + var suffix = pattern.substring(indexOfStar + 1); + for (var _b = 0, candidates_3 = candidates; _b < candidates_3.length; _b++) { + var _c = candidates_3[_b], ending = _c.ending, value = _c.value; + if (value.length >= prefix.length + suffix.length && + ts.startsWith(value, prefix) && + ts.endsWith(value, suffix) && + validateEnding({ ending: ending, value: value })) { + var matchedStar = value.substring(prefix.length, value.length - suffix.length); + return { value: key.replace("*", matchedStar) }; + } } } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; + else if (ts.some(candidates, function (c) { return c.ending !== 0 /* Ending.Minimal */ && pattern === c.value; }) || + ts.some(candidates, function (c) { return c.ending === 0 /* Ending.Minimal */ && pattern === c.value && validateEnding(c); })) { + return { value: key }; } + }; + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } + function validateEnding(_a) { + var ending = _a.ending, value = _a.value; + // Optimization: `removeExtensionAndIndexPostFix` can query the file system (a good bit) if `ending` is `Minimal`, the basename + // is 'index', and a `host` is provided. To avoid that until it's unavoidable, we ran the function with no `host` above. Only + // here, after we've checked that the minimal ending is indeed a match (via the length and prefix/suffix checks / `some` calls), + // do we check that the host-validated result is consistent with the answer we got before. If it's not, it falls back to the + // `Ending.Index` result, which should already be in the list of candidates if `Minimal` was. (Note: the assumption here is + // that every module resolution mode that supports dropping extensions also supports dropping `/index`. Like literally + // everything else in this file, this logic needs to be updated if that's not true in some future module resolution mode.) + return ending !== 0 /* Ending.Minimal */ || value === removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions, host); + } } var MatchingMode; (function (MatchingMode) { @@ -122432,10 +124350,10 @@ var ts; return undefined; } // Simplify the full file path to something that can be resolved by Node. + var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var moduleSpecifier = path; var isPackageRootPath = false; if (!packageNameOnly) { - var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var packageRootIndex = parts.packageRootIndex; var moduleFileName = void 0; while (true) { @@ -122484,15 +124402,13 @@ var ts; var packageRootPath = path.substring(0, packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); var moduleFileToTry = path; + var maybeBlockedByTypesVersions = false; var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) { var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); + var importMode = overrideMode || importingSourceFile.impliedNodeFormat; if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { - // `conditions` *could* be made to go against `importingSourceFile.impliedNodeFormat` if something wanted to generate - // an ImportEqualsDeclaration in an ESM-implied file or an ImportCall in a CJS-implied file. But since this function is - // usually called to conjure an import out of thin air, we don't have an existing usage to call `getModeForUsageAtIndex` - // with, so for now we just stick with the mode of the file. - var conditions = ["node", overrideMode || importingSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext ? "import" : "require", "types"]; + var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"]; var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, ts.getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions) : undefined; @@ -122511,16 +124427,26 @@ var ts; : undefined; if (versionPaths) { var subModuleName = path.slice(packageRootPath.length + 1); - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Ending.Minimal */, options), versionPaths.paths); - if (fromPaths !== undefined) { + var fromPaths = tryGetModuleNameFromPaths(subModuleName, versionPaths.paths, getAllowedEndings(preferences.ending, options, importMode), host, options); + if (fromPaths === undefined) { + maybeBlockedByTypesVersions = true; + } + else { moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths); } } // If the file is the main module, it can be imported by the package name var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; - if (ts.isString(mainFileRelative)) { + if (ts.isString(mainFileRelative) && !(maybeBlockedByTypesVersions && ts.matchPatternOrExact(ts.tryParsePatterns(versionPaths.paths), mainFileRelative))) { + // The 'main' file is also subject to mapping through typesVersions, and we couldn't come up with a path + // explicitly through typesVersions, so if it matches a key in typesVersions now, it's not reachable. + // (The only way this can happen is if some file in a package that's not resolvable from outside the + // package got pulled into the program anyway, e.g. transitively through a file that *is* reachable. It + // happens very easily in fourslash tests though, since every test file listed gets included. See + // importNameCodeFix_typesVersions.ts for an example.) var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + // ^ An arbitrary removal of file extension for this comparison is almost certainly wrong return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry }; } } @@ -122815,23 +124741,46 @@ var ts; var file = _c[_i]; write("".concat(toFileName(file, relativeFileName))); (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write(" ".concat(fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText)); }); - (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); + (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); } } ts.explainFiles = explainFiles; - function explainIfFileIsRedirect(file, fileNameConvertor) { + function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { + var _a; var result; if (file.path !== file.resolvedPath) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); } if (file.redirectInfo) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); } + if (ts.isExternalOrCommonJsModule(file)) { + switch (file.impliedNodeFormat) { + case ts.ModuleKind.ESNext: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + break; + case ts.ModuleKind.CommonJS: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, file.packageJsonScope.packageJsonContent.type ? + ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : + ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + else if ((_a = file.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found)); + } + break; + } + } return result; } - ts.explainIfFileIsRedirect = explainIfFileIsRedirect; + ts.explainIfFileIsRedirectAndImpliedFormat = explainIfFileIsRedirectAndImpliedFormat; function getMatchedFileSpec(program, fileName) { var _a; var configFile = program.getCompilerOptions().configFile; @@ -122848,6 +124797,9 @@ var ts; var configFile = program.getCompilerOptions().configFile; if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedIncludeSpecs)) return undefined; + // Return true if its default include spec + if (configFile.configFileSpecs.isDefaultIncludeSpec) + return true; var isJsonFile = ts.fileExtensionIs(fileName, ".json" /* Extension.Json */); var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); var useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); @@ -122913,11 +124865,13 @@ var ts; if (matchedByFiles) return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Part_of_files_list_in_tsconfig_json); var matchedByInclude = getMatchedIncludeSpec(program, fileName); - return matchedByInclude ? + return ts.isString(matchedByInclude) ? ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) : - // Could be additional files specified as roots - ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation); + // Could be additional files specified as roots or matched by default include + ts.chainDiagnosticMessages(/*details*/ undefined, matchedByInclude ? + ts.Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : + ts.Diagnostics.Root_file_specified_for_compilation); case ts.FileIncludeKind.SourceFromProjectReference: case ts.FileIncludeKind.OutputFromProjectReference: var isOutput = reason.kind === ts.FileIncludeKind.OutputFromProjectReference; @@ -123036,11 +124990,19 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", + AffectingFileLocation: "File location affecting resolution", TypeRoots: "Type roots", ConfigFileOfReferencedProject: "Config file of referened project", ExtendedConfigOfReferencedProject: "Extended config file of referenced project", WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", PackageJson: "package.json file", + ClosedScriptInfo: "Closed Script info", + ConfigFileForInferredRoot: "Config file for the inferred project root", + NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache", + MissingSourceMapFile: "Missing source map file", + NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root", + MissingGeneratedFile: "Missing generated file", + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -123149,6 +125111,7 @@ var ts; createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, storeFilesChangingSignatureDuringEmit: system.storeFilesChangingSignatureDuringEmit, + now: ts.maybeBind(system, system.now), }; } ts.createProgramHost = createProgramHost; @@ -123216,20 +125179,27 @@ var ts; var ts; (function (ts) { function readBuilderProgram(compilerOptions, host) { - if (ts.outFile(compilerOptions)) - return undefined; var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions); if (!buildInfoPath) return undefined; - var content = host.readFile(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); + var buildInfo; + if (host.getBuildInfo) { + // host provides buildinfo, get it from there. This allows host to cache it + buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); + if (!buildInfo) + return undefined; + } + else { + var content = host.readFile(buildInfoPath); + if (!content) + return undefined; + buildInfo = ts.getBuildInfo(content); + } if (buildInfo.version !== ts.version) return undefined; if (!buildInfo.program) return undefined; - return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); + return ts.createBuilderProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); } ts.readBuilderProgram = readBuilderProgram; function createIncrementalCompilerHost(options, system) { @@ -123282,14 +125252,12 @@ var ts; var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc var missingFilesMap; // Map of file watchers for the missing files - var packageJsonMap; // map of watchers for package json files used in module resolution var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations var parsedConfigs; // Parsed commandline and watching cached for referenced projects var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation - var changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution var reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files @@ -123346,6 +125314,7 @@ var ts; compilerHost.getCompilationSettings = function () { return compilerOptions; }; compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect); compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); }; + compilerHost.watchAffectingFileLocation = function (file, cb) { return watchFile(file, cb, ts.PollingInterval.High, watchOptions, ts.WatchType.AffectingFileLocation); }; compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); }; compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations; @@ -123379,6 +125348,9 @@ var ts; return host.resolveTypeReferenceDirectives.apply(host, args); }) : (function (typeDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference, containingFileMode); }); + compilerHost.getModuleResolutionCache = host.resolveModuleNames ? + ts.maybeBind(host, host.getModuleResolutionCache) : + (function () { return resolutionCache.getModuleResolutionCache(); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); @@ -123428,10 +125400,6 @@ var ts; }); parsedConfigs = undefined; } - if (packageJsonMap) { - ts.clearMap(packageJsonMap, ts.closeFileWatcher); - packageJsonMap = undefined; - } } function getCurrentBuilderProgram() { return builderProgram; @@ -123445,12 +125413,12 @@ var ts; var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); - if (program && (changesAffectResolution || ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions))) { + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { resolutionCache.clear(); } } // All resolutions are invalid if user provided resolutions - var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution); + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { @@ -123466,7 +125434,6 @@ var ts; } createNewProgram(hasInvalidatedResolution); } - changesAffectResolution = false; // reset for next sync reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); @@ -123486,16 +125453,11 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + var oldProgram = getCurrentProgram(); builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); - // map package json cache entries to their realpaths so we don't try to watch across symlinks - var packageCacheEntries = ts.map(resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [compilerHost.realpath ? toPath(compilerHost.realpath(path)) : path, data]; - }); - resolutionCache.finishCachingPerDirectoryResolution(); + resolutionCache.finishCachingPerDirectoryResolution(builderProgram.getProgram(), oldProgram); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath); - ts.updatePackageJsonWatch(packageCacheEntries, packageJsonMap || (packageJsonMap = new ts.Map()), watchPackageJsonLookupPath); if (needsUpdateInTypeRootWatch) { resolutionCache.updateTypeRootsWatch(); } @@ -123575,9 +125537,6 @@ var ts; sourceFilesCache.set(path, false); } } - if (sourceFile) { - sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); - } return sourceFile; } return hostSourceFile.sourceFile; @@ -123692,6 +125651,7 @@ var ts; } function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; rootFileNames = ts.getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions); if (ts.updateErrorForNoInputFiles(rootFileNames, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; @@ -123800,21 +125760,6 @@ var ts; ts.noopFileWatcher : watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } - function watchPackageJsonLookupPath(packageJsonPath) { - // If the package.json is pulled into the compilation itself (eg, via json imports), don't add a second watcher here - return sourceFilesCache.has(packageJsonPath) ? - ts.noopFileWatcher : - watchFilePath(packageJsonPath, packageJsonPath, onPackageJsonChange, ts.PollingInterval.High, watchOptions, ts.WatchType.PackageJson); - } - function onPackageJsonChange(fileName, eventKind, path) { - updateCachedSystemWithFile(fileName, path, eventKind); - // package.json changes invalidate module resolution and can change the set of loaded files - // so if we witness a change to one, we have to do a full reload - reloadLevel = ts.ConfigFileProgramReloadLevel.Full; - changesAffectResolution = true; - // Update the program - scheduleProgramUpdate(); - } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { @@ -123972,14 +125917,17 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream"; - UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate"; - UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream"; - UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["OutOfDateBuildInfo"] = 7] = "OutOfDateBuildInfo"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 8] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 9] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 10] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 11] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["UpToDateWithInputFileText"] = 12] = "UpToDateWithInputFileText"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 13] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ForceBuild"] = 14] = "ForceBuild"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); function resolveConfigFileProjectName(project) { if (ts.fileExtensionIs(project, ".json" /* Extension.Json */)) { @@ -124024,9 +125972,12 @@ var ts; function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); }); } - function newer(date1, date2) { - return date2 > date1 ? date2 : date1; + /*@internal*/ + /** Helper to use now method instead of current date for testing purposes to get consistent baselines */ + function getCurrentTime(host) { + return host.now ? host.now() : new Date(); } + ts.getCurrentTime = getCurrentTime; /*@internal*/ function isCircularBuildOrder(buildOrder) { return !!buildOrder && !!buildOrder.buildOrder; @@ -124101,6 +126052,7 @@ var ts; compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); }; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); + compilerHost.getModuleResolutionCache = ts.maybeBind(host, host.getModuleResolutionCache); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { @@ -124116,6 +126068,7 @@ var ts; return ts.loadWithTypeDirectiveCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader_4); }; } + compilerHost.getBuildInfo = function (fileName, configFilePath) { return getBuildInfo(state, fileName, toResolvedConfigFilePath(state, configFilePath), /*modifiedTime*/ undefined); }; var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -124132,8 +126085,9 @@ var ts; resolvedConfigFilePaths: new ts.Map(), configFileCache: new ts.Map(), projectStatus: new ts.Map(), - buildInfoChecked: new ts.Map(), extendedConfigCache: new ts.Map(), + buildInfoCache: new ts.Map(), + outputTimeStamps: new ts.Map(), builderPrograms: new ts.Map(), diagnostics: new ts.Map(), projectPendingBuild: new ts.Map(), @@ -124149,7 +126103,6 @@ var ts; allProjectBuildPending: true, needsSummary: true, watchAllProjectsPending: watch, - currentInvalidatedProject: undefined, // Watch state watch: watch, allWatchedWildcardDirectories: new ts.Map(), @@ -124157,6 +126110,7 @@ var ts; allWatchedConfigFiles: new ts.Map(), allWatchedExtendedConfigFiles: new ts.Map(), allWatchedPackageJsonFiles: new ts.Map(), + filesWatched: new ts.Map(), lastCachedPackageJsonLookups: new ts.Map(), timerToBuildInvalidatedProject: undefined, reportFileChangeDetected: false, @@ -124263,11 +126217,12 @@ var ts; // Config file cache ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete); - ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.buildInfoCache, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.outputTimeStamps, currentProjects, noopOnDelete); // Remove watches for the program no longer in the solution if (state.watch) { ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher }); @@ -124382,7 +126337,6 @@ var ts; })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {})); function doneInvalidatedProject(state, projectPath) { state.projectPendingBuild.delete(projectPath); - state.currentInvalidatedProject = undefined; return state.diagnostics.has(projectPath) ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; @@ -124558,21 +126512,21 @@ var ts; } function emit(writeFileCallback, cancellationToken, customTransformers) { var _a; - var _b, _c; + var _b, _c, _d; ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.Emit); // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly - program.backupState(); + var saved = program.saveEmitState(); var declDiagnostics; var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; var outputFiles = []; var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, /*write*/ undefined, - /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, + /*reportSummary*/ undefined, function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark, buildInfo: data === null || data === void 0 ? void 0 : data.buildInfo }); }, cancellationToken, /*emitOnlyDts*/ false, customTransformers || ((_c = (_b = state.host).getCustomTransformers) === null || _c === void 0 ? void 0 : _c.call(_b, project))).emitResult; // Don't emit .d.ts if there are decl file errors if (declDiagnostics) { - program.restoreState(); + program.restoreEmitState(saved); (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step); return { emitSkipped: true, @@ -124581,38 +126535,38 @@ var ts; } // Actual Emit var host = state.host, compilerHost = state.compilerHost; - var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; - var newestDeclarationFileContentChangedTime = minimumDate; - var anyDtsChanged = false; + var resultFlags = ((_d = program.hasChangedEmitSignature) === null || _d === void 0 ? void 0 : _d.call(program)) ? BuildResultFlags.None : BuildResultFlags.DeclarationOutputUnchanged; var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var options = program.getCompilerOptions(); + var isIncremental = ts.isIncrementalCompilation(options); + var outputTimeStampMap; + var now; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; - var priorChangeTime; - if (!anyDtsChanged && ts.isDeclarationFileName(name)) { - // Check for unchanged .d.ts files - if (host.fileExists(name) && state.readFileWithCache(name) === text) { - priorChangeTime = host.getModifiedTime(name); - } - else { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - anyDtsChanged = true; - } - } + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; + var path = toPath(state, name); emittedOutputs.set(toPath(state, name), name); + if (buildInfo) + setBuildInfo(state, buildInfo, projectPath, options, resultFlags); ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); - if (priorChangeTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + if (!isIncremental && state.watch) { + (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); } }); - finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); + finishEmit(emitterDiagnostics, emittedOutputs, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); return emitResult; } function emitBuildInfo(writeFileCallback, cancellationToken) { ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.EmitBuildInfo); - var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken); + var emitResult = program.emitBuildInfo(function (name, text, writeByteOrderMark, onError, sourceFiles, data) { + if (data === null || data === void 0 ? void 0 : data.buildInfo) + setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), BuildResultFlags.DeclarationOutputUnchanged); + if (writeFileCallback) + writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); + else + state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); + }, cancellationToken); if (emitResult.diagnostics.length) { reportErrors(state, emitResult.diagnostics); state.diagnostics.set(projectPath, __spreadArray(__spreadArray([], state.diagnostics.get(projectPath), true), emitResult.diagnostics, true)); @@ -124625,7 +126579,7 @@ var ts; step = BuildStep.QueueReferencingProjects; return emitResult; } - function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) { + function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) { var _a; var emitDiagnostics = emitterDiagnostics.getDiagnostics(); if (emitDiagnostics.length) { @@ -124636,13 +126590,10 @@ var ts; emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); }); } // Update time stamps for rest of the outputs - var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); + updateOutputTimestampsWorker(state, config, projectPath, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); state.diagnostics.delete(projectPath); state.projectStatus.set(projectPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ? - maximumDate : - newestDeclarationFileContentChangedTime, oldestOutputFileName: oldestOutputFileName }); afterProgramDone(state, program, config); @@ -124677,13 +126628,21 @@ var ts; ts.Debug.assert(!!outputFiles.length); var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; + var existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var _b, _c; + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; emittedOutputs.set(toPath(state, name), name); + if (buildInfo) { + if (((_b = buildInfo.program) === null || _b === void 0 ? void 0 : _b.outSignature) !== ((_c = existingBuildInfo.program) === null || _c === void 0 ? void 0 : _c.outSignature)) { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + } + setBuildInfo(state, buildInfo, projectPath, config.options, resultFlags); + } ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); }); - var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged); + var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, outputFiles[0].name, resultFlags); return { emitSkipped: false, diagnostics: emitDiagnostics }; } function executeSteps(till, cancellationToken, writeFile, customTransformers) { @@ -124733,17 +126692,11 @@ var ts; !!ts.getConfigFileParsingDiagnostics(config).length || !ts.isIncrementalCompilation(config.options); } - function getNextInvalidatedProject(state, buildOrder, reportQueue) { + function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { if (!state.projectPendingBuild.size) return undefined; if (isCircularBuildOrder(buildOrder)) return undefined; - if (state.currentInvalidatedProject) { - // Only if same buildOrder the currentInvalidated project can be sent again - return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ? - state.currentInvalidatedProject : - undefined; - } var options = state.options, projectPendingBuild = state.projectPendingBuild; for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { var project = buildOrder[projectIndex]; @@ -124776,9 +126729,9 @@ var ts; watchPackageJsonFiles(state, project, projectPath, config); } var status = getUpToDateStatus(state, config, projectPath); - verboseReportProjectStatus(state, project, status); if (!options.force) { if (status.type === ts.UpToDateStatusType.UpToDate) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Up to date, skip @@ -124788,12 +126741,20 @@ var ts; } continue; } - if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) { + if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes || status.type === ts.UpToDateStatusType.UpToDateWithInputFileText) { reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); - return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder); + return { + kind: InvalidatedProjectKind.UpdateOutputFileStamps, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config + }; } } if (status.type === ts.UpToDateStatusType.UpstreamBlocked) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); if (options.verbose) { @@ -124804,17 +126765,37 @@ var ts; continue; } if (status.type === ts.UpToDateStatusType.ContainerOnly) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Do nothing continue; } - return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ? - InvalidatedProjectKind.Build : - InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder); + return { + kind: needsBuild(state, status, config) ? + InvalidatedProjectKind.Build : + InvalidatedProjectKind.UpdateBundle, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config, + }; } return undefined; } + function createInvalidatedProjectWithInfo(state, info, buildOrder) { + verboseReportProjectStatus(state, info.project, info.status); + return info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps ? + createBuildOrUpdateInvalidedProject(info.kind, state, info.project, info.projectPath, info.projectIndex, info.config, buildOrder) : + createUpdateOutputFileStampsProject(state, info.project, info.projectPath, info.config, buildOrder); + } + function getNextInvalidatedProject(state, buildOrder, reportQueue) { + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); + if (!info) + return info; + return createInvalidatedProjectWithInfo(state, info, buildOrder); + } function listEmittedFile(_a, proj, file) { var write = _a.write; if (write && proj.options.listEmittedFiles) { @@ -124832,7 +126813,7 @@ var ts; } function afterProgramDone(state, program, config) { if (program) { - if (program && state.write) + if (state.write) ts.listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); @@ -124845,7 +126826,8 @@ var ts; state.projectCompilerOptions = state.baseCompilerOptions; } function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) { - var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions()); + // Since buildinfo has changeset and diagnostics when doing multi file emit, only --out cannot emit buildinfo if it has errors + var canEmitBuildInfo = program && !ts.outFile(program.getCompilerOptions()); reportAndStoreErrors(state, resolvedPath, diagnostics); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: "".concat(errorType, " errors") }); if (canEmitBuildInfo) @@ -124853,9 +126835,107 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } + function isFileWatcherWithModifiedTime(value) { + return !!value.watcher; + } + function getModifiedTime(state, fileName) { + var path = toPath(state, fileName); + var existing = state.filesWatched.get(path); + if (state.watch && !!existing) { + if (!isFileWatcherWithModifiedTime(existing)) + return existing; + if (existing.modifiedTime) + return existing.modifiedTime; + } + // In watch mode we store the modified times in the cache + // This is either Date | FileWatcherWithModifiedTime because we query modified times first and + // then after complete compilation of the project, watch the files so we dont want to loose these modified times. + var result = ts.getModifiedTime(state.host, fileName); + if (state.watch) { + if (existing) + existing.modifiedTime = result; + else + state.filesWatched.set(path, result); + } + return result; + } + function watchFile(state, file, callback, pollingInterval, options, watchType, project) { + var path = toPath(state, file); + var existing = state.filesWatched.get(path); + if (existing && isFileWatcherWithModifiedTime(existing)) { + existing.callbacks.push(callback); + } + else { + var watcher = state.watchFile(file, function (fileName, eventKind, modifiedTime) { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + existing.modifiedTime = modifiedTime; + existing.callbacks.forEach(function (cb) { return cb(fileName, eventKind, modifiedTime); }); + }, pollingInterval, options, watchType, project); + state.filesWatched.set(path, { callbacks: [callback], watcher: watcher, modifiedTime: existing }); + } + return { + close: function () { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + if (existing.callbacks.length === 1) { + state.filesWatched.delete(path); + ts.closeFileWatcherOf(existing); + } + else { + ts.unorderedRemoveItem(existing.callbacks, callback); + } + } + }; + } + function getOutputTimeStampMap(state, resolvedConfigFilePath) { + // Output timestamps are stored only in watch mode + if (!state.watch) + return undefined; + var result = state.outputTimeStamps.get(resolvedConfigFilePath); + if (!result) + state.outputTimeStamps.set(resolvedConfigFilePath, result = new ts.Map()); + return result; + } + function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) { + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(options); + var existing = getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath); + var modifiedTime = getCurrentTime(state.host); + if (existing) { + existing.buildInfo = buildInfo; + existing.modifiedTime = modifiedTime; + if (!(resultFlags & BuildResultFlags.DeclarationOutputUnchanged)) + existing.latestChangedDtsTime = modifiedTime; + } + else { + state.buildInfoCache.set(resolvedConfigPath, { + path: toPath(state, buildInfoPath), + buildInfo: buildInfo, + modifiedTime: modifiedTime, + latestChangedDtsTime: resultFlags & BuildResultFlags.DeclarationOutputUnchanged ? undefined : modifiedTime, + }); + } + } + function getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + return (existing === null || existing === void 0 ? void 0 : existing.path) === path ? existing : undefined; + } + function getBuildInfo(state, buildInfoPath, resolvedConfigPath, modifiedTime) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + if (existing !== undefined && existing.path === path) { + return existing.buildInfo || undefined; + } + var value = state.readFileWithCache(buildInfoPath); + var buildInfo = value ? ts.getBuildInfo(value) : undefined; + ts.Debug.assert(modifiedTime || !buildInfo); + state.buildInfoCache.set(resolvedConfigPath, { path: path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || ts.missingFileModifiedTime }); + return buildInfo; + } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = ts.getModifiedTime(state.host, configFile); + var tsconfigTime = getModifiedTime(state, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -124865,88 +126945,24 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { - var force = !!state.options.force; - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - var host = state.host; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: ts.UpToDateStatusType.Unbuildable, - reason: "".concat(inputFile, " does not exist") - }; - } - if (!force) { - var inputTime = ts.getModifiedTime(host, inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - } + var _a, _b; // Container if no files are specified in the project if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) { return { type: ts.UpToDateStatusType.ContainerOnly }; } - // Collect the expected outputs of this project - var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - if (!force) { - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = ts.getModifiedTime(host, output); - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (ts.isDeclarationFileName(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; + // Fast check to see if reference projects are upto date and error free + var referenceStatuses; + var force = !!state.options.force; if (project.projectReferences) { state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream }); - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); + for (var _i = 0, _c = project.projectReferences; _i < _c.length; _i++) { + var ref = _c[_i]; var resolvedRef = ts.resolveProjectReferencePath(ref); var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef); - var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath); + var resolvedConfig = parseConfigFile(state, resolvedRef, resolvedRefPath); + var refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath); // Its a circular reference ignore the status of this project if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream || refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project @@ -124968,75 +126984,192 @@ var ts; upstreamProjectName: ref.path }; } - // Check oldest output file name only if there is no missing output file name - // (a check we will have skipped if this is a forced build) - if (!force && !missingOutputFileName) { - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + if (!force) + (referenceStatuses || (referenceStatuses = [])).push({ ref: ref, refStatus: refStatus, resolvedRefPath: resolvedRefPath, resolvedConfig: resolvedConfig }); + } + } + if (force) + return { type: ts.UpToDateStatusType.ForceBuild }; + // Check buildinfo first + var host = state.host; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); + var oldestOutputFileName; + var oldestOutputFileTime = maximumDate; + var buildInfoTime; + var buildInfoProgram; + var buildInfoVersionMap; + if (buildInfoPath) { + var buildInfoCacheEntry_1 = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath); + buildInfoTime = (buildInfoCacheEntry_1 === null || buildInfoCacheEntry_1 === void 0 ? void 0 : buildInfoCacheEntry_1.modifiedTime) || ts.getModifiedTime(host, buildInfoPath); + if (buildInfoTime === ts.missingFileModifiedTime) { + if (!buildInfoCacheEntry_1) { + state.buildInfoCache.set(resolvedPath, { + path: toPath(state, buildInfoPath), + buildInfo: false, + modifiedTime: buildInfoTime + }); + } + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: buildInfoPath + }; + } + var buildInfo = ts.Debug.checkDefined(getBuildInfo(state, buildInfoPath, resolvedPath, buildInfoTime)); + if ((buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + return { + type: ts.UpToDateStatusType.TsVersionOutputOfDate, + version: buildInfo.version + }; + } + if (buildInfo.program) { + // If there are pending changes that are not emitted, project is out of date + 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))) { return { - type: ts.UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path + type: ts.UpToDateStatusType.OutOfDateBuildInfo, + buildInfoFile: buildInfoPath }; } + buildInfoProgram = buildInfo.program; } + oldestOutputFileTime = buildInfoTime; + oldestOutputFileName = buildInfoPath; } - if (missingOutputFileName !== undefined) { - return { - type: ts.UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; + // Check input files + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + /** True if input file has changed timestamp but text is not changed, we can then do only timestamp updates on output to make it look up-to-date later */ + var pseudoInputUpToDate = false; + // Get timestamps of input files + for (var _d = 0, _e = project.fileNames; _d < _e.length; _d++) { + var inputFile = _e[_d]; + var inputTime = getModifiedTime(state, inputFile); + if (inputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.Unbuildable, + reason: "".concat(inputFile, " does not exist") + }; + } + // If an buildInfo is older than the newest input, we can stop checking + if (buildInfoTime && buildInfoTime < inputTime) { + var version_3 = void 0; + var currentVersion = void 0; + if (buildInfoProgram) { + // Read files and see if they are same, read is anyways cached + if (!buildInfoVersionMap) + buildInfoVersionMap = ts.getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + version_3 = buildInfoVersionMap.get(toPath(state, inputFile)); + var text = version_3 ? state.readFileWithCache(inputFile) : undefined; + currentVersion = text && (host.createHash || ts.generateDjb2Hash)(text); + if (version_3 && version_3 === currentVersion) + pseudoInputUpToDate = true; + } + if (!version_3 || version_3 !== currentVersion) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: buildInfoPath, + newerInputFileName: inputFile + }; + } + } + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - if (isOutOfDateWithInputs) { - return { - type: ts.UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; + // Now see if all outputs are newer than the newest input + // Dont check output timestamps if we have buildinfo telling us output is uptodate + if (!buildInfoPath) { + // Collect the expected outputs of this project + var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, resolvedPath); + for (var _f = 0, outputs_1 = outputs; _f < outputs_1.length; _f++) { + var output = outputs_1[_f]; + var path = toPath(state, output); + // Output is missing; can stop checking + var outputTime = outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.get(path); + if (!outputTime) { + outputTime = ts.getModifiedTime(state.host, output); + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.set(path, outputTime); + } + if (outputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: output + }; + } + // If an output is older than the newest input, we can stop checking + if (outputTime < newestInputFileTime) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: output, + newerInputFileName: newestInputFileName + }; + } + // No need to get newestDeclarationFileContentChangedTime since thats needed only for composite projects + // And composite projects are the only ones that can be referenced + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + } } - else { - // Check tsconfig time - var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); - if (configStatus) - return configStatus; - // Check extended config time - var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); - if (extendedConfigStatus) - return extendedConfigStatus; - // Check package file time - var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { - var path = _a[0]; - return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); - }); - if (dependentPackageFileStatus) - return dependentPackageFileStatus; - } - if (!force && !state.buildInfoChecked.has(resolvedPath)) { - state.buildInfoChecked.set(resolvedPath, true); - var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); - if (buildInfoPath) { - var value = state.readFileWithCache(buildInfoPath); - var buildInfo = value && ts.getBuildInfo(value); - if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + var seenRefs = buildInfoPath ? new ts.Set() : undefined; + var buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath); + seenRefs === null || seenRefs === void 0 ? void 0 : seenRefs.add(resolvedPath); + /** Inputs are up-to-date, just need either timestamp update or bundle prepend manipulation to make it look up-to-date */ + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (referenceStatuses) { + for (var _g = 0, referenceStatuses_1 = referenceStatuses; _g < referenceStatuses_1.length; _g++) { + var _h = referenceStatuses_1[_g], ref = _h.ref, refStatus = _h.refStatus, resolvedConfig = _h.resolvedConfig, resolvedRefPath = _h.resolvedRefPath; + usesPrepend = usesPrepend || !!(ref.prepend); + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // Check if tsbuildinfo path is shared, then we need to rebuild + if (buildInfoCacheEntry && hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath)) { return { - type: ts.UpToDateStatusType.TsVersionOutputOfDate, - version: buildInfo.version + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: buildInfoPath, + newerProjectName: ref.path }; } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + var newestDeclarationFileContentChangedTime = getLatestChangedDtsTime(state, resolvedConfig.options, resolvedRefPath); + if (newestDeclarationFileContentChangedTime && newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + // Check package file time + var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { + var path = _a[0]; + return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); + }); + if (dependentPackageFileStatus) + return dependentPackageFileStatus; if (usesPrepend && pseudoUpToDate) { return { type: ts.UpToDateStatusType.OutOfDateWithPrepend, @@ -125046,15 +127179,36 @@ var ts; } // Up to date return { - type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + type: pseudoUpToDate ? + ts.UpToDateStatusType.UpToDateWithUpstreamTypes : + pseudoInputUpToDate ? + ts.UpToDateStatusType.UpToDateWithInputFileText : + ts.UpToDateStatusType.UpToDate, newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, oldestOutputFileName: oldestOutputFileName }; } + function hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath) { + if (seenRefs.has(resolvedRefPath)) + return false; + seenRefs.add(resolvedRefPath); + var refBuildInfo = state.buildInfoCache.get(resolvedRefPath); + if (refBuildInfo.path === buildInfoCacheEntry.path) + return true; + if (resolvedConfig.projectReferences) { + // Check references + for (var _i = 0, _a = resolvedConfig.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRef = ts.resolveProjectReferencePath(ref); + var resolvedRefPath_1 = toResolvedConfigFilePath(state, resolvedRef); + var resolvedConfig_1 = parseConfigFile(state, resolvedRef, resolvedRefPath_1); + if (hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig_1, resolvedRefPath_1)) + return true; + } + } + return false; + } function getUpToDateStatus(state, project, resolvedPath) { if (project === undefined) { return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; @@ -125067,39 +127221,71 @@ var ts; state.projectStatus.set(resolvedPath, actual); return actual; } - function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) { if (proj.options.noEmit) - return priorNewestUpdateTime; + return; + var now; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(proj.options); + if (buildInfoPath) { + // For incremental projects, only buildinfo needs to be upto date with timestamp check + // as we dont check output files for up-to-date ness + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(toPath(state, buildInfoPath)))) { + if (!!state.options.verbose) + reportStatus(state, verboseMessage, proj.options.configFilePath); + state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); + getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; + } + state.outputTimeStamps.delete(projectPath); + return; + } var host = state.host; var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, projectPath); + var modifiedOutputs = outputTimeStampMap ? new ts.Set() : undefined; if (!skipOutputs || outputs.length !== skipOutputs.size) { var reportVerbose = !!state.options.verbose; - var now = host.now ? host.now() : new Date(); for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { var file = outputs_2[_i]; - if (skipOutputs && skipOutputs.has(toPath(state, file))) { + var path = toPath(state, file); + if (skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(path)) continue; - } if (reportVerbose) { reportVerbose = false; reportStatus(state, verboseMessage, proj.options.configFilePath); } - if (ts.isDeclarationFileName(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); + host.setModifiedTime(file, now || (now = getCurrentTime(state.host))); + // Store output timestamps in a map because non incremental build will need to check them to determine up-to-dateness + if (outputTimeStampMap) { + outputTimeStampMap.set(path, now); + modifiedOutputs.add(path); } - host.setModifiedTime(file, now); } } - return priorNewestUpdateTime; + // Clear out timestamps not in output list any more + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.forEach(function (_value, key) { + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) + outputTimeStampMap.delete(key); + }); + } + function getLatestChangedDtsTime(state, options, resolvedConfigPath) { + if (!options.composite) + return undefined; + var entry = ts.Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); + if (entry.latestChangedDtsTime !== undefined) + return entry.latestChangedDtsTime || undefined; + var latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? + state.host.getModifiedTime(ts.getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, ts.getDirectoryPath(entry.path))) : + undefined; + entry.latestChangedDtsTime = latestChangedDtsTime || false; + return latestChangedDtsTime; } function updateOutputTimestamps(state, proj, resolvedPath) { if (state.options.dry) { return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath); } - var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); + updateOutputTimestampsWorker(state, proj, resolvedPath, ts.Diagnostics.Updating_output_timestamps_of_project_0); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: priorNewestUpdateTime, oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames()) }); } @@ -125145,6 +127331,7 @@ var ts; break; } // falls through + case ts.UpToDateStatusType.UpToDateWithInputFileText: case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: case ts.UpToDateStatusType.OutOfDateWithPrepend: if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { @@ -125255,9 +127442,9 @@ var ts; function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) { state.reportFileChangeDetected = true; invalidateProject(state, resolvedPath, reloadLevel); - scheduleBuildInvalidatedProject(state); + scheduleBuildInvalidatedProject(state, 250, /*changeDetected*/ true); } - function scheduleBuildInvalidatedProject(state) { + function scheduleBuildInvalidatedProject(state, time, changeDetected) { var hostWithWatch = state.hostWithWatch; if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; @@ -125265,25 +127452,38 @@ var ts; if (state.timerToBuildInvalidatedProject) { hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject); } - state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state); + state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, state, changeDetected); } - function buildNextInvalidatedProject(state) { + function buildNextInvalidatedProject(state, changeDetected) { state.timerToBuildInvalidatedProject = undefined; if (state.reportFileChangeDetected) { state.reportFileChangeDetected = false; state.projectErrorsReported.clear(); reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation); } + var projectsBuilt = 0; var buildOrder = getBuildOrder(state); var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false); if (invalidatedProject) { invalidatedProject.done(); - if (state.projectPendingBuild.size) { - // Schedule next project for build - if (state.watch && !state.timerToBuildInvalidatedProject) { - scheduleBuildInvalidatedProject(state); + projectsBuilt++; + while (state.projectPendingBuild.size) { + // If already scheduled, skip + if (state.timerToBuildInvalidatedProject) + return; + // Before scheduling check if the next project needs build + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, /*reportQueue*/ false); + if (!info) + break; // Nothing to build any more + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps && (changeDetected || projectsBuilt === 5)) { + // Schedule next project for build + scheduleBuildInvalidatedProject(state, 100, /*changeDetected*/ false); + return; } - return; + var project = createInvalidatedProjectWithInfo(state, info, buildOrder); + project.done(); + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps) + projectsBuilt++; } } disableCache(state); @@ -125292,12 +127492,10 @@ var ts; function watchConfigFile(state, resolved, resolvedPath, parsed) { if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; - state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(resolved, function () { - invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); - }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); + state.allWatchedConfigFiles.set(resolvedPath, watchFile(state, resolved, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(state, extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -125329,7 +127527,7 @@ var ts; if (!state.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), { - createNewValue: function (_path, input) { return state.watchFile(input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, + createNewValue: function (_path, input) { return watchFile(state, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -125337,7 +127535,7 @@ var ts; if (!state.watch || !state.lastCachedPackageJsonLookups) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), new ts.Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), { - createNewValue: function (path, _input) { return state.watchFile(path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, + createNewValue: function (path, _input) { return watchFile(state, path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -125387,8 +127585,6 @@ var ts; return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath); }, invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); }, - buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); }, - getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); }, close: function () { return stopWatching(state); }, }; } @@ -125469,19 +127665,18 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { - if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { - return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); - } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); case ts.UpToDateStatusType.OutOfDateWithUpstream: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.OutputMissing: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName)); + case ts.UpToDateStatusType.OutOfDateBuildInfo: + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), relName(state, status.buildInfoFile)); case ts.UpToDateStatusType.UpToDate: if (status.newestInputFileTime !== undefined) { - return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); } // Don't report anything for "up to date because it was already built" -- too verbose break; @@ -125489,6 +127684,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName)); + case ts.UpToDateStatusType.UpToDateWithInputFileText: + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, relName(state, configFileName)); case ts.UpToDateStatusType.UpstreamOutOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName)); case ts.UpToDateStatusType.UpstreamBlocked: @@ -125499,6 +127696,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason); case ts.UpToDateStatusType.TsVersionOutputOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, ts.version); + case ts.UpToDateStatusType.ForceBuild: + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); case ts.UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects // falls through @@ -125665,7 +127864,7 @@ var ts; * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ - function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry, compilerOptions) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } @@ -125683,12 +127882,14 @@ var ts; addInferredTypings(typeAcquisition.include, "Explicitly included types"); var exclude = typeAcquisition.exclude || []; // Directories to search for package.json, bower.json and other typing information - var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); - possibleSearchDirs.add(projectRootPath); - possibleSearchDirs.forEach(function (searchDir) { - getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); - getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); - }); + if (!compilerOptions.types) { + var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); + possibleSearchDirs.add(projectRootPath); + possibleSearchDirs.forEach(function (searchDir) { + getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); + getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); + }); + } if (!typeAcquisition.disableFilenameBasedTypeAcquisition) { getTypingNamesFromSourceFileNames(fileNames); } @@ -127051,6 +129252,8 @@ var ts; case 256 /* SyntaxKind.FunctionDeclaration */: case 213 /* SyntaxKind.FunctionExpression */: return getAdjustedLocationForFunction(node); + case 171 /* SyntaxKind.Constructor */: + return node; } } if (ts.isNamedDeclaration(node)) { @@ -127139,7 +129342,7 @@ var ts; // // NOTE: If the node is a modifier, we don't adjust its location if it is the `default` modifier as that is handled // specially by `getSymbolAtLocation`. - if (ts.isModifier(node) && (forRename || node.kind !== 88 /* SyntaxKind.DefaultKeyword */) ? ts.contains(parent.modifiers, node) : + if (ts.isModifier(node) && (forRename || node.kind !== 88 /* SyntaxKind.DefaultKeyword */) ? ts.canHaveModifiers(parent) && ts.contains(parent.modifiers, node) : node.kind === 84 /* SyntaxKind.ClassKeyword */ ? ts.isClassDeclaration(parent) || ts.isClassExpression(node) : node.kind === 98 /* SyntaxKind.FunctionKeyword */ ? ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(node) : node.kind === 118 /* SyntaxKind.InterfaceKeyword */ ? ts.isInterfaceDeclaration(parent) : @@ -127378,12 +129581,18 @@ var ts; // flag causes us to return the first node whose end position matches the position and which produces and acceptable token // kind. Meanwhile, if includePrecedingTokenAtEndPosition is unset, we look for the first node whose start is <= the // position and whose end is greater than the position. + // There are more sophisticated end tests later, but this one is very fast + // and allows us to skip a bunch of work + var end = children[middle].getEnd(); + if (end < position) { + return -1 /* Comparison.LessThan */; + } var start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { return 1 /* Comparison.GreaterThan */; } // first element whose start position is before the input and whose end position is after or equal to the input - if (nodeContainsPosition(children[middle])) { + if (nodeContainsPosition(children[middle], start, end)) { if (children[middle - 1]) { // we want the _first_ element that contains the position, so left-recur if the prior node also contains the position if (nodeContainsPosition(children[middle - 1])) { @@ -127415,13 +129624,16 @@ var ts; case "continue-outer": continue outer; } } - function nodeContainsPosition(node) { - var start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true); + function nodeContainsPosition(node, start, end) { + end !== null && end !== void 0 ? end : (end = node.getEnd()); + if (end < position) { + return false; + } + start !== null && start !== void 0 ? start : (start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true)); if (start > position) { // If this child begins after position, then all subsequent children will as well. return false; } - var end = node.getEnd(); if (position < end || (position === end && (node.kind === 1 /* SyntaxKind.EndOfFileToken */ || includeEndPosition))) { return true; } @@ -128119,7 +130331,6 @@ var ts; ts.makeImportIfNecessary = makeImportIfNecessary; function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) { return ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, defaultImport || namedImports ? ts.factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? ts.factory.createNamedImports(namedImports) : undefined) : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier, @@ -128209,7 +130420,7 @@ var ts; node.getEnd() <= ts.textSpanEnd(span); } function findModifier(node, kind) { - return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + return ts.canHaveModifiers(node) ? ts.find(node.modifiers, function (m) { return m.kind === kind; }) : undefined; } ts.findModifier = findModifier; function insertImports(changes, sourceFile, imports, blankLineBetween) { @@ -128288,6 +130499,41 @@ var ts; return true; } ts.isTextWhiteSpaceLike = isTextWhiteSpaceLike; + function getMappedLocation(location, sourceMapper, fileExists) { + var mapsTo = sourceMapper.tryGetSourcePosition(location); + return mapsTo && (!fileExists || fileExists(ts.normalizePath(mapsTo.fileName)) ? mapsTo : undefined); + } + ts.getMappedLocation = getMappedLocation; + function getMappedDocumentSpan(documentSpan, sourceMapper, fileExists) { + var fileName = documentSpan.fileName, textSpan = documentSpan.textSpan; + var newPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start }, sourceMapper, fileExists); + if (!newPosition) + return undefined; + var newEndPosition = getMappedLocation({ fileName: fileName, pos: textSpan.start + textSpan.length }, sourceMapper, fileExists); + var newLength = newEndPosition + ? newEndPosition.pos - newPosition.pos + : textSpan.length; // This shouldn't happen + return { + fileName: newPosition.fileName, + textSpan: { + start: newPosition.pos, + length: newLength, + }, + originalFileName: documentSpan.fileName, + originalTextSpan: documentSpan.textSpan, + contextSpan: getMappedContextSpan(documentSpan, sourceMapper, fileExists), + originalContextSpan: documentSpan.contextSpan + }; + } + ts.getMappedDocumentSpan = getMappedDocumentSpan; + function getMappedContextSpan(documentSpan, sourceMapper, fileExists) { + var contextSpanStart = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, sourceMapper, fileExists); + var contextSpanEnd = documentSpan.contextSpan && getMappedLocation({ fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length }, sourceMapper, fileExists); + return contextSpanStart && contextSpanEnd ? + { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : + undefined; + } + ts.getMappedContextSpan = getMappedContextSpan; // #endregion // Display-part writer helpers // #region @@ -128781,7 +131027,7 @@ var ts; for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { var change = textChanges_1[_b]; var span = change.span, newText = change.newText; - var index = indexInTextChange(newText, name); + var index = indexInTextChange(newText, ts.escapeString(name)); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. @@ -129749,32 +131995,41 @@ var ts; || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } - function forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, cb) { + function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { var _a, _b; - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var excludePatterns = preferences.autoImportFileExcludePatterns && ts.mapDefined(preferences.autoImportFileExcludePatterns, function (spec) { + // The client is expected to send rooted path specs since we don't know + // what directory a relative path is relative to. + var pattern = ts.getPatternFromSpec(spec, "", "exclude"); + return pattern ? ts.getRegexFromPattern(pattern, useCaseSensitiveFileNames) : undefined; + }); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); var autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)); if (autoImportProvider) { var start = ts.timestamp(); - forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); + forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: ".concat(ts.timestamp() - start)); } } ts.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModule(checker, allSourceFiles, cb) { - for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { - var ambient = _a[_i]; - if (!ts.stringContains(ambient.name, "*")) { + function forEachExternalModule(checker, allSourceFiles, excludePatterns, cb) { + var _a; + var isExcluded = function (fileName) { return excludePatterns === null || excludePatterns === void 0 ? void 0 : excludePatterns.some(function (p) { return p.test(fileName); }); }; + for (var _i = 0, _b = checker.getAmbientModules(); _i < _b.length; _i++) { + var ambient = _b[_i]; + if (!ts.stringContains(ambient.name, "*") && !(excludePatterns && ((_a = ambient.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return isExcluded(d.getSourceFile().fileName); })))) { cb(ambient, /*sourceFile*/ undefined); } } - for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { - var sourceFile = allSourceFiles_1[_b]; - if (ts.isExternalOrCommonJsModule(sourceFile)) { + for (var _c = 0, allSourceFiles_1 = allSourceFiles; _c < allSourceFiles_1.length; _c++) { + var sourceFile = allSourceFiles_1[_c]; + if (ts.isExternalOrCommonJsModule(sourceFile) && !isExcluded(sourceFile.fileName)) { cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } } } - function getExportInfoMap(importingFile, host, program, cancellationToken) { + function getExportInfoMap(importingFile, host, program, preferences, cancellationToken) { var _a, _b, _c, _d, _e; var start = ts.timestamp(); // Pulling the AutoImportProvider project will trigger its updateGraph if pending, @@ -129794,7 +132049,7 @@ var ts; var compilerOptions = program.getCompilerOptions(); var moduleCount = 0; try { - forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { + forEachExternalModuleToImportFrom(program, host, preferences, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { if (++moduleCount % 100 === 0) cancellationToken === null || cancellationToken === void 0 ? void 0 : cancellationToken.throwIfCancellationRequested(); var seenExports = new ts.Map(); @@ -131135,6 +133390,26 @@ var ts; (function (Completions) { var StringCompletions; (function (StringCompletions) { + var _a; + var kindPrecedence = (_a = {}, + _a["directory" /* ScriptElementKind.directory */] = 0, + _a["script" /* ScriptElementKind.scriptElement */] = 1, + _a["external module name" /* ScriptElementKind.externalModuleName */] = 2, + _a); + function createNameAndKindSet() { + var map = new ts.Map(); + function add(value) { + var existing = map.get(value.name); + if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value.kind]) { + map.set(value.name, value); + } + } + return { + add: add, + has: map.has.bind(map), + values: map.values.bind(map), + }; + } function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); @@ -131238,11 +133513,11 @@ var ts; var parent = walkUpParentheses(node.parent); switch (parent.kind) { case 196 /* SyntaxKind.LiteralType */: { - var grandParent = walkUpParentheses(parent.parent); - switch (grandParent.kind) { + var grandParent_1 = walkUpParentheses(parent.parent); + switch (grandParent_1.kind) { + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: case 178 /* SyntaxKind.TypeReference */: { - var typeReference_1 = grandParent; - var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === typeReference_1; }); + var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === grandParent_1; }); if (typeArgument) { return { kind: 2 /* StringLiteralCompletionKind.Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), isNewIdentifier: false }; } @@ -131255,7 +133530,7 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - var _a = grandParent, indexType = _a.indexType, objectType = _a.objectType; + var _a = grandParent_1, indexType = _a.indexType, objectType = _a.objectType; if (!ts.rangeContainsPosition(indexType, position)) { return undefined; } @@ -131263,11 +133538,11 @@ var ts; case 200 /* SyntaxKind.ImportType */: return { kind: 0 /* StringLiteralCompletionKind.Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; case 187 /* SyntaxKind.UnionType */: { - if (!ts.isTypeReferenceNode(grandParent.parent)) { + if (!ts.isTypeReferenceNode(grandParent_1.parent)) { return undefined; } - var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent); - var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(grandParent_1, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(grandParent_1)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); return { kind: 2 /* StringLiteralCompletionKind.Types */, types: types, isNewIdentifier: false }; } default: @@ -131416,11 +133691,12 @@ var ts; } function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { var literalValue = ts.normalizeSlashes(node.text); + var mode = ts.isStringLiteralLike(node) ? ts.getModeForUsageLocation(sourceFile, node) : undefined; var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, getIncludeExtensionOption()) - : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, compilerOptions, host, getIncludeExtensionOption(), typeChecker); function getIncludeExtensionOption() { var mode = ts.isStringLiteralLike(node) ? ts.getModeForUsageLocation(sourceFile, node) : undefined; return preferences.importModuleSpecifierEnding === "js" || mode === ts.ModuleKind.ESNext ? 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */ : 0 /* IncludeExtensionsOption.Exclude */; @@ -131436,7 +133712,7 @@ var ts; return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + return ts.arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath).values()); } } function isEmitResolutionKindUsingNodeModules(compilerOptions) { @@ -131472,7 +133748,7 @@ var ts; var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); - return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); }); + return ts.flatMap(baseDirectories, function (baseDirectory) { return ts.arrayFrom(getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude).values()); }); } var IncludeExtensionsOption; (function (IncludeExtensionsOption) { @@ -131483,9 +133759,9 @@ var ts; /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) { - var extensions = _a.extensions, includeExtensionsOption = _a.includeExtensionsOption; - if (result === void 0) { result = []; } + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensionOptions, host, exclude, result) { + var _a; + if (result === void 0) { result = createNameAndKindSet(); } if (fragment === undefined) { fragment = ""; } @@ -131501,92 +133777,124 @@ var ts; fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths var absolutePath = ts.resolvePath(scriptPath, fragment); var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); + // check for a version redirect + var packageJsonPath = ts.findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionPaths = (_a = ts.getPackageJsonTypesVersionsPaths(typesVersions)) === null || _a === void 0 ? void 0 : _a.paths; + if (versionPaths) { + var packageDirectory = ts.getDirectoryPath(packageJsonPath); + var pathInPackage = absolutePath.slice(ts.ensureTrailingDirectorySeparator(packageDirectory).length); + if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, host, versionPaths)) { + // A true result means one of the `versionPaths` was matched, which will block relative resolution + // to files and folders from here. All reachable paths given the pattern match are already added. + return result; + } + } + } + } var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (!ts.tryDirectoryExists(host, baseDirectory)) return result; // Enumerate the available files if possible - var files = ts.tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + var files = ts.tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensionsOption === includeExtensionsOption.Exclude) so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - var foundFiles = new ts.Map(); // maps file to its extension for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { var filePath = files_1[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* Comparison.EqualTo */) { continue; } - var foundFileName = void 0; - var outputExtension = ts.moduleSpecifiers.tryGetJSExtensionForFile(filePath, host.getCompilationSettings()); - if (includeExtensionsOption === 0 /* IncludeExtensionsOption.Exclude */ && !ts.fileExtensionIsOneOf(filePath, [".json" /* Extension.Json */, ".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */])) { - foundFileName = ts.removeFileExtension(ts.getBaseFileName(filePath)); - foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); - } - else if ((ts.fileExtensionIsOneOf(filePath, [".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */]) || includeExtensionsOption === 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */) && outputExtension) { - foundFileName = ts.changeExtension(ts.getBaseFileName(filePath), outputExtension); - foundFiles.set(foundFileName, outputExtension); - } - else { - foundFileName = ts.getBaseFileName(filePath); - foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath)); - } + var _b = getFilenameWithExtensionOption(ts.getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions.includeExtensionsOption), name = _b.name, extension = _b.extension; + result.add(nameAndKind(name, "script" /* ScriptElementKind.scriptElement */, extension)); } - foundFiles.forEach(function (ext, foundFile) { - result.push(nameAndKind(foundFile, "script" /* ScriptElementKind.scriptElement */, ext)); - }); } // If possible, get folder completion as well var directories = ts.tryGetDirectories(host, baseDirectory); if (directories) { - for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { - var directory = directories_1[_b]; + for (var _c = 0, directories_1 = directories; _c < directories_1.length; _c++) { + var directory = directories_1[_c]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); if (directoryName !== "@types") { - result.push(directoryResult(directoryName)); - } - } - } - // check for a version redirect - var packageJsonPath = ts.findPackageJson(baseDirectory, host); - if (packageJsonPath) { - var packageJson = ts.readJson(packageJsonPath, host); - var typesVersions = packageJson.typesVersions; - if (typeof typesVersions === "object") { - var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); - var versionPaths = versionResult && versionResult.paths; - var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); - if (versionPaths) { - addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + result.add(directoryResult(directoryName)); } } } return result; } - function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { - for (var path in paths) { - if (!ts.hasProperty(paths, path)) + function getFilenameWithExtensionOption(name, compilerOptions, includeExtensionsOption) { + var outputExtension = ts.moduleSpecifiers.tryGetJSExtensionForFile(name, compilerOptions); + if (includeExtensionsOption === 0 /* IncludeExtensionsOption.Exclude */ && !ts.fileExtensionIsOneOf(name, [".json" /* Extension.Json */, ".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */])) { + return { name: ts.removeFileExtension(name), extension: ts.tryGetExtensionFromPath(name) }; + } + else if ((ts.fileExtensionIsOneOf(name, [".mts" /* Extension.Mts */, ".cts" /* Extension.Cts */, ".d.mts" /* Extension.Dmts */, ".d.cts" /* Extension.Dcts */, ".mjs" /* Extension.Mjs */, ".cjs" /* Extension.Cjs */]) || includeExtensionsOption === 2 /* IncludeExtensionsOption.ModuleSpecifierCompletion */) && outputExtension) { + return { name: ts.changeExtension(name, outputExtension), extension: outputExtension }; + } + else { + return { name: name, extension: ts.tryGetExtensionFromPath(name) }; + } + } + /** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */ + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, host, paths) { + var getPatternsForKey = function (key) { return paths[key]; }; + var comparePaths = function (a, b) { + var patternA = ts.tryParsePattern(a); + var patternB = ts.tryParsePattern(b); + var lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length; + var lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length; + return ts.compareValues(lengthB, lengthA); + }; + return addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, ts.getOwnKeys(paths), getPatternsForKey, comparePaths); + } + /** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */ + function addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, keys, getPatternsForKey, comparePaths) { + var pathResults = []; + var matchedPath; + for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { + var key = keys_1[_i]; + if (key === ".") continue; - var patterns = paths[path]; + var keyWithoutLeadingDotSlash = key.replace(/^\.\//, ""); // remove leading "./" + var patterns = getPatternsForKey(key); if (patterns) { - var _loop_3 = function (name, kind, extension) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind, extension)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_3(name, kind, extension); + var pathPattern = ts.tryParsePattern(keyWithoutLeadingDotSlash); + if (!pathPattern) + continue; + var isMatch = typeof pathPattern === "object" && ts.isPatternMatch(pathPattern, fragment); + var isLongestMatch = isMatch && (matchedPath === undefined || comparePaths(key, matchedPath) === -1 /* Comparison.LessThan */); + if (isLongestMatch) { + // If this is a higher priority match than anything we've seen so far, previous results from matches are invalid, e.g. + // for `import {} from "some-package/|"` with a typesVersions: + // { + // "bar/*": ["bar/*"], // <-- 1. We add 'bar', but 'bar/*' doesn't match yet. + // "*": ["dist/*"], // <-- 2. We match here and add files from dist. 'bar' is still ok because it didn't come from a match. + // "foo/*": ["foo/*"] // <-- 3. We matched '*' earlier and added results from dist, but if 'foo/*' also matched, + // } results in dist would not be visible. 'bar' still stands because it didn't come from a match. + // This is especially important if `dist/foo` is a folder, because if we fail to clear results + // added by the '*' match, after typing `"some-package/foo/|"` we would get file results from both + // ./dist/foo and ./foo, when only the latter will actually be resolvable. + // See pathCompletionsTypesVersionsWildcard6.ts. + matchedPath = key; + pathResults = pathResults.filter(function (r) { return !r.matchedPattern; }); + } + if (typeof pathPattern === "string" || matchedPath === undefined || comparePaths(key, matchedPath) !== 1 /* Comparison.GreaterThan */) { + pathResults.push({ + matchedPattern: isMatch, + results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host) + .map(function (_a) { + var name = _a.name, kind = _a.kind, extension = _a.extension; + return nameAndKind(name, kind, extension); + }), + }); } } } + pathResults.forEach(function (pathResult) { return pathResult.results.forEach(function (r) { return result.add(r); }); }); + return matchedPath !== undefined; } /** * Check all of the declared modules and those in node modules. Possible sources of modules: @@ -131595,22 +133903,22 @@ var ts; * Modules from node_modules (i.e. those listed in package.json) * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions */ - function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, compilerOptions, host, includeExtensionsOption, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; - var result = []; - var extensionOptions = getExtensionOptions(compilerOptions); + var result = createNameAndKindSet(); + var extensionOptions = getExtensionOptions(compilerOptions, includeExtensionsOption); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); if (paths) { - addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, host, paths); } } var fragmentDirectory = getFragmentDirectory(fragment); for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { var ambientName = _a[_i]; - result.push(nameAndKind(ambientName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); + result.add(nameAndKind(ambientName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (isEmitResolutionKindUsingNodeModules(compilerOptions)) { @@ -131618,15 +133926,13 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_4 = function (moduleName) { - if (!result.some(function (entry) { return entry.name === moduleName; })) { - foundGlobal = true; - result.push(nameAndKind(moduleName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); - } - }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_4(moduleName); + var moduleResult = nameAndKind(moduleName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined); + if (!result.has(moduleResult.name)) { + foundGlobal = true; + result.add(moduleResult); + } } } if (!foundGlobal) { @@ -131652,39 +133958,19 @@ var ts; } packagePath = ts.combinePaths(packagePath, subName); } - var packageFile = ts.combinePaths(ancestor, "node_modules", packagePath, "package.json"); + var packageDirectory = ts.combinePaths(ancestor, "node_modules", packagePath); + var packageFile = ts.combinePaths(packageDirectory, "package.json"); if (ts.tryFileExists(host, packageFile)) { var packageJson = ts.readJson(packageFile, host); - var exports = packageJson.exports; - if (exports) { - if (typeof exports !== "object" || exports === null) { // eslint-disable-line no-null/no-null + var exports_1 = packageJson.exports; + if (exports_1) { + if (typeof exports_1 !== "object" || exports_1 === null) { // eslint-disable-line no-null/no-null return; // null exports or entrypoint only, no sub-modules available } - var keys = ts.getOwnKeys(exports); - var fragmentSubpath_1 = components.join("/"); - var processedKeys = ts.mapDefined(keys, function (k) { - if (k === ".") - return undefined; - if (!ts.startsWith(k, "./")) - return undefined; - var subpath = k.substring(2); - if (!ts.startsWith(subpath, fragmentSubpath_1)) - return undefined; - // subpath is a valid export (barring conditions, which we don't currently check here) - if (!ts.stringContains(subpath, "*")) { - return subpath; - } - // pattern export - only return everything up to the `*`, so the user can autocomplete, then - // keep filling in the pattern (we could speculatively return a list of options by hitting disk, - // but conditions will make that somewhat awkward, as each condition may have a different set of possible - // options for the `*`. - return subpath.slice(0, subpath.indexOf("*")); - }); - ts.forEach(processedKeys, function (k) { - if (k) { - result.push(nameAndKind(k, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); - } - }); + var keys = ts.getOwnKeys(exports_1); + var fragmentSubpath = components.join("/") + (components.length && ts.hasTrailingDirectorySeparator(fragment) ? "/" : ""); + var conditions_1 = mode === ts.ModuleKind.ESNext ? ["node", "import", "types"] : ["node", "require", "types"]; + addCompletionEntriesFromPathsOrExports(result, fragmentSubpath, packageDirectory, extensionOptions, host, keys, function (key) { return ts.singleElementArray(getPatternFromFirstMatchingCondition(exports_1[key], conditions_1)); }, ts.comparePatternKeys); return; } } @@ -131694,26 +133980,44 @@ var ts; ts.forEachAncestorDirectory(scriptPath, ancestorLookup); } } - return result; + return ts.arrayFrom(result.values()); + } + function getPatternFromFirstMatchingCondition(target, conditions) { + if (typeof target === "string") { + return target; + } + if (target && typeof target === "object" && !ts.isArray(target)) { + for (var condition in target) { + if (condition === "default" || conditions.indexOf(condition) > -1 || ts.isApplicableVersionedTypesKey(conditions, condition)) { + var pattern = target[condition]; + return getPatternFromFirstMatchingCondition(pattern, conditions); + } + } + } } function getFragmentDirectory(fragment) { return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; } - function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; + return !ts.stringContains(path, "*") ? justPathMappingName(path, "script" /* ScriptElementKind.scriptElement */) : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); - return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { - return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); - }); - function justPathMappingName(name) { - return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray; + if (remainingFragment === undefined) { + var starIsFullPathComponent = path[path.length - 2] === "/"; + return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* ScriptElementKind.directory */) : ts.flatMap(patterns, function (pattern) { var _a; return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)) === null || _a === void 0 ? void 0 : _a.map(function (_a) { + var name = _a.name, rest = __rest(_a, ["name"]); + return (__assign({ name: pathPrefix + name }, rest)); + }); }); + } + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host); }); + function justPathMappingName(name, kind) { + return ts.startsWith(name, fragment) ? [{ name: ts.removeTrailingDirectorySeparator(name), kind: kind, extension: undefined }] : ts.emptyArray; } } - function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, host) { if (!host.readDirectory) { return undefined; } @@ -131732,21 +134036,33 @@ var ts; var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". - var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var baseDirectory = ts.normalizePath(ts.combinePaths(packageDirectory, expandedPrefixDirectory)); var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) { - var extension = ts.tryGetExtensionFromPath(match); - var name = trimPrefixAndSuffix(match); - return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* ScriptElementKind.scriptElement */, extension); - }); - var directories = ts.mapDefined(ts.tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) { - var name = trimPrefixAndSuffix(dir); - return name === undefined ? undefined : directoryResult(name); + // If we have a suffix, then we read the directory all the way down to avoid returning completions for + // directories that don't contain files that would match the suffix. A previous comment here was concerned + // about the case where `normalizedSuffix` includes a `?` character, which should be interpreted literally, + // but will match any single character as part of the `include` pattern in `tryReadDirectory`. This is not + // a problem, because (in the extremely unusual circumstance where the suffix has a `?` in it) a `?` + // interpreted as "any character" can only return *too many* results as compared to the literal + // interpretation, so we can filter those superfluous results out via `trimPrefixAndSuffix` as we've always + // done. + var includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*"; + var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, [includeGlob]), function (match) { + var trimmedWithPattern = trimPrefixAndSuffix(match); + if (trimmedWithPattern) { + if (containsSlash(trimmedWithPattern)) { + return directoryResult(ts.getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); + } + var _a = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions.includeExtensionsOption), name = _a.name, extension = _a.extension; + return nameAndKind(name, "script" /* ScriptElementKind.scriptElement */, extension); + } }); + // If we had a suffix, we already recursively searched for all possible files that could match + // it and returned the directories leading to those files. Otherwise, assume any directory could + // have something valid to import. + var directories = normalizedSuffix + ? ts.emptyArray + : ts.mapDefined(ts.tryGetDirectories(host, baseDirectory), function (dir) { return dir === "node_modules" ? undefined : directoryResult(dir); }); return __spreadArray(__spreadArray([], matches, true), directories, true); function trimPrefixAndSuffix(path) { var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix); @@ -131789,10 +134105,10 @@ var ts; var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, 1 /* IncludeExtensionsOption.Include */), host, sourceFile.path) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) : ts.Debug.fail(); - return addReplacementSpans(toComplete, range.pos + prefix.length, names); + return addReplacementSpans(toComplete, range.pos + prefix.length, ts.arrayFrom(names.values())); } function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) { - if (result === void 0) { result = []; } + if (result === void 0) { result = createNameAndKindSet(); } // Check for typings specified in compiler options var seen = new ts.Map(); var typeRoots = ts.tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; @@ -131817,7 +134133,7 @@ var ts; continue; if (fragmentDirectory === undefined) { if (!seen.has(packageName)) { - result.push(nameAndKind(packageName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); + result.add(nameAndKind(packageName, "external module name" /* ScriptElementKind.externalModuleName */, /*extension*/ undefined)); seen.set(packageName, true); } } @@ -132013,10 +134329,9 @@ var ts; GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; })(GlobalsSearch || (GlobalsSearch = {})); - function resolvingModuleSpecifiers(logPrefix, host, program, sourceFile, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { + function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { var _a, _b, _c; var start = ts.timestamp(); - var packageJsonImportFilter = ts.createPackageJsonImportFilter(sourceFile, preferences, host); // Under `--moduleResolution nodenext`, we have to resolve module specifiers up front, because // package.json exports can mean we *can't* resolve a module specifier (that doesn't include a // relative path into node_modules), and we want to filter those completions out entirely. @@ -132041,7 +134356,7 @@ var ts; return result; function tryResolve(exportInfo, symbolName, isFromAmbientModule) { if (isFromAmbientModule) { - var result_1 = ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, sourceFile, program, host, preferences); + var result_1 = resolver.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite); if (result_1) { ambientCount++; } @@ -132050,7 +134365,7 @@ var ts; var shouldResolveModuleSpecifier = needsFullResolution || preferences.allowIncompleteCompletions && resolvedCount < Completions.moduleSpecifierResolutionLimit; var shouldGetModuleSpecifierFromCache = !shouldResolveModuleSpecifier && preferences.allowIncompleteCompletions && cacheAttemptCount < Completions.moduleSpecifierResolutionCacheAttemptLimit; var result = (shouldResolveModuleSpecifier || shouldGetModuleSpecifierFromCache) - ? ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, sourceFile, program, host, preferences, packageJsonImportFilter, shouldGetModuleSpecifierFromCache) + ? resolver.getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, shouldGetModuleSpecifierFromCache) : undefined; if (!shouldResolveModuleSpecifier && !shouldGetModuleSpecifierFromCache || shouldGetModuleSpecifierFromCache && !result) { skippedAny = true; @@ -132154,8 +134469,8 @@ var ts; if (!previousResponse) return undefined; var lowerCaseTokenText = location.text.toLowerCase(); - var exportMap = ts.getExportInfoMap(file, host, program, cancellationToken); - var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, program, file, location.getStart(), preferences, + var exportMap = ts.getExportInfoMap(file, host, program, preferences, cancellationToken); + var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, ts.codefix.createImportSpecifierResolver(file, program, host, preferences), program, location.getStart(), preferences, /*isForImportStatementCompletion*/ false, ts.isValidTypeOnlyAliasUseSite(location), function (context) { var entries = ts.mapDefined(previousResponse.entries, function (entry) { var _a; @@ -132239,37 +134554,36 @@ var ts; } } var entries = ts.createSortedArray(); - if (isUncheckedFile(sourceFile, compilerOptions)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); - getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); - } - else { - if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* KeywordCompletionFilters.None */) { - return undefined; - } - getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); + var isChecked = isCheckedFile(sourceFile, compilerOptions); + if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* KeywordCompletionFilters.None */) { + return undefined; } + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag); if (keywordFilters !== 0 /* KeywordCompletionFilters.None */) { - var entryNames_1 = new ts.Set(entries.map(function (e) { return e.name; })); for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; - if (isTypeOnlyLocation && ts.isTypeKeyword(ts.stringToToken(keywordEntry.name)) || !entryNames_1.has(keywordEntry.name)) { + if (isTypeOnlyLocation && ts.isTypeKeyword(ts.stringToToken(keywordEntry.name)) || !uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } } - var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); for (var _b = 0, _c = getContextualKeywords(contextToken, position); _b < _c.length; _b++) { var keywordEntry = _c[_b]; - if (!entryNames.has(keywordEntry.name)) { + if (!uniqueNames.has(keywordEntry.name)) { + uniqueNames.add(keywordEntry.name); ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } for (var _d = 0, literals_1 = literals; _d < literals_1.length; _d++) { var literal = literals_1[_d]; - ts.insertSorted(entries, createCompletionEntryForLiteral(sourceFile, preferences, literal), compareCompletionEntries, /*allowDuplicates*/ true); + var literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal); + uniqueNames.add(literalEntry.name); + ts.insertSorted(entries, literalEntry, compareCompletionEntries, /*allowDuplicates*/ true); + } + if (!isChecked) { + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); } return { flags: completionData.flags, @@ -132281,8 +134595,8 @@ var ts; entries: entries, }; } - function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + function isCheckedFile(sourceFile, compilerOptions) { + return !ts.isSourceFileJS(sourceFile) || !!ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -132651,7 +134965,7 @@ var ts; span = ts.createTextSpanFromNode(contextToken); } if (ts.isPropertyDeclaration(contextToken.parent)) { - modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers); + modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers) & 125951 /* ModifierFlags.Modifier */; span = ts.createTextSpanFromNode(contextToken.parent); } return { modifiers: modifiers, span: span }; @@ -132711,7 +135025,7 @@ var ts; var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var quotePreference = ts.getQuotePreference(sourceFile, preferences); - var builderFlags = quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : undefined; + var builderFlags = 33554432 /* NodeBuilderFlags.OmitThisParameter */ | (quotePreference === 0 /* QuotePreference.Single */ ? 268435456 /* NodeBuilderFlags.UseSingleQuotesForStringLiteralType */ : 0 /* NodeBuilderFlags.None */); switch (declaration.kind) { case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: @@ -132750,12 +135064,10 @@ var ts; } var parameters = typeNode.parameters.map(function (typedParam) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typedParam.dotDotDotToken, typedParam.name, typedParam.questionToken, /*type*/ undefined, typedParam.initializer); }); return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, @@ -133242,7 +135554,7 @@ var ts; } function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) { var typeChecker = program.getTypeChecker(); - var inUncheckedFile = isUncheckedFile(sourceFile, compilerOptions); + var inCheckedFile = isCheckedFile(sourceFile, compilerOptions); var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -133486,6 +135798,7 @@ var ts; var hasUnresolvedAutoImports = false; // This also gets mutated in nested-functions after the return var symbols = []; + var importSpecifierResolver; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; var seenPropertySymbols = new ts.Map(); @@ -133657,15 +135970,7 @@ var ts; isNewIdentifierLocation = true; } var propertyAccess = node.kind === 200 /* SyntaxKind.ImportType */ ? node : node.parent; - if (inUncheckedFile) { - // In javascript files, for union types, we don't just get the members that - // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part - // of the individual types to a higher status since we know what they are. - symbols.push.apply(symbols, ts.filter(getPropertiesForCompletion(type, typeChecker), function (s) { return typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s); })); - } - else { + if (inCheckedFile) { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) { @@ -133673,6 +135978,14 @@ var ts; } } } + else { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + symbols.push.apply(symbols, ts.filter(getPropertiesForCompletion(type, typeChecker), function (s) { return typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s); })); + } if (insertAwait && preferences.includeCompletionsWithInsertText) { var promiseType = typeChecker.getPromisedTypeOfPromise(type); if (promiseType) { @@ -133707,14 +136020,14 @@ var ts; } else { var fileName = ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? (_a = ts.getSourceFileOfModule(moduleSymbol)) === null || _a === void 0 ? void 0 : _a.fileName : undefined; - var moduleSpecifier = (ts.codefix.getModuleSpecifierForBestExportInfo([{ + var moduleSpecifier = ((importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo([{ exportKind: 0 /* ExportKind.Named */, moduleFileName: fileName, isFromPackageJson: false, moduleSymbol: moduleSymbol, symbol: firstAccessibleSymbol, targetFlags: ts.skipAlias(firstAccessibleSymbol, typeChecker).flags, - }], firstAccessibleSymbol.name, position, ts.isValidTypeOnlyAliasUseSite(location), sourceFile, program, host, preferences) || {}).moduleSpecifier; + }], firstAccessibleSymbol.name, position, ts.isValidTypeOnlyAliasUseSite(location)) || {}).moduleSpecifier; if (moduleSpecifier) { var origin = { kind: getNullableSymbolOriginInfoKind(6 /* SymbolOriginInfoKind.SymbolMemberExport */), @@ -133864,7 +136177,7 @@ var ts; } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 305 /* SyntaxKind.SourceFile */) { - var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); + var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false, ts.isClassLike(scopeNode.parent) ? scopeNode : undefined); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { var symbol = _a[_i]; @@ -133967,10 +136280,10 @@ var ts; previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); - var exportInfo = ts.getExportInfoMap(sourceFile, host, program, cancellationToken); + var exportInfo = ts.getExportInfoMap(sourceFile, host, program, preferences, cancellationToken); var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); - resolvingModuleSpecifiers("collectAutoImports", host, program, sourceFile, position, preferences, !!importCompletionNode, ts.isValidTypeOnlyAliasUseSite(location), function (context) { + resolvingModuleSpecifiers("collectAutoImports", host, importSpecifierResolver || (importSpecifierResolver = ts.codefix.createImportSpecifierResolver(sourceFile, program, host, preferences)), program, position, preferences, !!importCompletionNode, ts.isValidTypeOnlyAliasUseSite(location), function (context) { exportInfo.search(sourceFile.path, /*preferCapitalized*/ isRightOfOpenTag, function (symbolName, targetFlags) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) @@ -135067,6 +137380,7 @@ var ts; return kind === 131 /* SyntaxKind.AsyncKeyword */ || kind === 132 /* SyntaxKind.AwaitKeyword */ || kind === 127 /* SyntaxKind.AsKeyword */ + || kind === 152 /* SyntaxKind.TypeKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { @@ -135166,6 +137480,10 @@ var ts; } break; case 79 /* SyntaxKind.Identifier */: { + var originalKeywordKind = location.originalKeywordKind; + if (originalKeywordKind && ts.isKeyword(originalKeywordKind)) { + return undefined; + } // class c { public prop = c| } if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) { return undefined; @@ -135953,60 +138271,64 @@ var ts; } return settingsOrHost; } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings)); - return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions); } - function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind); + function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind, languageVersionOrOptions); } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings)); - return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind); + return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions); } - function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { - return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); + function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind, languageVersionOrOptions) { + return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version, /*acquiring*/ false, scriptKind, languageVersionOrOptions); } function getDocumentRegistryEntry(bucketEntry, scriptKind) { var entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(ts.Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:".concat(scriptKind, " and sourceFile.scriptKind: ").concat(entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind, ", !entry: ").concat(!entry)); return entry; } - function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version, acquiring, scriptKind) { + function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version, acquiring, scriptKind, languageVersionOrOptions) { var _a, _b, _c, _d; scriptKind = ts.ensureScriptKind(fileName, scriptKind); var compilationSettings = getCompilationSettings(compilationSettingsOrHost); var host = compilationSettingsOrHost === compilationSettings ? undefined : compilationSettingsOrHost; var scriptTarget = scriptKind === 6 /* ScriptKind.JSON */ ? 100 /* ScriptTarget.JSON */ : ts.getEmitScriptTarget(compilationSettings); - var sourceFileOptions = { - languageVersion: scriptTarget, - impliedNodeFormat: host && ts.getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getModuleResolutionCache) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(compilationSettings) - }; + var sourceFileOptions = typeof languageVersionOrOptions === "object" ? + languageVersionOrOptions : + { + languageVersion: scriptTarget, + impliedNodeFormat: host && ts.getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getModuleResolutionCache) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings), + setExternalModuleIndicator: ts.getSetExternalModuleIndicator(compilationSettings) + }; + sourceFileOptions.languageVersion = scriptTarget; var oldBucketCount = buckets.size; - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var keyWithMode = getDocumentRegistryBucketKeyWithMode(key, sourceFileOptions.impliedNodeFormat); + var bucket = ts.getOrUpdate(buckets, keyWithMode, function () { return new ts.Map(); }); if (ts.tracing) { if (buckets.size > oldBucketCount) { // It is interesting, but not definitively problematic if a build requires multiple document registry buckets - // perhaps they are for two projects that don't have any overlap. // Bonus: these events can help us interpret the more interesting event below. - ts.tracing.instant("session" /* tracing.Phase.Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: key }); + ts.tracing.instant("session" /* tracing.Phase.Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: keyWithMode }); } // It is fairly suspicious to have one path in two buckets - you'd expect dependencies to have similar configurations. // If this occurs unexpectedly, the fix is likely to synchronize the project settings. // Skip .d.ts files to reduce noise (should also cover most of node_modules). var otherBucketKey = !ts.isDeclarationFileName(path) && - ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== key && bucket.has(path) && bucketKey; }); + ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== keyWithMode && bucket.has(path) && bucketKey; }); if (otherBucketKey) { - ts.tracing.instant("session" /* tracing.Phase.Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: key }); + ts.tracing.instant("session" /* tracing.Phase.Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: keyWithMode }); } } var bucketEntry = bucket.get(path); var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { - var sourceFile = externalCache.getDocument(key, path); + var sourceFile = externalCache.getDocument(keyWithMode, path); if (sourceFile) { ts.Debug.assert(acquiring); entry = { @@ -136020,7 +138342,7 @@ var ts; // Have never seen this file with these settings. Create a new source file for it. var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, sourceFileOptions, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { - externalCache.setDocument(key, path, sourceFile); + externalCache.setDocument(keyWithMode, path, sourceFile); } entry = { sourceFile: sourceFile, @@ -136035,7 +138357,7 @@ var ts; if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 if (externalCache) { - externalCache.setDocument(key, path, entry.sourceFile); + externalCache.setDocument(keyWithMode, path, entry.sourceFile); } } // If we're acquiring, then this is the first time this LS is asking for this document. @@ -136064,13 +138386,13 @@ var ts; } } } - function releaseDocument(fileName, compilationSettings, scriptKind) { + function releaseDocument(fileName, compilationSettings, scriptKind, impliedNodeFormat) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key, scriptKind); + return releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat); } - function releaseDocumentWithKey(path, key, scriptKind) { - var bucket = ts.Debug.checkDefined(buckets.get(key)); + function releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat) { + var bucket = ts.Debug.checkDefined(buckets.get(getDocumentRegistryBucketKeyWithMode(key, impliedNodeFormat))); var bucketEntry = bucket.get(path); var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; @@ -136118,7 +138440,7 @@ var ts; } var str = "{"; for (var key in value) { - if (ts.hasOwnProperty.call(value, key)) { // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier + if (ts.hasProperty(value, key)) { str += "".concat(key, ": ").concat(compilerOptionValueToString(value[key])); } } @@ -136127,6 +138449,9 @@ var ts; function getKeyForCompilationSettings(settings) { return ts.sourceFileAffectingCompilerOptions.map(function (option) { return compilerOptionValueToString(ts.getCompilerOptionValue(settings, option)); }).join("|") + (settings.pathsBasePath ? "|".concat(settings.pathsBasePath) : undefined); } + function getDocumentRegistryBucketKeyWithMode(key, mode) { + return (mode ? "".concat(key, "|").concat(mode) : key); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -136259,7 +138584,7 @@ var ts; return ts.findAncestor(node, function (node) { if (stopAtAmbientModule && isAmbientModuleDeclaration(node)) return "quit"; - return ts.some(node.modifiers, function (mod) { return mod.kind === 93 /* SyntaxKind.ExportKeyword */; }); + return ts.canHaveModifiers(node) && ts.some(node.modifiers, ts.isExportModifier); }); } function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { @@ -136683,7 +139008,7 @@ var ts; ts.Debug.assert(parent.name === node); return true; case 203 /* SyntaxKind.BindingElement */: - return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent); + return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent.parent.parent); default: return false; } @@ -136942,18 +139267,18 @@ var ts; || node.kind === 106 /* SyntaxKind.SuperKeyword */) { referenceEntries = entries && __spreadArray([], entries, true); } - else { - var queue = entries && __spreadArray([], entries, true); + else if (entries) { + var queue = ts.createQueue(entries); var seenNodes = new ts.Map(); - while (queue && queue.length) { - var entry = queue.shift(); + while (!queue.isEmpty()) { + var entry = queue.dequeue(); if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) { continue; } referenceEntries = ts.append(referenceEntries, entry); var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); if (entries_1) { - queue.push.apply(queue, entries_1); + queue.enqueue.apply(queue, entries_1); } } } @@ -137209,6 +139534,7 @@ var ts; var commonjsSource = source && ts.isBinaryExpression(source) ? source.left : undefined; return !!(source && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === source || d === commonjsSource; }))); } + FindAllReferences.isDeclarationOfSymbol = isDeclarationOfSymbol; /** * True if 'decl' provides a value, as in `function f() {}`; * false if 'decl' is just a location for a future write, as in 'let x;' @@ -137415,7 +139741,7 @@ var ts; result = references; continue; } - var _loop_5 = function (entry) { + var _loop_3 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* DefinitionKind.Symbol */) { result.push(entry); return "continue"; @@ -137447,7 +139773,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_5(entry); + _loop_3(entry); } } return result; @@ -138148,7 +140474,7 @@ var ts; // Use the parent symbol if the location is commonjs require syntax on javascript files only. if (ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 203 /* SyntaxKind.BindingElement */ - && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent)) { + && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) { referenceSymbol = referenceLocation.parent.symbol; // The parent will not have a symbol if it's an ObjectBindingPattern (when destructuring is used). In // this case, just skip it, since the bound identifiers are not an alias of the import. @@ -139028,8 +141354,8 @@ var ts; var declarations; if (symbol && symbol.declarations) { var indices = ts.indicesOf(symbol.declarations); - var keys_1 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); }); - indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_1[a].file, keys_1[b].file) || keys_1[a].pos - keys_1[b].pos; }); + var keys_2 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); }); + indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_2[a].file, keys_2[b].file) || keys_2[a].pos - keys_2[b].pos; }); var sortedDeclarations = ts.map(indices, function (i) { return symbol.declarations[i]; }); var lastDecl = void 0; for (var _i = 0, sortedDeclarations_1 = sortedDeclarations; _i < sortedDeclarations_1.length; _i++) { @@ -139299,14 +141625,16 @@ var ts; collect(node.body); } function collectCallSitesOfClassLikeDeclaration(node, collect) { - ts.forEach(node.decorators, collect); + ts.forEach(node.modifiers, collect); var heritage = ts.getClassExtendsHeritageElement(node); if (heritage) { collect(heritage.expression); } for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - ts.forEach(member.decorators, collect); + if (ts.canHaveModifiers(member)) { + ts.forEach(member.modifiers, collect); + } if (ts.isPropertyDeclaration(member)) { collect(member.initializer); } @@ -139475,7 +141803,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_6 = function (sourceFile) { + var _loop_4 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -139507,7 +141835,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_6(sourceFile); + _loop_4(sourceFile); } } function combineNormal(pathA, pathB) { @@ -140149,11 +142477,12 @@ var ts; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var jsdoc = _a[_i]; + var inheritDoc = ts.isJSDoc(jsdoc) && jsdoc.tags && ts.find(jsdoc.tags, function (t) { return t.kind === 327 /* SyntaxKind.JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc"); }); // skip comments containing @typedefs since they're not associated with particular declarations // Exceptions: // - @typedefs are themselves declarations with associated comments // - @param or @return indicate that the author thinks of it as a 'local' @typedef that's part of the function documentation - if (jsdoc.comment === undefined + if (jsdoc.comment === undefined && !inheritDoc || ts.isJSDoc(jsdoc) && declaration.kind !== 345 /* SyntaxKind.JSDocTypedefTag */ && declaration.kind !== 338 /* SyntaxKind.JSDocCallbackTag */ && jsdoc.tags @@ -140161,7 +142490,10 @@ var ts; && !jsdoc.tags.some(function (t) { return t.kind === 340 /* SyntaxKind.JSDocParameterTag */ || t.kind === 341 /* SyntaxKind.JSDocReturnTag */; })) { continue; } - var newparts = getDisplayPartsFromComment(jsdoc.comment, checker); + var newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : []; + if (inheritDoc && inheritDoc.comment) { + newparts = newparts.concat(getDisplayPartsFromComment(inheritDoc.comment, checker)); + } if (!ts.contains(parts, newparts, isIdenticalListOfDisplayParts)) { parts.push(newparts); } @@ -140395,8 +142727,12 @@ var ts; return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters, hasReturn = commentOwnerInfo.hasReturn; - var commentOwnerJSDoc = ts.hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? ts.lastOrUndefined(commentOwner.jsDoc) : undefined; - if (commentOwner.getStart(sourceFile) < position || commentOwnerJSDoc && commentOwnerJSDoc !== existingDocComment) { + var commentOwnerJsDoc = ts.hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : undefined; + var lastJsDoc = ts.lastOrUndefined(commentOwnerJsDoc); + if (commentOwner.getStart(sourceFile) < position + || lastJsDoc + && existingDocComment + && lastJsDoc !== existingDocComment) { return undefined; } var indentationStr = getIndentationStringAtPosition(sourceFile, position); @@ -140413,7 +142749,9 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var openComment = "/**"; var closeComment = " */"; - if (tags) { + // If any of the existing jsDoc has tags, ignore adding new ones. + var hasTag = (commentOwnerJsDoc || []).some(function (jsDoc) { return !!jsDoc.tags; }); + if (tags && !hasTag) { var preamble = openComment + newLine + indentationStr + " * "; var endLine = tokenStart === position ? newLine + indentationStr : ""; var result = preamble + newLine + tags + indentationStr + closeComment + endLine; @@ -140527,7 +142865,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_7 = function (sourceFile) { + var _loop_5 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -140539,7 +142877,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_7(sourceFile); + _loop_5(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -141135,7 +143473,7 @@ var ts; isPossibleConstructor(b.node) ? b.node : undefined; if (ctorFunction !== undefined) { - var ctorNode = ts.setTextRange(ts.factory.createConstructorDeclaration(/* decorators */ undefined, /* modifiers */ undefined, [], /* body */ undefined), ctorFunction); + var ctorNode = ts.setTextRange(ts.factory.createConstructorDeclaration(/* modifiers */ undefined, [], /* body */ undefined), ctorFunction); var ctor = emptyNavigationBarNode(ctorNode); ctor.indent = a.indent + 1; ctor.children = a.node === ctorFunction ? a.children : b.children; @@ -141151,7 +143489,6 @@ var ts; } } lastANode = a.node = ts.setTextRange(ts.factory.createClassDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, a.name || ts.factory.createIdentifier("__class__"), /* typeParameters */ undefined, /* heritageClauses */ undefined, []), a.node); @@ -141176,7 +143513,6 @@ var ts; if (!a.additionalNodes) a.additionalNodes = []; a.additionalNodes.push(ts.setTextRange(ts.factory.createClassDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, a.name || ts.factory.createIdentifier("__class__"), /* typeParameters */ undefined, /* heritageClauses */ undefined, []), b.node)); @@ -141685,7 +144021,7 @@ var ts; else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) { // If we’re in a declaration file, it’s safe to remove the import clause from it if (sourceFile.isDeclarationFile) { - usedImports.push(ts.factory.createImportDeclaration(importDecl.decorators, importDecl.modifiers, + usedImports.push(ts.factory.createImportDeclaration(importDecl.modifiers, /*importClause*/ undefined, moduleSpecifier, /*assertClause*/ undefined)); } @@ -141851,7 +144187,7 @@ var ts; newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(exportGroup_1, function (i) { return i.exportClause && ts.isNamedExports(i.exportClause) ? i.exportClause.elements : ts.emptyArray; })); var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); var exportDecl = exportGroup_1[0]; - coalescedExports.push(ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ? + coalescedExports.push(ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ? ts.factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : ts.factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.assertClause)); } @@ -141888,7 +144224,7 @@ var ts; } OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 + return ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, ts.factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), // TODO: GH#18217 importDeclaration.moduleSpecifier, importDeclaration.assertClause); } function sortSpecifiers(specifiers) { @@ -142604,13 +144940,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_8 = function (start) { + var _loop_6 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_8(start); + var state_3 = _loop_6(start); if (typeof state_3 === "object") return state_3.value; } @@ -143196,10 +145532,10 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(program, sourceFile, position, options) { + function getRenameInfo(program, sourceFile, position, preferences) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, preferences); if (renameInfo) { return renameInfo; } @@ -143207,7 +145543,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, preferences) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -143235,7 +145571,12 @@ var ts; return undefined; } if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { - return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + return preferences.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; + } + // Disallow rename for elements that would rename across `*/node_modules/*` packages. + var wouldRenameNodeModules = wouldRenameInOtherNodeModules(sourceFile, symbol, typeChecker, preferences); + if (wouldRenameNodeModules) { + return getRenameInfoError(wouldRenameNodeModules); } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) @@ -143249,6 +145590,49 @@ var ts; var sourceFile = declaration.getSourceFile(); return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Extension.Dts */); } + function wouldRenameInOtherNodeModules(originalFile, symbol, checker, preferences) { + if (!preferences.providePrefixAndSuffixTextForRename && symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var importSpecifier = symbol.declarations && ts.find(symbol.declarations, function (decl) { return ts.isImportSpecifier(decl); }); + if (importSpecifier && !importSpecifier.propertyName) { + symbol = checker.getAliasedSymbol(symbol); + } + } + var declarations = symbol.declarations; + if (!declarations) { + return undefined; + } + var originalPackage = getPackagePathComponents(originalFile.path); + if (originalPackage === undefined) { // original source file is not in node_modules + if (ts.some(declarations, function (declaration) { return ts.isInsideNodeModules(declaration.getSourceFile().path); })) { + return ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder; + } + else { + return undefined; + } + } + // original source file is in node_modules + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + var declPackage = getPackagePathComponents(declaration.getSourceFile().path); + if (declPackage) { + var length_2 = Math.min(originalPackage.length, declPackage.length); + for (var i = 0; i <= length_2; i++) { + if (ts.compareStringsCaseSensitive(originalPackage[i], declPackage[i]) !== 0 /* Comparison.EqualTo */) { + return ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder; + } + } + } + } + return undefined; + } + function getPackagePathComponents(filePath) { + var components = ts.getPathComponents(filePath); + var nodeModulesIdx = components.lastIndexOf("node_modules"); + if (nodeModulesIdx === -1) { + return undefined; + } + return components.slice(0, nodeModulesIdx + 2); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); @@ -143319,7 +145703,7 @@ var ts; var SmartSelectionRange; (function (SmartSelectionRange) { function getSmartSelectionRange(pos, sourceFile) { - var _a; + var _a, _b; var selectionRange = { textSpan: ts.createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd()) }; @@ -143371,6 +145755,17 @@ var ts; if (ts.hasJSDocNodes(node) && ((_a = node.jsDoc) === null || _a === void 0 ? void 0 : _a.length)) { pushSelectionRange(ts.first(node.jsDoc).getStart(), end); } + // (#39618 & #49807) + // When the node is a SyntaxList and its first child has a JSDoc comment, then the node's + // `start` (which usually is the result of calling `node.getStart()`) points to the first + // token after the JSDoc comment. So, we have to make sure we'd pushed the selection + // covering the JSDoc comment before diving further. + if (ts.isSyntaxList(node)) { + var firstChild = node.getChildren()[0]; + if (firstChild && ts.hasJSDocNodes(firstChild) && ((_b = firstChild.jsDoc) === null || _b === void 0 ? void 0 : _b.length) && firstChild.getStart() !== node.pos) { + start = Math.min(start, ts.first(firstChild.jsDoc).getStart()); + } + } pushSelectionRange(start, end); // String literals should have a stop both inside and outside their quotes. if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) { @@ -143444,6 +145839,7 @@ var ts; * other as well as of other top-level statements and declarations. */ function getSelectionChildren(node) { + var _a; // Group top-level imports if (ts.isSourceFile(node)) { return groupChildren(node.getChildAt(0).getChildren(), isImport); @@ -143459,7 +145855,7 @@ var ts; // because it allows the mapped type to become an object type with a // few keystrokes. if (ts.isMappedTypeNode(node)) { - var _a = node.getChildren(), openBraceToken = _a[0], children = _a.slice(1); + var _b = node.getChildren(), openBraceToken = _b[0], children = _b.slice(1); var closeBraceToken = ts.Debug.checkDefined(children.pop()); ts.Debug.assertEqual(openBraceToken.kind, 18 /* SyntaxKind.OpenBraceToken */); ts.Debug.assertEqual(closeBraceToken.kind, 19 /* SyntaxKind.CloseBraceToken */); @@ -143490,10 +145886,13 @@ var ts; var children = groupChildren(node.getChildren(), function (child) { return child === node.name || ts.contains(node.modifiers, child); }); - return splitChildren(children, function (_a) { + var firstJSDocChild = ((_a = children[0]) === null || _a === void 0 ? void 0 : _a.kind) === 320 /* SyntaxKind.JSDoc */ ? children[0] : undefined; + var withJSDocSeparated = firstJSDocChild ? children.slice(1) : children; + var splittedChildren = splitChildren(withJSDocSeparated, function (_a) { var kind = _a.kind; return kind === 58 /* SyntaxKind.ColonToken */; }); + return firstJSDocChild ? [firstJSDocChild, createSyntaxList(splittedChildren)] : splittedChildren; } // Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`. if (ts.isParameter(node)) { @@ -144029,7 +146428,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_9 = function (n) { + var _loop_7 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: ".concat(ts.Debug.formatSyntaxKind(n.kind), ", parent: ").concat(ts.Debug.formatSyntaxKind(n.parent.kind)); }); @@ -144039,7 +146438,7 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_4 = _loop_9(n); + var state_4 = _loop_7(n); if (typeof state_4 === "object") return state_4.value; } @@ -144238,7 +146637,7 @@ var ts; if (!ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) { return; } - if (ts.isTypeNode(node)) { + if (ts.isTypeNode(node) && !ts.isExpressionWithTypeArguments(node)) { return; } if (preferences.includeInlayVariableTypeHints && ts.isVariableDeclaration(node)) { @@ -144303,7 +146702,7 @@ var ts; return type.symbol && (type.symbol.flags & 1536 /* SymbolFlags.Module */); } function visitVariableLikeDeclaration(decl) { - if (!decl.initializer || ts.isBindingPattern(decl.name)) { + if (!decl.initializer || ts.isBindingPattern(decl.name) || ts.isVariableDeclaration(decl) && !isHintableDeclaration(decl)) { return; } var effectiveTypeAnnotation = ts.getEffectiveTypeAnnotationNode(decl); @@ -144316,6 +146715,10 @@ var ts; } var typeDisplayString = printTypeInSingleLine(declarationType); if (typeDisplayString) { + var isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && ts.equateStringsCaseInsensitive(decl.name.getText(), typeDisplayString); + if (isVariableNameMatchesType) { + return; + } addTypeHints(typeDisplayString, decl.name.end); } } @@ -144427,6 +146830,9 @@ var ts; } for (var i = 0; i < node.parameters.length && i < signature.parameters.length; ++i) { var param = node.parameters[i]; + if (!isHintableDeclaration(param)) { + continue; + } var effectiveTypeAnnotation = ts.getEffectiveTypeAnnotationNode(param); if (effectiveTypeAnnotation) { continue; @@ -144468,6 +146874,13 @@ var ts; function isUndefined(name) { return name === "undefined"; } + function isHintableDeclaration(node) { + if ((ts.isParameterDeclaration(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) && node.initializer) { + var initializer = ts.skipParentheses(node.initializer); + return !(isHintableLiteral(initializer) || ts.isNewExpression(initializer) || ts.isObjectLiteralExpression(initializer) || ts.isAssertionExpression(initializer)); + } + return true; + } } InlayHints.provideInlayHints = provideInlayHints; })(InlayHints = ts.InlayHints || (ts.InlayHints = {})); @@ -145638,7 +148051,7 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_10 = function (opt) { + var _loop_8 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -145657,7 +148070,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_10(opt); + _loop_8(opt); } return options; } @@ -146607,7 +149020,7 @@ var ts; } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - !!context.contextNode.decorators && + ts.hasDecorators(context.contextNode) && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -147172,6 +149585,7 @@ var ts; var options = _a.options, getRules = _a.getRules, host = _a.host; // formatting context is used by rules provider var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); + var previousRangeTriviaEnd; var previousRange; var previousParent; var previousRangeStartLine; @@ -147182,7 +149596,7 @@ var ts; if (formattingScanner.isOnToken()) { var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; var undecoratedStartLine = startLine; - if (enclosingNode.decorators) { + if (ts.hasDecorators(enclosingNode)) { undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; } processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); @@ -147200,10 +149614,30 @@ var ts; } } if (previousRange && formattingScanner.getStartPos() >= originalRange.end) { + // Formatting edits happen by looking at pairs of contiguous tokens (see `processPair`), + // typically inserting or deleting whitespace between them. The recursive `processNode` + // logic above bails out as soon as it encounters a token that is beyond the end of the + // range we're supposed to format (or if we reach the end of the file). But this potentially + // leaves out an edit that would occur *inside* the requested range but cannot be discovered + // without looking at one token *beyond* the end of the range: consider the line `x = { }` + // with a selection from the beginning of the line to the space inside the curly braces, + // inclusive. We would expect a format-selection would delete the space (if rules apply), + // but in order to do that, we need to process the pair ["{", "}"], but we stopped processing + // just before getting there. This block handles this trailing edit. var tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : undefined; - if (tokenInfo) { + if (tokenInfo && tokenInfo.pos === previousRangeTriviaEnd) { + // We need to check that tokenInfo and previousRange are contiguous: the `originalRange` + // may have ended in the middle of a token, which means we will have stopped formatting + // on that token, leaving `previousRange` pointing to the token before it, but already + // having moved the formatting scanner (where we just got `tokenInfo`) to the next token. + // If this happens, our supposed pair [previousRange, tokenInfo] actually straddles the + // token that intersects the end of the range we're supposed to format, so the pair will + // produce bogus edits if we try to `processPair`. Recall that the point of this logic is + // to perform a trailing edit at the end of the selection range: but there can be no valid + // edit in the middle of a token where the range ended, so if we have a non-contiguous + // pair here, we're already done and we can ignore it. var parent = ((_b = ts.findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)) === null || _b === void 0 ? void 0 : _b.parent) || previousParent; processPair(tokenInfo, sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line, parent, previousRange, previousRangeStartLine, previousParent, parent, /*dynamicIndentation*/ undefined); @@ -147269,8 +149703,10 @@ var ts; } } function getFirstNonDecoratorTokenOfNode(node) { - if (node.modifiers && node.modifiers.length) { - return node.modifiers[0].kind; + if (ts.canHaveModifiers(node)) { + var modifier = ts.find(node.modifiers, ts.isModifier, ts.findIndex(node.modifiers, ts.isDecorator)); + if (modifier) + return modifier.kind; } switch (node.kind) { case 257 /* SyntaxKind.ClassDeclaration */: return 84 /* SyntaxKind.ClassKeyword */; @@ -147345,7 +149781,6 @@ var ts; case 280 /* SyntaxKind.JsxOpeningElement */: case 281 /* SyntaxKind.JsxClosingElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: - case 228 /* SyntaxKind.ExpressionWithTypeArguments */: return false; } break; @@ -147359,7 +149794,7 @@ var ts; // if token line equals to the line of containing node (this is a first token in the node) - use node indentation return nodeStartLine !== line // if this token is the first token following the list of decorators, we do not need to indent - && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + && !(ts.hasDecorators(node) && kind === getFirstNonDecoratorTokenOfNode(node)); } function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node @@ -147399,13 +149834,14 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { + ts.Debug.assert(!ts.nodeIsSynthesized(child)); if (ts.nodeIsMissing(child)) { return inheritedIndentation; } var childStartPos = child.getStart(sourceFile); var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; var undecoratedChildStartLine = childStartLine; - if (child.decorators) { + if (ts.hasDecorators(child)) { undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; } // if child is a list item - try to get its indentation, only if parent is within the original range. @@ -147465,6 +149901,7 @@ var ts; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); + ts.Debug.assert(!ts.nodeIsSynthesized(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; @@ -147515,12 +149952,10 @@ var ts; var listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== 0 /* SyntaxKind.Unknown */ && formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(parent); - if (tokenInfo.token.kind === 27 /* SyntaxKind.CommaToken */ && ts.isCallLikeExpression(parent)) { - var commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - if (startLine !== commaTokenLine) { - formattingScanner.advance(); - tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; - } + if (tokenInfo.token.kind === 27 /* SyntaxKind.CommaToken */) { + // consume the comma + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one @@ -147560,6 +149995,7 @@ var ts; } } if (currentTokenInfo.trailingTrivia) { + previousRangeTriviaEnd = ts.last(currentTokenInfo.trailingTrivia).end; processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); } if (indentToken) { @@ -147630,6 +150066,7 @@ var ts; } } previousRange = range; + previousRangeTriviaEnd = range.end; previousParent = parent; previousRangeStartLine = rangeStart.line; return lineAction; @@ -147921,6 +150358,12 @@ var ts; case 169 /* SyntaxKind.MethodDeclaration */: case 168 /* SyntaxKind.MethodSignature */: case 214 /* SyntaxKind.ArrowFunction */: + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: if (node.typeParameters === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -147937,7 +150380,19 @@ var ts; return 20 /* SyntaxKind.OpenParenToken */; } break; + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 258 /* SyntaxKind.InterfaceDeclaration */: + case 259 /* SyntaxKind.TypeAliasDeclaration */: + if (node.typeParameters === list) { + return 29 /* SyntaxKind.LessThanToken */; + } + break; case 178 /* SyntaxKind.TypeReference */: + case 210 /* SyntaxKind.TaggedTemplateExpression */: + case 181 /* SyntaxKind.TypeQuery */: + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + case 200 /* SyntaxKind.ImportType */: if (node.typeArguments === list) { return 29 /* SyntaxKind.LessThanToken */; } @@ -149201,7 +151656,7 @@ var ts; return { indentation: indentation, prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter, - suffix: insertTrailingComma ? "," : "" + suffix: insertTrailingComma ? "," : ts.isInterfaceDeclaration(node) && isEmpty ? ";" : "" }; }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -149405,7 +151860,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_11 = function (sourceFile, node) { + var _loop_9 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -149418,7 +151873,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_11(sourceFile, node); + _loop_9(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -149506,14 +151961,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_12 = function (i) { + var _loop_10 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return "".concat(JSON.stringify(normalized[i].range), " and ").concat(JSON.stringify(normalized[i + 1].range)); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_12(i); + _loop_10(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -150224,7 +152679,6 @@ var ts; var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { var exportDeclaration = ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([]), /*moduleSpecifier*/ undefined); @@ -150422,7 +152876,7 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_13 = function (identifier) { + var _loop_11 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; @@ -150455,7 +152909,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_13(identifier); + _loop_11(identifier); } return initializers && { initializers: initializers, @@ -150754,8 +153208,7 @@ var ts; ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); var typeNode = ts.factory.createTypeReferenceNode(param.name, /*typeArguments*/ undefined); - var replacement = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); + var replacement = ts.factory.createParameterDeclaration(param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); changeTracker.replaceNode(sourceFile, param, replacement); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -150980,7 +153433,7 @@ var ts; var isRest = node.type.kind === 318 /* SyntaxKind.JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : node.dotDotDotToken; - return ts.factory.createParameterDeclaration(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); + return ts.factory.createParameterDeclaration(node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); } function transformJSDocTypeReference(node) { var name = node.typeName; @@ -151015,12 +153468,11 @@ var ts; } function transformJSDocIndexSignature(node) { var index = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "n" : "s", /*questionToken*/ undefined, ts.factory.createTypeReferenceNode(node.typeArguments[0].kind === 147 /* SyntaxKind.NumberKeyword */ ? "number" : "string", []), /*initializer*/ undefined); - var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + var indexSignature = ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(/*modifiers*/ undefined, [index], node.typeArguments[1])]); ts.setEmitFlags(indexSignature, 1 /* EmitFlags.SingleLine */); return indexSignature; } @@ -151162,7 +153614,7 @@ var ts; ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { - members.push(ts.factory.createPropertyDeclaration([], modifiers, symbol.name, /*questionToken*/ undefined, + members.push(ts.factory.createPropertyDeclaration(modifiers, symbol.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); return; } @@ -151198,7 +153650,7 @@ var ts; return; if (!ts.isPropertyAccessExpression(memberDeclaration)) return; - var prop = ts.factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); + var prop = ts.factory.createPropertyDeclaration(modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); members.push(prop); return; @@ -151211,7 +153663,7 @@ var ts; } function createFunctionExpressionMember(members, functionExpression, name) { var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 131 /* SyntaxKind.AsyncKeyword */)); - var method = ts.factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); @@ -151229,7 +153681,7 @@ var ts; bodyBlock = ts.factory.createBlock([ts.factory.createReturnStatement(arrowFunctionBody)]); } var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 131 /* SyntaxKind.AsyncKeyword */)); - var method = ts.factory.createMethodDeclaration(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + var method = ts.factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); @@ -151243,10 +153695,10 @@ var ts; } var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { - memberElements.unshift(ts.factory.createConstructorDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); + memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, initializer.parameters, initializer.body)); } var modifiers = getModifierKindFromSource(node.parent.parent, 93 /* SyntaxKind.ExportKeyword */); - var cls = ts.factory.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + var cls = ts.factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; @@ -151254,17 +153706,17 @@ var ts; function createClassFromFunctionDeclaration(node) { var memberElements = createClassElementsFromSymbol(ctorSymbol); if (node.body) { - memberElements.unshift(ts.factory.createConstructorDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body)); + memberElements.unshift(ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, node.parameters, node.body)); } var modifiers = getModifierKindFromSource(node, 93 /* SyntaxKind.ExportKeyword */); - var cls = ts.factory.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, + var cls = ts.factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } } function getModifierKindFromSource(source, kind) { - return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); + return ts.canHaveModifiers(source) ? ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }) : undefined; } function isConstructorAssignment(x) { if (!x.name) @@ -151340,12 +153792,9 @@ var ts; if (!returnStatements.length) { return; } - var pos = functionToConvert.modifiers ? functionToConvert.modifiers.end : - functionToConvert.decorators ? ts.skipTrivia(sourceFile.text, functionToConvert.decorators.end) : - functionToConvert.getStart(sourceFile); - var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; - changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, options); - var _loop_14 = function (returnStatement) { + var pos = ts.skipTrivia(sourceFile.text, ts.moveRangePastModifiers(functionToConvert).pos); + changes.insertModifierAt(sourceFile, pos, 131 /* SyntaxKind.AsyncKeyword */, { suffix: " " }); + var _loop_12 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); @@ -151367,7 +153816,7 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - var state_5 = _loop_14(returnStatement); + var state_5 = _loop_12(returnStatement); if (typeof state_5 === "object") return state_5.value; } @@ -152470,12 +154919,10 @@ var ts; } // Node helpers function functionExpressionToDeclaration(name, additionalModifiers, fn, useSitesToUnqualify) { - return ts.factory.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); + return ts.factory.createFunctionDeclaration(ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); } function classExpressionToDeclaration(name, additionalModifiers, cls, useSitesToUnqualify) { - return ts.factory.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. - ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); + return ts.factory.createClassDeclaration(ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); } function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" @@ -152490,7 +154937,6 @@ var ts; } function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { return ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, exportSpecifiers && ts.factory.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.factory.createStringLiteral(moduleSpecifier)); } @@ -152579,11 +155025,10 @@ var ts; changes.insertModifierBefore(context.sourceFile, 152 /* SyntaxKind.TypeKeyword */, exportClause); } else { - var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.decorators, exportDeclaration.modifiers, + var valueExportDeclaration = ts.factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, /*isTypeOnly*/ false, ts.factory.updateNamedExports(exportClause, ts.filter(exportClause.elements, function (e) { return !ts.contains(typeExportSpecifiers, e); })), exportDeclaration.moduleSpecifier, /*assertClause*/ undefined); var typeExportDeclaration = ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ true, ts.factory.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, /*assertClause*/ undefined); @@ -152647,7 +155092,6 @@ var ts; if (importClause.name && importClause.namedBindings) { changes.deleteNodeRangeExcludingEnd(context.sourceFile, importClause.name, importDeclaration.importClause.namedBindings); changes.insertNodeBefore(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ true, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, @@ -153001,6 +155445,18 @@ var ts; return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0; } } + function createImportSpecifierResolver(importingFile, program, host, preferences) { + var packageJsonImportFilter = ts.createPackageJsonImportFilter(importingFile, preferences, host); + var importMap = createExistingImportMap(program.getTypeChecker(), importingFile, program.getCompilerOptions()); + return { getModuleSpecifierForBestExportInfo: getModuleSpecifierForBestExportInfo }; + function getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, fromCacheOnly) { + var _a = getImportFixes(exportInfo, { symbolName: symbolName, position: position }, isValidTypeOnlyUseSite, + /*useRequire*/ false, program, importingFile, host, preferences, importMap, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount; + var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host); + return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount }); + } + } + codefix.createImportSpecifierResolver = createImportSpecifierResolver; // Sorted with the preferred fix coming first. var ImportFixKind; (function (ImportFixKind) { @@ -153078,7 +155534,7 @@ var ts; var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); }); - ts.forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { + ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(importingFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { @@ -153101,18 +155557,12 @@ var ts; return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, preferences, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); } } - function getModuleSpecifierForBestExportInfo(exportInfo, symbolName, position, isValidTypeOnlyUseSite, importingFile, program, host, preferences, packageJsonImportFilter, fromCacheOnly) { - var _a = getImportFixes(exportInfo, { symbolName: symbolName, position: position }, isValidTypeOnlyUseSite, - /*useRequire*/ false, program, importingFile, host, preferences, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount; - var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter || ts.createPackageJsonImportFilter(importingFile, preferences, host), host); - return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount }); - } - codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo; function getImportFixes(exportInfos, useNamespaceInfo, /** undefined only for missing JSX namespace */ - isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, fromCacheOnly) { + isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap, fromCacheOnly) { + if (importMap === void 0) { importMap = createExistingImportMap(program.getTypeChecker(), sourceFile, program.getCompilerOptions()); } var checker = program.getTypeChecker(); - var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile, program.getCompilerOptions()); }); + var existingImports = ts.flatMap(exportInfos, importMap.getImportsForExportInfo); var useNamespace = useNamespaceInfo && tryUseExistingNamespaceImport(existingImports, useNamespaceInfo.symbolName, useNamespaceInfo.position, checker); var addToExisting = tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, program.getCompilerOptions()); if (addToExisting) { @@ -153240,21 +155690,37 @@ var ts; }; }); } - function getExistingImportDeclarations(_a, checker, importingFile, compilerOptions) { - var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, targetFlags = _a.targetFlags, symbol = _a.symbol; - // Can't use an es6 import for a type in JS. - if (!(targetFlags & 111551 /* SymbolFlags.Value */) && ts.isSourceFileJS(importingFile)) - return ts.emptyArray; - var importKind = getImportKind(importingFile, exportKind, compilerOptions); - return ts.mapDefined(importingFile.imports, function (moduleSpecifier) { + function createExistingImportMap(checker, importingFile, compilerOptions) { + var importMap; + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; var i = ts.importFromModuleSpecifier(moduleSpecifier); if (ts.isVariableDeclarationInitializedToRequire(i.parent)) { - return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind, symbol: symbol, targetFlags: targetFlags } : undefined; + var moduleSymbol = checker.resolveExternalModuleName(moduleSpecifier); + if (moduleSymbol) { + (importMap || (importMap = ts.createMultiMap())).add(ts.getSymbolId(moduleSymbol), i.parent); + } } - if (i.kind === 266 /* SyntaxKind.ImportDeclaration */ || i.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { - return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind, symbol: symbol, targetFlags: targetFlags } : undefined; + else if (i.kind === 266 /* SyntaxKind.ImportDeclaration */ || i.kind === 265 /* SyntaxKind.ImportEqualsDeclaration */) { + var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); + if (moduleSymbol) { + (importMap || (importMap = ts.createMultiMap())).add(ts.getSymbolId(moduleSymbol), i); + } } - }); + } + return { + getImportsForExportInfo: function (_a) { + var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, targetFlags = _a.targetFlags, symbol = _a.symbol; + // Can't use an es6 import for a type in JS. + if (!(targetFlags & 111551 /* SymbolFlags.Value */) && ts.isSourceFileJS(importingFile)) + return ts.emptyArray; + var matchingDeclarations = importMap === null || importMap === void 0 ? void 0 : importMap.get(ts.getSymbolId(moduleSymbol)); + if (!matchingDeclarations) + return ts.emptyArray; + var importKind = getImportKind(importingFile, exportKind, compilerOptions); + return matchingDeclarations.map(function (declaration) { return ({ declaration: declaration, importKind: importKind, symbol: symbol, targetFlags: targetFlags }); }); + } + }; } function shouldUseRequire(sourceFile, program) { // 1. TypeScript files don't use require variable declarations @@ -153537,7 +156003,7 @@ var ts; originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol: moduleSymbol, moduleFileName: toFile === null || toFile === void 0 ? void 0 : toFile.fileName, exportKind: exportKind, targetFlags: ts.skipAlias(exportedSymbol, checker).flags, isFromPackageJson: isFromPackageJson }); } } - ts.forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { + ts.forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); @@ -153797,10 +156263,8 @@ var ts; if (namespaceLikeImport) { var declaration = namespaceLikeImport.importKind === 3 /* ImportKind.CommonJS */ ? ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, needsTypeOnly(namespaceLikeImport), ts.factory.createIdentifier(namespaceLikeImport.name), ts.factory.createExternalModuleReference(quotedModuleSpecifier)) : ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(needsTypeOnly(namespaceLikeImport), /*name*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier, /*assertClause*/ undefined); @@ -153880,6 +156344,113 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingConstraint"; + var errorCodes = [ + // We want errors this could be attached to: + // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint + ts.Diagnostics.Type_0_is_not_comparable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, + ts.Diagnostics.Property_0_is_incompatible_with_index_signature.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program, preferences = context.preferences, host = context.host; + var info = getInfo(program, sourceFile, span); + if (info === undefined) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingConstraint(t, program, preferences, host, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_extends_constraint, fixId, ts.Diagnostics.Add_extends_constraint_to_all_type_parameters)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var program = context.program, preferences = context.preferences, host = context.host; + var seen = new ts.Map(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(program, diag.file, ts.createTextSpan(diag.start, diag.length)); + if (info) { + if (ts.addToSeen(seen, ts.getNodeId(info.declaration))) { + return addMissingConstraint(changes, program, preferences, host, diag.file, info); + } + } + return undefined; + }); + })); + } + }); + function getInfo(program, sourceFile, span) { + var diag = ts.find(program.getSemanticDiagnostics(sourceFile), function (diag) { return diag.start === span.start && diag.length === span.length; }); + if (diag === undefined || diag.relatedInformation === undefined) + return; + var related = ts.find(diag.relatedInformation, function (related) { return related.code === ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code; }); + if (related === undefined || related.file === undefined || related.start === undefined || related.length === undefined) + return; + var declaration = findAncestorMatchingSpan(related.file, ts.createTextSpan(related.start, related.length)); + if (declaration === undefined) + return; + if (ts.isIdentifier(declaration) && ts.isTypeParameterDeclaration(declaration.parent)) { + declaration = declaration.parent; + } + if (ts.isTypeParameterDeclaration(declaration)) { + // should only issue fix on type parameters written using `extends` + if (ts.isMappedTypeNode(declaration.parent)) + return; + var token = ts.getTokenAtPosition(sourceFile, span.start); + var checker = program.getTypeChecker(); + var constraint = tryGetConstraintType(checker, token) || tryGetConstraintFromDiagnosticMessage(related.messageText); + return { constraint: constraint, declaration: declaration, token: token }; + } + return undefined; + } + function addMissingConstraint(changes, program, preferences, host, sourceFile, info) { + var declaration = info.declaration, constraint = info.constraint; + var checker = program.getTypeChecker(); + if (ts.isString(constraint)) { + changes.insertText(sourceFile, declaration.name.end, " extends ".concat(constraint)); + } + else { + var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions()); + var tracker = codefix.getNoopSymbolTrackerWithResolver({ program: program, host: host }); + var importAdder = codefix.createImportAdder(sourceFile, program, preferences, host); + var typeNode = codefix.typeToAutoImportableTypeNode(checker, importAdder, constraint, /*contextNode*/ undefined, scriptTarget, /*flags*/ undefined, tracker); + if (typeNode) { + changes.replaceNode(sourceFile, declaration, ts.factory.updateTypeParameterDeclaration(declaration, /*modifiers*/ undefined, declaration.name, typeNode, declaration.default)); + importAdder.writeFixes(changes); + } + } + } + function findAncestorMatchingSpan(sourceFile, span) { + var end = ts.textSpanEnd(span); + var token = ts.getTokenAtPosition(sourceFile, span.start); + while (token.end < end) { + token = token.parent; + } + return token; + } + function tryGetConstraintFromDiagnosticMessage(messageText) { + var _a = ts.flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || [], _ = _a[0], constraint = _a[1]; + return constraint; + } + function tryGetConstraintType(checker, node) { + if (ts.isTypeNode(node.parent)) { + return checker.getTypeArgumentConstraint(node.parent); + } + var contextualType = ts.isExpression(node) ? checker.getContextualType(node) : undefined; + return contextualType || checker.getTypeAtLocation(node); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -154002,10 +156573,11 @@ var ts; var staticModifier = ts.find(modifiers, ts.isStaticModifier); var abstractModifier = ts.find(modifiers, ts.isAbstractModifier); var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var lastDecorator = ts.findLast(modifiers, ts.isDecorator); var modifierPos = abstractModifier ? abstractModifier.end : staticModifier ? staticModifier.end : accessibilityModifier ? accessibilityModifier.end : - classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + lastDecorator ? ts.skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile); var options = accessibilityModifier || staticModifier || abstractModifier ? { prefix: " " } : { suffix: " " }; changeTracker.insertModifierAt(sourceFile, modifierPos, 159 /* SyntaxKind.OverrideKeyword */, options); } @@ -154015,7 +156587,7 @@ var ts; changeTracker.filterJSDocTags(sourceFile, classElement, ts.not(ts.isJSDocOverrideTag)); return; } - var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 159 /* SyntaxKind.OverrideKeyword */; }); + var overrideModifier = ts.find(classElement.modifiers, ts.isOverrideModifier); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); } @@ -154615,7 +157187,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, declaration) { var supers = ts.isTypeLiteralNode(declaration) ? undefined : codefix.getAllSupers(declaration, checker); - var _loop_15 = function (info) { + var _loop_13 = function (info) { // If some superclass added this property, don't add it again. if (supers === null || supers === void 0 ? void 0 : supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -154642,7 +157214,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_15(info); + _loop_13(info); } }); })); @@ -154694,7 +157266,7 @@ var ts; return undefined; return { kind: 4 /* InfoKind.JsxAttributes */, token: token, attributes: attributes, parentDeclaration: token.parent }; } - if (ts.isIdentifier(token) && ts.isCallExpression(parent)) { + if (ts.isIdentifier(token) && ts.isCallExpression(parent) && parent.expression === token) { return { kind: 2 /* InfoKind.Function */, token: token, call: parent, sourceFile: sourceFile, modifierFlags: 0 /* ModifierFlags.None */, parentDeclaration: sourceFile }; } if (!ts.isPropertyAccessExpression(parent)) @@ -154771,7 +157343,6 @@ var ts; } else if (ts.isPrivateIdentifier(token)) { var property = ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, tokenName, /*questionToken*/ undefined, /*type*/ undefined, @@ -154829,7 +157400,7 @@ var ts; function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) { var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var property = ts.isClassLike(node) - ? ts.factory.createPropertyDeclaration(/*decorators*/ undefined, modifiers, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined) + ? ts.factory.createPropertyDeclaration(modifiers, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined) : ts.factory.createPropertySignature(/*modifiers*/ undefined, tokenName, /*questionToken*/ undefined, typeNode); var lastProp = getNodeToInsertPropertyAfter(node); if (lastProp) { @@ -154854,13 +157425,11 @@ var ts; // Index signatures cannot have the static modifier. var stringTypeNode = ts.factory.createKeywordTypeNode(150 /* SyntaxKind.StringKeyword */); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, stringTypeNode, /*initializer*/ undefined); var indexSignature = ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertMemberAtStart(sourceFile, node, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. @@ -154908,7 +157477,7 @@ var ts; return !!(type && type.flags & 402653316 /* TypeFlags.StringLike */); }); var enumMember = ts.factory.createEnumMember(token, hasStringInitializer ? ts.factory.createStringLiteral(token.text) : undefined); - changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.decorators, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), { + changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, ts.factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.modifiers, parentDeclaration.name, ts.concatenate(parentDeclaration.members, ts.singleElementArray(enumMember))), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude }); @@ -154917,6 +157486,7 @@ var ts; var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(256 /* SyntaxKind.FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration); changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); + importAdder.writeFixes(changes); } function addJsxAttributes(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); @@ -154925,7 +157495,7 @@ var ts; var jsxAttributesNode = info.parentDeclaration.attributes; var hasSpreadAttribute = ts.some(jsxAttributesNode.properties, ts.isJsxSpreadAttribute); var attrs = ts.map(info.attributes, function (attr) { - var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr)); + var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr), info.parentDeclaration); var name = ts.factory.createIdentifier(attr.name); var jsxAttribute = ts.factory.createJsxAttribute(name, ts.factory.createJsxExpression(/*dotDotDotToken*/ undefined, value)); // formattingScanner requires the Identifier to have a context for scanning attributes with "-" (data-foo). @@ -154935,6 +157505,7 @@ var ts; var jsxAttributes = ts.factory.createJsxAttributes(hasSpreadAttribute ? __spreadArray(__spreadArray([], attrs, true), jsxAttributesNode.properties, true) : __spreadArray(__spreadArray([], jsxAttributesNode.properties, true), attrs, true)); var options = { prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : undefined }; changes.replaceNode(context.sourceFile, jsxAttributesNode, jsxAttributes, options); + importAdder.writeFixes(changes); } function addObjectLiteralProperties(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); @@ -154942,8 +157513,8 @@ var ts; var target = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var props = ts.map(info.properties, function (prop) { - var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop)); - return ts.factory.createPropertyAssignment(ts.createPropertyNameNodeForIdentifierOrLiteral(prop.name, target, quotePreference === 0 /* QuotePreference.Single */), initializer); + var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), info.parentDeclaration); + return ts.factory.createPropertyAssignment(createPropertyNameFromSymbol(prop, target, quotePreference, checker), initializer); }); var options = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, @@ -154951,8 +157522,9 @@ var ts; indentation: info.indentation }; changes.replaceNode(context.sourceFile, info.parentDeclaration, ts.factory.createObjectLiteralExpression(__spreadArray(__spreadArray([], info.parentDeclaration.properties, true), props, true), /*multiLine*/ true), options); + importAdder.writeFixes(changes); } - function tryGetValueFromType(context, checker, importAdder, quotePreference, type) { + function tryGetValueFromType(context, checker, importAdder, quotePreference, type, enclosingDeclaration) { if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { return createUndefined(); } @@ -154989,7 +157561,7 @@ var ts; return ts.factory.createNull(); } if (type.flags & 1048576 /* TypeFlags.Union */) { - var expression = ts.firstDefined(type.types, function (t) { return tryGetValueFromType(context, checker, importAdder, quotePreference, t); }); + var expression = ts.firstDefined(type.types, function (t) { return tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration); }); return expression !== null && expression !== void 0 ? expression : createUndefined(); } if (checker.isArrayLikeType(type)) { @@ -154997,7 +157569,7 @@ var ts; } if (isObjectLiteralType(type)) { var props = ts.map(checker.getPropertiesOfType(type), function (prop) { - var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration)) : createUndefined(); + var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration), enclosingDeclaration) : createUndefined(); return ts.factory.createPropertyAssignment(prop.name, initializer); }); return ts.factory.createObjectLiteralExpression(props, /*multiLine*/ true); @@ -155009,7 +157581,7 @@ var ts; var signature = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (signature === undefined) return createUndefined(); - var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ undefined, importAdder); + var func = codefix.createSignatureDeclarationFromSignature(213 /* SyntaxKind.FunctionExpression */, context, quotePreference, signature[0], codefix.createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ enclosingDeclaration, importAdder); return func !== null && func !== void 0 ? func : createUndefined(); } if (ts.getObjectFlags(type) & 1 /* ObjectFlags.Class */) { @@ -155062,6 +157634,15 @@ var ts; var declaration = ts.findAncestor(callExpression, function (n) { return ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n); }); return declaration && declaration.parent === node ? declaration : undefined; } + function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) { + if (ts.isTransientSymbol(symbol) && symbol.nameType && symbol.nameType.flags & 8192 /* TypeFlags.UniqueESSymbol */) { + var expression = checker.symbolToExpression(symbol.nameType.symbol, 111551 /* SymbolFlags.Value */, symbol.valueDeclaration, 1048576 /* NodeBuilderFlags.AllowUniqueESSymbolType */); + if (expression) { + return ts.factory.createComputedPropertyName(expression); + } + } + return ts.createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* QuotePreference.Single */); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -155987,7 +158568,12 @@ var ts; if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) { if (parameter.modifiers && parameter.modifiers.length > 0 && (!ts.isIdentifier(parameter.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) { - parameter.modifiers.forEach(function (modifier) { return changes.deleteModifier(sourceFile, modifier); }); + for (var _i = 0, _a = parameter.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isModifier(modifier)) { + changes.deleteModifier(sourceFile, modifier); + } + } } else if (!parameter.initializer && isNotProvidedArguments(parameter, checker, sourceFiles)) { changes.delete(sourceFile, parameter); @@ -157402,7 +159988,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_16 = function (i) { + var _loop_14 = function (i) { var symbol = checker.createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg".concat(i))); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -157411,7 +159997,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_16(i); + _loop_14(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* SignatureFlags.None */); @@ -157601,8 +160187,7 @@ var ts; importSymbols(importAdder, importableReference.symbols); } } - addClassElement(ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, + addClassElement(ts.factory.createPropertyDeclaration(modifiers, name, optional && (preserveOptional & 2 /* PreserveOptionalFlags.Property */) ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; case 172 /* SyntaxKind.GetAccessor */: @@ -157622,15 +160207,13 @@ var ts; for (var _i = 0, orderedAccessors_1 = orderedAccessors; _i < orderedAccessors_1.length; _i++) { var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { - addClassElement(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createGetAccessorDeclaration(modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; - addClassElement(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); + addClassElement(ts.factory.createSetAccessorDeclaration(modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } } break; @@ -157644,7 +160227,7 @@ var ts; // If there is more than one overload but no implementation signature // (eg: an abstract method or interface declaration), there is a 1-1 // correspondence of declarations and signatures. - var signatures = checker.getSignaturesOfType(type, 0 /* SignatureKind.Call */); + var signatures = type.isUnion() ? ts.flatMap(type.types, function (t) { return t.getCallSignatures(); }) : type.getCallSignatures(); if (!ts.some(signatures)) { break; } @@ -157725,7 +160308,7 @@ var ts; type = importableReference.typeNode; importSymbols(importAdder, importableReference.symbols); } - return ts.factory.updateParameterDeclaration(parameterDecl, parameterDecl.decorators, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, parameterDecl.questionToken, type, parameterDecl.initializer); + return ts.factory.updateParameterDeclaration(parameterDecl, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, parameterDecl.questionToken, type, parameterDecl.initializer); }); if (parameters !== newParameters) { parameters = ts.setTextRange(ts.factory.createNodeArray(newParameters, parameters.hasTrailingComma), parameters); @@ -157747,7 +160330,7 @@ var ts; return ts.factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body !== null && body !== void 0 ? body : signatureDeclaration.body); } if (ts.isMethodDeclaration(signatureDeclaration)) { - return ts.factory.updateMethodDeclaration(signatureDeclaration, /* decorators */ undefined, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); + return ts.factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name !== null && name !== void 0 ? name : ts.factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); } return undefined; } @@ -157763,40 +160346,50 @@ var ts; var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined; }); - var types = isJs ? [] : ts.map(args, function (arg) { - return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker); - }); + var instanceTypes = isJs ? [] : ts.map(args, function (arg) { return checker.getTypeAtLocation(arg); }); + var _a = getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, /*flags*/ undefined, tracker), argumentTypeNodes = _a.argumentTypeNodes, argumentTypeParameters = _a.argumentTypeParameters; var modifiers = modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; var asteriskToken = ts.isYieldExpression(parent) ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined; - var typeParameters = isJs || typeArguments === undefined - ? undefined - : ts.map(typeArguments, function (_, i) { - return ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, 84 /* CharacterCodes.T */ + typeArguments.length - 1 <= 90 /* CharacterCodes.Z */ ? String.fromCharCode(84 /* CharacterCodes.T */ + i) : "T".concat(i)); - }); - var parameters = createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, isJs); + var typeParameters = isJs ? undefined : createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments); + var parameters = createDummyParameters(args.length, names, argumentTypeNodes, /*minArgumentCount*/ undefined, isJs); var type = isJs || contextualType === undefined ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); switch (kind) { case 169 /* SyntaxKind.MethodDeclaration */: - return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers, asteriskToken, name, + return ts.factory.createMethodDeclaration(modifiers, asteriskToken, name, /*questionToken*/ undefined, typeParameters, parameters, type, createStubbedMethodBody(quotePreference)); case 168 /* SyntaxKind.MethodSignature */: return ts.factory.createMethodSignature(modifiers, name, - /*questionToken*/ undefined, typeParameters, parameters, type); + /*questionToken*/ undefined, typeParameters, parameters, type === undefined ? ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */) : type); case 256 /* SyntaxKind.FunctionDeclaration */: - return ts.factory.createFunctionDeclaration( - /*decorators*/ undefined, modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); + return ts.factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(ts.Diagnostics.Function_not_implemented.message, quotePreference)); default: ts.Debug.fail("Unexpected kind"); } } codefix.createSignatureDeclarationFromCallExpression = createSignatureDeclarationFromCallExpression; + function createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments) { + var usedNames = new ts.Set(argumentTypeParameters.map(function (pair) { return pair[0]; })); + var constraintsByName = new ts.Map(argumentTypeParameters); + if (typeArguments) { + var typeArgumentsWithNewTypes = typeArguments.filter(function (typeArgument) { return !argumentTypeParameters.some(function (pair) { var _a; return checker.getTypeAtLocation(typeArgument) === ((_a = pair[1]) === null || _a === void 0 ? void 0 : _a.argumentType); }); }); + var targetSize = usedNames.size + typeArgumentsWithNewTypes.length; + for (var i = 0; usedNames.size < targetSize; i += 1) { + usedNames.add(createTypeParameterName(i)); + } + } + return ts.map(ts.arrayFrom(usedNames.values()), function (usedName) { var _a; return ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, usedName, (_a = constraintsByName.get(usedName)) === null || _a === void 0 ? void 0 : _a.constraint); }); + } + function createTypeParameterName(index) { + return 84 /* CharacterCodes.T */ + index <= 90 /* CharacterCodes.Z */ + ? String.fromCharCode(84 /* CharacterCodes.T */ + index) + : "T".concat(index); + } function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); if (typeNode && ts.isImportTypeNode(typeNode)) { @@ -157810,16 +160403,107 @@ var ts; return ts.getSynthesizedDeepClone(typeNode); } codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode; + function typeContainsTypeParameter(type) { + if (type.isUnionOrIntersection()) { + return type.types.some(typeContainsTypeParameter); + } + return type.flags & 262144 /* TypeFlags.TypeParameter */; + } + function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, tracker) { + // Types to be used as the types of the parameters in the new function + // E.g. from this source: + // added("", 0) + // The value will look like: + // [{ typeName: { text: "string" } }, { typeName: { text: "number" }] + // And in the output function will generate: + // function added(a: string, b: number) { ... } + var argumentTypeNodes = []; + // Names of type parameters provided as arguments to the call + // E.g. from this source: + // added(value); + // The value will look like: + // [ + // ["T", { argumentType: { typeName: { text: "T" } } } ], + // ["U", { argumentType: { typeName: { text: "U" } } } ], + // ] + // And in the output function will generate: + // function added() { ... } + var argumentTypeParameters = new ts.Map(); + for (var i = 0; i < instanceTypes.length; i += 1) { + var instanceType = instanceTypes[i]; + // If the instance type contains a deep reference to an existing type parameter, + // instead of copying the full union or intersection, create a new type parameter + // E.g. from this source: + // function existing(value: T | U & string) { + // added/*1*/(value); + // We don't want to output this: + // function added(value: T | U & string) { ... } + // We instead want to output: + // function added(value: T) { ... } + if (instanceType.isUnionOrIntersection() && instanceType.types.some(typeContainsTypeParameter)) { + var synthesizedTypeParameterName = createTypeParameterName(i); + argumentTypeNodes.push(ts.factory.createTypeReferenceNode(synthesizedTypeParameterName)); + argumentTypeParameters.set(synthesizedTypeParameterName, undefined); + continue; + } + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + var widenedInstanceType = checker.getBaseTypeOfLiteralType(instanceType); + var argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, tracker); + if (!argumentTypeNode) { + continue; + } + argumentTypeNodes.push(argumentTypeNode); + var argumentTypeParameter = getFirstTypeParameterName(instanceType); + // If the instance type is a type parameter with a constraint (other than an anonymous object), + // remember that constraint for when we create the new type parameter + // E.g. from this source: + // function existing(value: T) { + // added/*1*/(value); + // We don't want to output this: + // function added(value: T) { ... } + // We instead want to output: + // function added(value: T) { ... } + var instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) + ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, tracker) + : undefined; + if (argumentTypeParameter) { + argumentTypeParameters.set(argumentTypeParameter, { argumentType: instanceType, constraint: instanceTypeConstraint }); + } + } + return { argumentTypeNodes: argumentTypeNodes, argumentTypeParameters: ts.arrayFrom(argumentTypeParameters.entries()) }; + } + codefix.getArgumentTypesAndTypeParameters = getArgumentTypesAndTypeParameters; + function isAnonymousObjectConstraintType(type) { + return (type.flags & 524288 /* TypeFlags.Object */) && type.objectFlags === 16 /* ObjectFlags.Anonymous */; + } + function getFirstTypeParameterName(type) { + var _a; + if (type.flags & (1048576 /* TypeFlags.Union */ | 2097152 /* TypeFlags.Intersection */)) { + for (var _i = 0, _b = type.types; _i < _b.length; _i++) { + var subType = _b[_i]; + var subTypeName = getFirstTypeParameterName(subType); + if (subTypeName) { + return subTypeName; + } + } + } + return type.flags & 262144 /* TypeFlags.TypeParameter */ + ? (_a = type.getSymbol()) === null || _a === void 0 ? void 0 : _a.getName() + : undefined; + } function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; + var parameterNameCounts = new ts.Map(); for (var i = 0; i < argCount; i++) { + var parameterName = (names === null || names === void 0 ? void 0 : names[i]) || "arg".concat(i); + var parameterNameCount = parameterNameCounts.get(parameterName); + parameterNameCounts.set(parameterName, (parameterNameCount || 0) + 1); var newParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - /*name*/ names && names[i] || "arg".concat(i), + /*name*/ parameterName + (parameterNameCount || ""), /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, - /*type*/ inJs ? undefined : types && types[i] || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), + /*type*/ inJs ? undefined : (types === null || types === void 0 ? void 0 : types[i]) || ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -157848,7 +160532,6 @@ var ts; var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var restParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, ts.factory.createArrayTypeNode(ts.factory.createKeywordTypeNode(155 /* SyntaxKind.UnknownKeyword */)), /*initializer*/ undefined); @@ -157864,8 +160547,7 @@ var ts; } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { - return ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers, + return ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } function createStubbedMethodBody(quotePreference) { @@ -157996,6 +160678,9 @@ var ts; accessorModifiers = ts.createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); fieldModifiers = ts.createModifiers(prepareModifierFlagsForField(modifierFlags)); } + if (ts.canHaveDecorators(declaration)) { + fieldModifiers = ts.concatenate(ts.getDecorators(declaration), fieldModifiers); + } } updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); @@ -158060,7 +160745,7 @@ var ts; error: ts.getLocaleSpecificMessage(ts.Diagnostics.Name_is_not_valid) }; } - if ((ts.getEffectiveModifierFlags(declaration) | meaning) !== meaning) { + if (((ts.getEffectiveModifierFlags(declaration) & 125951 /* ModifierFlags.Modifier */) | meaning) !== meaning) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_property_with_modifier) }; @@ -158083,17 +160768,14 @@ var ts; } codefix.getAccessorConvertiblePropertyAtPosition = getAccessorConvertiblePropertyAtPosition; function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { - return ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, accessorName, + return ts.factory.createGetAccessorDeclaration(modifiers, accessorName, /*parameters*/ undefined, // TODO: GH#18217 type, ts.factory.createBlock([ ts.factory.createReturnStatement(createAccessorAccessExpression(fieldName, isStatic, container)) ], /*multiLine*/ true)); } function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { - return ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, accessorName, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createSetAccessorDeclaration(modifiers, accessorName, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.factory.createIdentifier("value"), /*questionToken*/ undefined, type)], ts.factory.createBlock([ @@ -158101,7 +160783,7 @@ var ts; ], /*multiLine*/ true)); } function updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) { - var property = ts.factory.updatePropertyDeclaration(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); + var property = ts.factory.updatePropertyDeclaration(declaration, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); changeTracker.replaceNode(file, declaration, property); } function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { @@ -158116,7 +160798,7 @@ var ts; updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - changeTracker.replaceNode(file, declaration, ts.factory.updateParameterDeclaration(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + changeTracker.replaceNode(file, declaration, ts.factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } function insertAccessor(changeTracker, file, accessor, declaration, container) { @@ -158190,7 +160872,6 @@ var ts; if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, namespace.name, ts.factory.createExternalModuleReference(node.moduleSpecifier)))); } @@ -158327,7 +161008,7 @@ var ts; } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { ts.suppressLeadingAndTrailingTrivia(propertyDeclaration); - var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* SyntaxKind.ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); + var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* SyntaxKind.ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, info) { @@ -158357,7 +161038,7 @@ var ts; } function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { ts.suppressLeadingAndTrailingTrivia(propertyDeclaration); - var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); + var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { @@ -158423,8 +161104,8 @@ var ts; function doChange(changes, sourceFile, info) { var allowSyntheticDefaults = info.allowSyntheticDefaults, defaultImportName = info.defaultImportName, namedImports = info.namedImports, statement = info.statement, required = info.required; changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults - ? ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required)) - : ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); + ? ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, ts.factory.createExternalModuleReference(required)) + : ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); } function getInfo(sourceFile, program, pos) { var parent = ts.getTokenAtPosition(sourceFile, pos).parent; @@ -158562,7 +161243,7 @@ var ts; return token.parent; } function doChange(changes, sourceFile, importType) { - var newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + var newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.assertions, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); changes.replaceNode(sourceFile, importType, newTypeNode); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -158679,7 +161360,7 @@ var ts; return { indexSignature: indexSignature, container: container }; } function createTypeAliasFromInterface(declaration, type) { - return ts.factory.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + return ts.factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); } function doChange(changes, sourceFile, _a) { var indexSignature = _a.indexSignature, container = _a.container; @@ -158795,9 +161476,8 @@ var ts; return; } var importClause = ts.Debug.checkDefined(importDeclaration.importClause); - changes.replaceNode(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); + changes.replaceNode(context.sourceFile, importDeclaration, ts.factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); changes.insertNodeAfter(context.sourceFile, importDeclaration, ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ undefined, importClause.namedBindings), importDeclaration.moduleSpecifier, importDeclaration.assertClause)); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -159019,14 +161699,14 @@ var ts; if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_export_statement) }; } - var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var checker = program.getTypeChecker(); + var exportingModuleSymbol = getExportingModuleSymbol(exportNode, checker); var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ModifierFlags.ExportDefault */ : 0 /* ModifierFlags.None */); var wasDefault = !!(flags & 512 /* ModifierFlags.Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* ModifierFlags.Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* InternalSymbolName.Default */)) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.This_file_already_has_a_default_export) }; } - var checker = program.getTypeChecker(); var noSymbolError = function (id) { return (ts.isIdentifier(id) && checker.getSymbolAtLocation(id)) ? undefined : { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Can_only_convert_named_export) }; @@ -159078,7 +161758,7 @@ var ts; if (ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) { var exp = exportNode.expression; var spec = makeExportSpecifier(exp.text, exp.text); - changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); + changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); } else { changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 88 /* SyntaxKind.DefaultKeyword */), "Should find a default keyword in modifier list")); @@ -159118,6 +161798,8 @@ var ts; var checker = program.getTypeChecker(); var exportSymbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + if (exportName === ref) + return; var importingSourceFile = ref.getSourceFile(); if (wasDefault) { changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); @@ -159166,7 +161848,7 @@ var ts; } case 200 /* SyntaxKind.ImportType */: var importTypeNode = parent; - changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); + changes.replaceNode(importingSourceFile, parent, ts.factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, ts.factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); break; default: ts.Debug.failBadSyntaxKind(parent); @@ -159210,6 +161892,17 @@ var ts; function makeExportSpecifier(propertyName, name) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, propertyName === name ? undefined : ts.factory.createIdentifier(propertyName), ts.factory.createIdentifier(name)); } + function getExportingModuleSymbol(node, checker) { + var parent = node.parent; + if (ts.isSourceFile(parent)) { + return parent.symbol; + } + var symbol = parent.parent.symbol; + if (symbol.valueDeclaration && ts.isExternalModuleAugmentation(symbol.valueDeclaration)) { + return checker.getMergedSymbol(symbol); + } + return symbol; + } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ @@ -159384,7 +162077,7 @@ var ts; // Imports that need to be kept as named imports in the refactored code, to avoid changing the semantics. // More specifically, those are named imports that appear in named exports in the original code, e.g. `a` in `import { a } from "m"; export { a }`. var neededNamedImports = new ts.Set(); - var _loop_17 = function (element) { + var _loop_15 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -159401,7 +162094,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_17(element); + _loop_15(element); } changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? ts.factory.createIdentifier(namespaceImportName) @@ -159422,7 +162115,7 @@ var ts; return externalModule !== exportEquals; } function updateImport(old, defaultImportName, elements) { - return ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); + return ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); @@ -159736,7 +162429,7 @@ var ts; break; } case 169 /* SyntaxKind.MethodDeclaration */: { - updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } case 174 /* SyntaxKind.CallSignature */: { @@ -159744,7 +162437,7 @@ var ts; break; } case 171 /* SyntaxKind.Constructor */: { - updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); + updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); break; } case 175 /* SyntaxKind.ConstructSignature */: { @@ -159752,7 +162445,7 @@ var ts; break; } case 256 /* SyntaxKind.FunctionDeclaration */: { - updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } default: return ts.Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); @@ -159772,7 +162465,6 @@ var ts; } return ts.factory.createNodeArray([ ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */), "args", /*questionToken*/ undefined, ts.factory.createUnionTypeNode(ts.map(signatureDeclarations, convertSignatureParametersToTuple))) ]); @@ -159819,6 +162511,9 @@ var ts; if (!containingDecl) { return; } + if (ts.isFunctionLikeDeclaration(containingDecl) && containingDecl.body && ts.rangeContainsPosition(containingDecl.body, startPosition)) { + return; + } var checker = program.getTypeChecker(); var signatureSymbol = containingDecl.symbol; if (!signatureSymbol) { @@ -159839,7 +162534,7 @@ var ts; return; } var signatureDecls = decls; - if (ts.some(signatureDecls, function (d) { return !!d.typeParameters || ts.some(d.parameters, function (p) { return !!p.decorators || !!p.modifiers || !ts.isIdentifier(p.name); }); })) { + if (ts.some(signatureDecls, function (d) { return !!d.typeParameters || ts.some(d.parameters, function (p) { return !!p.modifiers || !ts.isIdentifier(p.name); }); })) { return; } var signatures = ts.mapDefined(signatureDecls, function (d) { return checker.getSignatureFromDeclaration(d); }); @@ -160169,11 +162864,11 @@ var ts; } } else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { - var declarations_5 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; + var declarations_6 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, declarations_4 = declarations_5; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + for (var _i = 0, declarations_5 = declarations_6; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; if (declaration.initializer) { numInitializers++; lastInitializer = declaration.initializer; @@ -160332,7 +163027,7 @@ var ts; var savedPermittedJumps = permittedJumps; switch (node.kind) { case 239 /* SyntaxKind.IfStatement */: - permittedJumps = 0 /* PermittedJumps.None */; + permittedJumps &= ~4 /* PermittedJumps.Return */; break; case 252 /* SyntaxKind.TryStatement */: // forbid all jumps inside try blocks @@ -160624,7 +163319,6 @@ var ts; typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NodeBuilderFlags.NoTruncation */); } var paramDecl = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ name, @@ -160664,22 +163358,19 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { modifiers.push(ts.factory.createModifier(131 /* SyntaxKind.AsyncKeyword */)); } - newFunction = ts.factory.createMethodDeclaration( - /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, + newFunction = ts.factory.createMethodDeclaration(modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { if (callThis) { parameters.unshift(ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ "this", /*questionToken*/ undefined, checker.typeToTypeNode(checker.getTypeAtLocation(range.thisNode), scope, 1 /* NodeBuilderFlags.NoTruncation */), /*initializer*/ undefined)); } - newFunction = ts.factory.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + newFunction = ts.factory.createFunctionDeclaration(range.facts & RangeFacts.IsAsyncFunction ? [ts.factory.createToken(131 /* SyntaxKind.AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.factory.createToken(41 /* SyntaxKind.AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); } var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; @@ -160861,8 +163552,7 @@ var ts; modifiers.push(ts.factory.createModifier(124 /* SyntaxKind.StaticKeyword */)); } modifiers.push(ts.factory.createModifier(145 /* SyntaxKind.ReadonlyKeyword */)); - var newVariable = ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, localNameText, + var newVariable = ts.factory.createPropertyDeclaration(modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.factory.createPropertyAccessExpression(rangeFacts & RangeFacts.InStaticRegion ? ts.factory.createIdentifier(scope.name.getText()) // TODO: GH#18217 @@ -160957,7 +163647,7 @@ var ts; var paramType = checker.getTypeAtLocation(p); if (paramType === checker.getAnyType()) hasAny = true; - parameters.push(ts.factory.updateParameterDeclaration(p, p.decorators, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NodeBuilderFlags.NoTruncation */), p.initializer)); + parameters.push(ts.factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NodeBuilderFlags.NoTruncation */), p.initializer)); } } // If a parameter was inferred as any we skip adding function parameters at all. @@ -160967,7 +163657,7 @@ var ts; return { variableType: variableType, initializer: initializer }; variableType = undefined; if (ts.isArrowFunction(initializer)) { - initializer = ts.factory.updateArrowFunction(initializer, node.modifiers, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.equalsGreaterThanToken, initializer.body); + initializer = ts.factory.updateArrowFunction(initializer, ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.equalsGreaterThanToken, initializer.body); } else { if (functionSignature && !!functionSignature.thisParameter) { @@ -160977,13 +163667,12 @@ var ts; if ((!firstParameter || (ts.isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this"))) { var thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); parameters.splice(0, 0, ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, checker.typeToTypeNode(thisType, scope, 1 /* NodeBuilderFlags.NoTruncation */))); } } - initializer = ts.factory.updateFunctionExpression(initializer, node.modifiers, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.body); + initializer = ts.factory.updateFunctionExpression(initializer, ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NodeBuilderFlags.NoTruncation */), initializer.body); } return { variableType: variableType, initializer: initializer }; } @@ -161299,7 +163988,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_18 = function (i) { + var _loop_16 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -161342,7 +164031,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_18(i); + _loop_16(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -161778,7 +164467,6 @@ var ts; function doTypeAliasChange(changes, file, name, info) { var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters; var newTypeNode = ts.factory.createTypeAliasDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters.map(function (id) { return ts.factory.updateTypeParameterDeclaration(id, id.modifiers, id.name, id.constraint, /* defaultType */ undefined); }), selection); changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true); changes.replaceNode(file, selection, ts.factory.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.factory.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.ExcludeWhitespace }); @@ -161787,7 +164475,6 @@ var ts; var _a; var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters, typeElements = info.typeElements; var newTypeNode = ts.factory.createInterfaceDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters, /* heritageClauses */ undefined, typeElements); ts.setTextRange(newTypeNode, (_a = typeElements[0]) === null || _a === void 0 ? void 0 : _a.parent); @@ -161951,7 +164638,7 @@ var ts; var usage = getUsageInfo(oldFile, toMove.all, checker); var currentDirectory = ts.getDirectoryPath(oldFile.fileName); var extension = ts.extensionFromPath(oldFile.fileName); - var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.oldFileImportsFromNewFile, usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; // If previous file was global, this is easy. changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); @@ -162045,10 +164732,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_19 = function (sourceFile) { + var _loop_17 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_20 = function (statement) { + var _loop_18 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -162070,12 +164757,12 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_20(statement); + _loop_18(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_19(sourceFile); + _loop_17(sourceFile); } } function getNamespaceLikeImport(node) { @@ -162118,10 +164805,10 @@ var ts; switch (node.kind) { case 266 /* SyntaxKind.ImportDeclaration */: return ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, + /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString, /*assertClause*/ undefined); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); + return ts.factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); case 254 /* SyntaxKind.VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: @@ -162315,8 +165002,8 @@ var ts; newModuleName = "".concat(moduleName, ".").concat(i); } } - function getNewModuleName(movedSymbols) { - return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + function getNewModuleName(importsFromNewFile, movedSymbols) { + return importsFromNewFile.forEachEntry(ts.symbolNameNoDefault) || movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; } function getUsageInfo(oldFile, toMove, checker) { var movedSymbols = new SymbolSet(); @@ -162409,7 +165096,7 @@ var ts; var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); return defaultImport || namedBindings - ? ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) + ? ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined) : undefined; } case 265 /* SyntaxKind.ImportEqualsDeclaration */: @@ -162574,24 +165261,25 @@ var ts; return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); } function addEs6Export(d) { - var modifiers = ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], d.modifiers); + var modifiers = ts.canHaveModifiers(d) ? ts.concatenate([ts.factory.createModifier(93 /* SyntaxKind.ExportKeyword */)], ts.getModifiers(d)) : undefined; switch (d.kind) { case 256 /* SyntaxKind.FunctionDeclaration */: - return ts.factory.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + return ts.factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); case 257 /* SyntaxKind.ClassDeclaration */: - return ts.factory.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + var decorators = ts.canHaveDecorators(d) ? ts.getDecorators(d) : undefined; + return ts.factory.updateClassDeclaration(d, ts.concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); case 237 /* SyntaxKind.VariableStatement */: return ts.factory.updateVariableStatement(d, modifiers, d.declarationList); case 261 /* SyntaxKind.ModuleDeclaration */: - return ts.factory.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + return ts.factory.updateModuleDeclaration(d, modifiers, d.name, d.body); case 260 /* SyntaxKind.EnumDeclaration */: - return ts.factory.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + return ts.factory.updateEnumDeclaration(d, modifiers, d.name, d.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return ts.factory.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + return ts.factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); case 258 /* SyntaxKind.InterfaceDeclaration */: - return ts.factory.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + return ts.factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.isTypeOnly, d.name, d.moduleReference); + return ts.factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); case 238 /* SyntaxKind.ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: @@ -163088,7 +165776,7 @@ var ts; if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false; } - return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name); + return !parameterDeclaration.modifiers && ts.isIdentifier(parameterDeclaration.name); } function isValidVariableDeclaration(node) { return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113 @@ -163147,14 +165835,12 @@ var ts; objectInitializer = ts.factory.createObjectLiteralExpression(); } var objectParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, objectParameterName, /*questionToken*/ undefined, objectParameterType, objectInitializer); if (hasThisParameter(functionDeclaration.parameters)) { var thisParameter = functionDeclaration.parameters[0]; var newThisParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, thisParameter.type); @@ -163439,7 +166125,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText, rawHeadText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_21 = function (i) { + var _loop_19 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], rawSubsequentText = _c[2], stringIndexes = _c[3]; @@ -163468,7 +166154,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_21(i); + _loop_19(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -163675,7 +166361,7 @@ var ts; ts.suppressLeadingTrivia(statement); var modifiersFlags = (ts.getCombinedModifierFlags(variableDeclaration) & 1 /* ModifierFlags.Export */) | ts.getEffectiveModifierFlags(func); var modifiers = ts.factory.createModifiersFromModifierFlags(modifiersFlags); - var newNode = ts.factory.createFunctionDeclaration(func.decorators, ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + var newNode = ts.factory.createFunctionDeclaration(ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, statement, newNode); }); } @@ -164080,20 +166766,25 @@ var ts; return this.documentationComment; }; SymbolObject.prototype.getContextualDocumentationComment = function (context, checker) { - switch (context === null || context === void 0 ? void 0 : context.kind) { - case 172 /* SyntaxKind.GetAccessor */: + if (context) { + if (ts.isGetAccessor(context)) { if (!this.contextualGetAccessorDocumentationComment) { this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } - return this.contextualGetAccessorDocumentationComment; - case 173 /* SyntaxKind.SetAccessor */: + if (ts.length(this.contextualGetAccessorDocumentationComment)) { + return this.contextualGetAccessorDocumentationComment; + } + } + if (ts.isSetAccessor(context)) { if (!this.contextualSetAccessorDocumentationComment) { this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); } - return this.contextualSetAccessorDocumentationComment; - default: - return this.getDocumentationComment(checker); + if (ts.length(this.contextualSetAccessorDocumentationComment)) { + return this.contextualSetAccessorDocumentationComment; + } + } } + return this.getDocumentationComment(checker); }; SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { @@ -164102,20 +166793,25 @@ var ts; return this.tags; }; SymbolObject.prototype.getContextualJsDocTags = function (context, checker) { - switch (context === null || context === void 0 ? void 0 : context.kind) { - case 172 /* SyntaxKind.GetAccessor */: + if (context) { + if (ts.isGetAccessor(context)) { if (!this.contextualGetAccessorTags) { this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isGetAccessor), checker); } - return this.contextualGetAccessorTags; - case 173 /* SyntaxKind.SetAccessor */: + if (ts.length(this.contextualGetAccessorTags)) { + return this.contextualGetAccessorTags; + } + } + if (ts.isSetAccessor(context)) { if (!this.contextualSetAccessorTags) { this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isSetAccessor), checker); } - return this.contextualSetAccessorTags; - default: - return this.getJsDocTags(checker); + if (ts.length(this.contextualSetAccessorTags)) { + return this.contextualSetAccessorTags; + } + } } + return this.getJsDocTags(checker); }; return SymbolObject; }()); @@ -164296,7 +166992,7 @@ var ts; * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. */ function hasJSDocInheritDocTag(node) { - return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); + return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc"; }); } function getJsDocTagsOfDeclarations(declarations, checker) { if (!declarations) @@ -164304,7 +167000,7 @@ var ts; var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations, checker); if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) { var seenSymbols_1 = new ts.Set(); - var _loop_22 = function (declaration) { + var _loop_20 = function (declaration) { var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; if (!seenSymbols_1.has(symbol)) { @@ -164319,9 +167015,9 @@ var ts; tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); } }; - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - _loop_22(declaration); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + _loop_20(declaration); } } return tags; @@ -164332,7 +167028,7 @@ var ts; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { var seenSymbols_2 = new ts.Set(); - var _loop_23 = function (declaration) { + var _loop_21 = function (declaration) { var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { if (!seenSymbols_2.has(symbol)) { seenSymbols_2.add(symbol); @@ -164346,22 +167042,23 @@ var ts; if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); }; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - _loop_23(declaration); + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + _loop_21(declaration); } } return doc; } function findBaseOfDeclaration(checker, declaration, cb) { var _a; - if (ts.hasStaticModifier(declaration)) - return; var classOrInterfaceDeclaration = ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.kind) === 171 /* SyntaxKind.Constructor */ ? declaration.parent.parent : declaration.parent; if (!classOrInterfaceDeclaration) return; + var isStaticMember = ts.hasStaticModifier(declaration); return ts.firstDefined(ts.getAllSuperTypeNodes(classOrInterfaceDeclaration), function (superTypeNode) { - var symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name); + var baseType = checker.getTypeAtLocation(superTypeNode); + var type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType; + var symbol = checker.getPropertyOfType(type, declaration.symbol.name); return symbol ? cb(symbol) : undefined; }); } @@ -164604,70 +167301,6 @@ var ts; return ts.codefix.getSupportedErrorCodes(); } ts.getSupportedCodeFixes = getSupportedCodeFixes; - // Cache host information about script Should be refreshed - // at each language service public entry point, since we don't know when - // the set of scripts handled by the host changes. - var HostCache = /** @class */ (function () { - function HostCache(host, getCanonicalFileName) { - this.host = host; - // script id => script index - this.currentDirectory = host.getCurrentDirectory(); - this.fileNameToEntry = new ts.Map(); - // Initialize the list with the root file names - var rootFileNames = host.getScriptFileNames(); - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* tracing.Phase.Session */, "initializeHostCache", { count: rootFileNames.length }); - for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { - var fileName = rootFileNames_1[_i]; - this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); - } - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); - } - HostCache.prototype.createEntry = function (fileName, path) { - var entry; - var scriptSnapshot = this.host.getScriptSnapshot(fileName); - if (scriptSnapshot) { - entry = { - hostFileName: fileName, - version: this.host.getScriptVersion(fileName), - scriptSnapshot: scriptSnapshot, - scriptKind: ts.getScriptKind(fileName, this.host) - }; - } - else { - entry = fileName; - } - this.fileNameToEntry.set(path, entry); - return entry; - }; - HostCache.prototype.getEntryByPath = function (path) { - return this.fileNameToEntry.get(path); - }; - HostCache.prototype.getHostFileInformation = function (path) { - var entry = this.fileNameToEntry.get(path); - return !ts.isString(entry) ? entry : undefined; - }; - HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - var info = this.getEntryByPath(path) || this.createEntry(fileName, path); - return ts.isString(info) ? undefined : info; // TODO: GH#18217 - }; - HostCache.prototype.getRootFileNames = function () { - var names = []; - this.fileNameToEntry.forEach(function (entry) { - if (ts.isString(entry)) { - names.push(entry); - } - else { - names.push(entry.hostFileName); - } - }); - return names; - }; - HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getHostFileInformation(path); - return (file && file.scriptSnapshot); // TODO: GH#18217 - }; - return HostCache; - }()); var SyntaxTreeCache = /** @class */ (function () { function SyntaxTreeCache(host) { this.host = host; @@ -164929,32 +167562,16 @@ var ts; program = undefined; // TODO: GH#18217 lastTypesRootVersion = typeRootsVersion; } + // This array is retained by the program and will be used to determine if the program is up to date, + // so we need to make a copy in case the host mutates the underlying array - otherwise it would look + // like every program always has the host's current list of root files. + var rootFileNames = host.getScriptFileNames().slice(); // Get a fresh cache of the host information - var hostCache = new HostCache(host, getCanonicalFileName); - var rootFileNames = hostCache.getRootFileNames(); var newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; var hasChangedAutomaticTypeDirectiveNames = ts.maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); var projectReferences = (_b = host.getProjectReferences) === null || _b === void 0 ? void 0 : _b.call(host); var parsedCommandLines; - var parseConfigHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - fileExists: fileExists, - readFile: readFile, - readDirectory: readDirectory, - trace: ts.maybeBind(host, host.trace), - getCurrentDirectory: function () { return currentDirectory; }, - onUnRecoverableConfigFileDiagnostic: ts.noop, - }; - // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { - return; - } - // IMPORTANT - It is critical from this moment onward that we do not check - // cancellation tokens. We are about to mutate source files from a previous program - // instance. If we cancel midway through, we may end up in an inconsistent state where - // the program points to old source files that have been invalidated because of - // incremental parsing. // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -164966,8 +167583,8 @@ var ts; getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, - fileExists: fileExists, - readFile: readFile, + fileExists: function (fileName) { return host.fileExists(fileName); }, + readFile: function (fileName) { return host.readFile && host.readFile(fileName); }, getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache), realpath: ts.maybeBind(host, host.realpath), directoryExists: function (directoryName) { @@ -164976,19 +167593,56 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, - readDirectory: readDirectory, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, onReleaseParsedCommandLine: onReleaseParsedCommandLine, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, - trace: parseConfigHost.trace, + trace: ts.maybeBind(host, host.trace), resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), getModuleResolutionCache: ts.maybeBind(host, host.getModuleResolutionCache), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine: getParsedCommandLine, }; + var originalGetSourceFile = compilerHost.getSourceFile; + var getSourceFileWithCache = ts.changeCompilerHostLikeToUseCache(compilerHost, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args, false)); + }).getSourceFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; (_c = host.setCompilerHost) === null || _c === void 0 ? void 0 : _c.call(host, compilerHost); + var parseConfigHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, + readFile: function (fileName) { return compilerHost.readFile(fileName); }, + readDirectory: function () { + var _a; + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return (_a = compilerHost).readDirectory.apply(_a, args); + }, + trace: compilerHost.trace, + getCurrentDirectory: compilerHost.getCurrentDirectory, + onUnRecoverableConfigFileDiagnostic: ts.noop, + }; + // If the program is already up-to-date, we can reuse it + if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, function (fileName) { return compilerHost.fileExists(fileName); }, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + return; + } + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, @@ -164998,9 +167652,9 @@ var ts; projectReferences: projectReferences }; program = ts.createProgram(options); - // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. - // It needs to be cleared to allow all collected snapshots to be released - hostCache = undefined; + // 'getOrCreateSourceFile' depends on caching but should be used past this point. + // After this point, the cache needs to be cleared to allow all collected snapshots to be released + compilerHost = undefined; parsedCommandLines = undefined; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during @@ -165040,44 +167694,26 @@ var ts; onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); } } - function fileExists(fileName) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - return entry ? - !ts.isString(entry) : - (!!host.fileExists && host.fileExists(fileName)); - } - function readFile(fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - if (entry) { - return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); - } - return host.readFile && host.readFile(fileName); - } - function readDirectory(path, extensions, exclude, include, depth) { - ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(path, extensions, exclude, include, depth); - } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } - function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { - return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); + function getOrCreateSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { + return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersionOrOptions, onError, shouldCreateNewSourceFile); } - function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { - ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); + function getOrCreateSourceFileByPath(fileName, path, languageVersionOrOptions, _onError, shouldCreateNewSourceFile) { + ts.Debug.assert(compilerHost, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. - var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); - if (!hostFileInformation) { + var scriptSnapshot = host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { return undefined; } + var scriptKind = ts.getScriptKind(fileName, host); + var scriptVersion = host.getScriptVersion(fileName); // Check if the language version has changed since we last created a program; if they are the same, // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. @@ -165109,18 +167745,18 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { - return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } else { // Release old source file and fall through to aquire new file with new script kind - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } } // We didn't already have the file. Fall through and acquire it from the registry. } // Could not find this file in the old program, create a new SourceFile for it. - return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions); } } // TODO: GH#18217 frequently asserted as defined @@ -165136,6 +167772,61 @@ var ts; var _a; return (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); } + function updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans) { + var checker = program.getTypeChecker(); + var symbol = getSymbolForProgram(); + if (!symbol) + return false; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + var refNode = getNodeForSpan(ref); + ts.Debug.assertIsDefined(refNode); + if (knownSymbolSpans.has(ref) || ts.FindAllReferences.isDeclarationOfSymbol(refNode, symbol)) { + knownSymbolSpans.add(ref); + ref.isDefinition = true; + var mappedSpan = ts.getMappedDocumentSpan(ref, sourceMapper, ts.maybeBind(host, host.fileExists)); + if (mappedSpan) { + knownSymbolSpans.add(mappedSpan); + } + } + else { + ref.isDefinition = false; + } + } + } + return true; + function getSymbolForProgram() { + for (var _i = 0, referencedSymbols_2 = referencedSymbols; _i < referencedSymbols_2.length; _i++) { + var referencedSymbol = referencedSymbols_2[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var ref = _b[_a]; + if (knownSymbolSpans.has(ref)) { + var refNode = getNodeForSpan(ref); + ts.Debug.assertIsDefined(refNode); + return checker.getSymbolAtLocation(refNode); + } + var mappedSpan = ts.getMappedDocumentSpan(ref, sourceMapper, ts.maybeBind(host, host.fileExists)); + if (mappedSpan && knownSymbolSpans.has(mappedSpan)) { + var refNode = getNodeForSpan(mappedSpan); + if (refNode) { + return checker.getSymbolAtLocation(refNode); + } + } + } + } + return undefined; + } + function getNodeForSpan(docSpan) { + var sourceFile = program.getSourceFile(docSpan.fileName); + if (!sourceFile) + return undefined; + var rawNode = ts.getTouchingPropertyName(sourceFile, docSpan.textSpan.start); + var adjustedNode = ts.FindAllReferences.Core.getAdjustedNode(rawNode, { use: 1 /* FindAllReferences.FindReferencesUse.References */ }); + return adjustedNode; + } + } function cleanupSemanticCache() { program = undefined; // TODO: GH#18217 } @@ -165144,7 +167835,7 @@ var ts; // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); ts.forEach(program.getSourceFiles(), function (f) { - return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind, f.impliedNodeFormat); }); program = undefined; // TODO: GH#18217 } @@ -165932,9 +168623,9 @@ var ts; return ts.stringContains(path, "/node_modules/"); } } - function getRenameInfo(fileName, position, options) { + function getRenameInfo(fileName, position, preferences) { synchronizeHostData(); - return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, preferences || {}); } function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason, kind) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; @@ -166061,7 +168752,9 @@ var ts; getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getProgram: getProgram, + getCurrentProgram: function () { return program; }, getAutoImportProvider: getAutoImportProvider, + updateIsDefinitionOfReferencedSymbols: updateIsDefinitionOfReferencedSymbols, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, toLineColumnOffset: toLineColumnOffset, @@ -166213,7 +168906,7 @@ var ts; function getDefaultLibFilePath(options) { // Check __dirname is defined and that we are on a node.js system. if (typeof __dirname !== "undefined") { - return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); + return ts.combinePaths(__dirname, ts.getDefaultLibFileName(options)); } throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); } @@ -166255,8 +168948,9 @@ var ts; // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - var start = startNode.decorators ? - ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + var lastDecorator = ts.canHaveDecorators(startNode) ? ts.findLast(startNode.modifiers, ts.isDecorator) : undefined; + var start = lastDecorator ? + ts.skipTrivia(sourceFile.text, lastDecorator.end) : startNode.getStart(sourceFile); return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } @@ -166269,8 +168963,20 @@ var ts; } return spanInNode(otherwiseOnNode); } - function spanInNodeArray(nodeArray) { - return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + function spanInNodeArray(nodeArray, node, match) { + if (nodeArray) { + var index = nodeArray.indexOf(node); + if (index >= 0) { + var start = index; + var end = index + 1; + while (start > 0 && match(nodeArray[start - 1])) + start--; + while (end < nodeArray.length && match(nodeArray[end])) + end++; + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray[start].pos), nodeArray[end - 1].end); + } + } + return textSpan(node); } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); @@ -166383,7 +169089,7 @@ var ts; // span in statement return spanInNode(node.statement); case 165 /* SyntaxKind.Decorator */: - return spanInNodeArray(parent.decorators); + return spanInNodeArray(parent.modifiers, node, ts.isDecorator); case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: return spanInBindingPattern(node); @@ -166546,7 +169252,7 @@ var ts; } // Breakpoint is possible in variableDeclaration only if there is initialization // or its declaration from 'for of' - if (variableDeclaration.initializer || + if ((ts.hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer) || ts.hasSyntacticModifier(variableDeclaration, 1 /* ModifierFlags.Export */) || parent.parent.kind === 244 /* SyntaxKind.ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); @@ -167286,9 +169992,9 @@ var ts; var _this = this; return this.forwardJSONCall("getImplementationAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, options); }); + return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, preferences); }); }; LanguageServiceShimObject.prototype.getSmartSelectionRange = function (fileName, position) { var _this = this; @@ -167513,7 +170219,8 @@ var ts; } return { resolvedFileName: resolvedFileName, - failedLookupLocations: result.failedLookupLocations + failedLookupLocations: result.failedLookupLocations, + affectingLocations: result.affectingLocations, }; }); }; @@ -167592,7 +170299,7 @@ var ts; if (_this.safeList === undefined) { _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); } - return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry); + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports, info.typesRegistry, ts.emptyOptions); }); }; return CoreServicesShimObject; @@ -167714,23 +170421,80 @@ if (typeof process === "undefined" || process.browser) { if (typeof module !== "undefined" && module.exports) { module.exports = ts; } +// The following are deprecations for the public API. Deprecated exports are removed from the compiler itself +// and compatible implementations are added here, along with an appropriate deprecation warning using +// the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. +// +// Deprecations fall into one of three categories: +// +// - "soft" - Soft deprecations are indicated with the `@deprecated` JSDoc Tag. +// - "warn" - Warning deprecations are indicated with the `@deprecated` JSDoc Tag and a diagnostic message (assuming a compatible host). +// - "error" - Error deprecations are either indicated with the `@deprecated` JSDoc tag and will throw a `TypeError` when invoked, or removed from the API entirely. +// +// Once we have determined enough time has passed after a deprecation has been marked as `"warn"` or `"error"`, it will be removed from the public API. +/* @internal */ +var ts; +(function (ts) { + function createOverload(name, overloads, binder, deprecations) { + Object.defineProperty(call, "name", __assign(__assign({}, Object.getOwnPropertyDescriptor(call, "name")), { value: name })); + if (deprecations) { + for (var _i = 0, _a = Object.keys(deprecations); _i < _a.length; _i++) { + var key = _a[_i]; + var index = +key; + if (!isNaN(index) && ts.hasProperty(overloads, "".concat(index))) { + overloads[index] = ts.Debug.deprecate(overloads[index], __assign(__assign({}, deprecations[index]), { name: name })); + } + } + } + var bind = createBinder(overloads, binder); + return call; + function call() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var index = bind(args); + var fn = index !== undefined ? overloads[index] : undefined; + if (typeof fn === "function") { + return fn.apply(void 0, args); + } + throw new TypeError("Invalid arguments"); + } + } + ts.createOverload = createOverload; + function createBinder(overloads, binder) { + return function (args) { + for (var i = 0; ts.hasProperty(overloads, "".concat(i)) && ts.hasProperty(binder, "".concat(i)); i++) { + var fn = binder[i]; + if (fn(args)) { + return i; + } + } + }; + } + // NOTE: We only use this "builder" because we don't infer correctly when calling `createOverload` directly in < TS 4.7, + // but lib is currently at TS 4.4. We can switch to directly calling `createOverload` when we update LKG in main. + function buildOverload(name) { + return { + overload: function (overloads) { return ({ + bind: function (binder) { return ({ + finish: function () { return createOverload(name, overloads, binder); }, + deprecate: function (deprecations) { return ({ + finish: function () { return createOverload(name, overloads, binder, deprecations); } + }); } + }); } + }); } + }; + } + ts.buildOverload = buildOverload; +})(ts || (ts = {})); +// DEPRECATION: Node factory top-level exports +// DEPRECATION PLAN: +// - soft: 4.0 +// - warn: 4.1 +// - error: 5.0 var ts; (function (ts) { - // The following are deprecations for the public API. Deprecated exports are removed from the compiler itself - // and compatible implementations are added here, along with an appropriate deprecation warning using - // the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. - // - // Deprecations fall into one of three categories: - // - // * "soft" - Soft deprecations are indicated with the `@deprecated` JSDoc Tag. - // * "warn" - Warning deprecations are indicated with the `@deprecated` JSDoc Tag and a diagnostic message (assuming a compatible host) - // * "error" - Error deprecations are indicated with the `@deprecated` JSDoc tag and will throw a `TypeError` when invoked. - // DEPRECATION: Node factory top-level exports - // DEPRECATION PLAN: - // - soft: 4.0 - // - warn: 4.1 - // - error: TBD - // #region Node factory top-level exports // NOTE: These exports are deprecated in favor of using a `NodeFactory` instance and exist here purely for backwards compatibility reasons. var factoryDeprecation = { since: "4.0", warnAfter: "4.1", message: "Use the appropriate method on 'ts.factory' or the 'factory' supplied by your transformation context instead." }; /** @deprecated Use `factory.createNodeArray` or the factory supplied by your transformation context instead. */ @@ -168600,13 +171364,14 @@ var ts; ts.setParent(clone, node.parent); return clone; }, { since: "4.0", warnAfter: "4.1", message: "Use an appropriate `factory.update...` method instead, use `setCommentRange` or `setSourceMapRange`, and avoid setting `parent`." }); - // #endregion Node Factory top-level exports - // DEPRECATION: Renamed node tests - // DEPRECATION PLAN: - // - soft: 4.0 - // - warn: 4.1 - // - error: TBD - // #region Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Renamed node tests +// DEPRECATION PLAN: +// - soft: 4.0 +// - warn: 4.1 +// - error: TBD +var ts; +(function (ts) { /** @deprecated Use `isTypeAssertionExpression` instead. */ ts.isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node) { return node.kind === 211 /* SyntaxKind.TypeAssertionExpression */; @@ -168615,13 +171380,14 @@ var ts; warnAfter: "4.1", message: "Use `isTypeAssertionExpression` instead." }); - // #endregion - // DEPRECATION: Renamed node tests - // DEPRECATION PLAN: - // - soft: 4.2 - // - warn: 4.3 - // - error: TBD - // #region Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Renamed node tests +// DEPRECATION PLAN: +// - soft: 4.2 +// - warn: 4.3 +// - error: 5.0 +var ts; +(function (ts) { /** * @deprecated Use `isMemberName` instead. */ @@ -168632,7 +171398,1422 @@ var ts; warnAfter: "4.3", message: "Use `isMemberName` instead." }); - // #endregion Renamed node Tests +})(ts || (ts = {})); +// DEPRECATION: Overloads for createConstructorTypeNode/updateConstructorTypeNode that do not accept 'modifiers' +// DEPRECATION PLAN: +// - soft: 4.2 +// - warn: 4.3 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createConstructorTypeNode = factory.createConstructorTypeNode, updateConstructorTypeNode = factory.updateConstructorTypeNode; + factory.createConstructorTypeNode = ts.buildOverload("createConstructorTypeNode") + .overload({ + 0: function (modifiers, typeParameters, parameters, type) { + return createConstructorTypeNode(modifiers, typeParameters, parameters, type); + }, + 1: function (typeParameters, parameters, type) { + return createConstructorTypeNode(/*modifiers*/ undefined, typeParameters, parameters, type); + }, + }) + .bind({ + 0: function (args) { return args.length === 4; }, + 1: function (args) { return args.length === 3; }, + }) + .deprecate({ + 1: { since: "4.2", warnAfter: "4.3", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + factory.updateConstructorTypeNode = ts.buildOverload("updateConstructorTypeNode") + .overload({ + 0: function (node, modifiers, typeParameters, parameters, type) { + return updateConstructorTypeNode(node, modifiers, typeParameters, parameters, type); + }, + 1: function (node, typeParameters, parameters, type) { + return updateConstructorTypeNode(node, node.modifiers, typeParameters, parameters, type); + } + }) + .bind({ + 0: function (args) { return args.length === 5; }, + 1: function (args) { return args.length === 4; }, + }) + .deprecate({ + 1: { since: "4.2", warnAfter: "4.3", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Overloads to createImportTypeNode/updateImportTypeNode that do not accept `assertions` +// DEPRECATION PLAN: +// - soft: 4.6 +// - warn: 4.7 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createImportTypeNode = factory.createImportTypeNode, updateImportTypeNode = factory.updateImportTypeNode; + factory.createImportTypeNode = ts.buildOverload("createImportTypeNode") + .overload({ + 0: function (argument, assertions, qualifier, typeArguments, isTypeOf) { + return createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf); + }, + 1: function (argument, qualifier, typeArguments, isTypeOf) { + return createImportTypeNode(argument, /*assertions*/ undefined, qualifier, typeArguments, isTypeOf); + }, + }) + .bind({ + 0: function (_a) { + var assertions = _a[1], qualifier = _a[2], typeArguments = _a[3], isTypeOf = _a[4]; + return (assertions === undefined || ts.isImportTypeAssertionContainer(assertions)) && + (qualifier === undefined || !ts.isArray(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + 1: function (_a) { + var qualifier = _a[1], typeArguments = _a[2], isTypeOf = _a[3], other = _a[4]; + return (other === undefined) && + (qualifier === undefined || ts.isEntityName(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + }) + .deprecate({ + 1: { since: "4.6", warnAfter: "4.7", message: "Use the overload that accepts 'assertions'" } + }) + .finish(); + factory.updateImportTypeNode = ts.buildOverload("updateImportTypeNode") + .overload({ + 0: function (node, argument, assertions, qualifier, typeArguments, isTypeOf) { + return updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf); + }, + 1: function (node, argument, qualifier, typeArguments, isTypeOf) { + return updateImportTypeNode(node, argument, node.assertions, qualifier, typeArguments, isTypeOf); + }, + }) + .bind({ + 0: function (_a) { + var assertions = _a[2], qualifier = _a[3], typeArguments = _a[4], isTypeOf = _a[5]; + return (assertions === undefined || ts.isImportTypeAssertionContainer(assertions)) && + (qualifier === undefined || !ts.isArray(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + 1: function (_a) { + var qualifier = _a[2], typeArguments = _a[3], isTypeOf = _a[4], other = _a[5]; + return (other === undefined) && + (qualifier === undefined || ts.isEntityName(qualifier)) && + (typeArguments === undefined || ts.isArray(typeArguments)) && + (isTypeOf === undefined || typeof isTypeOf === "boolean"); + }, + }). + deprecate({ + 1: { since: "4.6", warnAfter: "4.7", message: "Use the overload that accepts 'assertions'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Overloads to createTypeParameter/updateTypeParameter that does not accept `modifiers` +// DEPRECATION PLAN: +// - soft: 4.7 +// - warn: 4.8 +// - error: 5.0 +var ts; +(function (ts) { + function patchNodeFactory(factory) { + var createTypeParameterDeclaration = factory.createTypeParameterDeclaration, updateTypeParameterDeclaration = factory.updateTypeParameterDeclaration; + factory.createTypeParameterDeclaration = ts.buildOverload("createTypeParameterDeclaration") + .overload({ + 0: function (modifiers, name, constraint, defaultType) { + return createTypeParameterDeclaration(modifiers, name, constraint, defaultType); + }, + 1: function (name, constraint, defaultType) { + return createTypeParameterDeclaration(/*modifiers*/ undefined, name, constraint, defaultType); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0]; + return (modifiers === undefined || ts.isArray(modifiers)); + }, + 1: function (_a) { + var name = _a[0]; + return (name !== undefined && !ts.isArray(name)); + }, + }) + .deprecate({ + 1: { since: "4.7", warnAfter: "4.8", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + factory.updateTypeParameterDeclaration = ts.buildOverload("updateTypeParameterDeclaration") + .overload({ + 0: function (node, modifiers, name, constraint, defaultType) { + return updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType); + }, + 1: function (node, name, constraint, defaultType) { + return updateTypeParameterDeclaration(node, node.modifiers, name, constraint, defaultType); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1]; + return (modifiers === undefined || ts.isArray(modifiers)); + }, + 1: function (_a) { + var name = _a[1]; + return (name !== undefined && !ts.isArray(name)); + }, + }) + .deprecate({ + 1: { since: "4.7", warnAfter: "4.8", message: "Use the overload that accepts 'modifiers'" } + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +// DEPRECATION: Deprecate passing `decorators` separate from `modifiers` +// DEPRECATION PLAN: +// - soft: 4.8 +// - warn: 4.9 +// - error: 5.0 +var ts; +(function (ts) { + var MUST_MERGE = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators have been combined with modifiers. Callers should switch to an overload that does not accept a 'decorators' parameter." }; + var DISALLOW_DECORATORS = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators are no longer supported for this function. Callers should switch to an overload that does not accept a 'decorators' parameter." }; + var DISALLOW_DECORATORS_AND_MODIFIERS = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators and modifiers are no longer supported for this function. Callers should switch to an overload that does not accept the 'decorators' and 'modifiers' parameters." }; + function patchNodeFactory(factory) { + var createParameterDeclaration = factory.createParameterDeclaration, updateParameterDeclaration = factory.updateParameterDeclaration, createPropertyDeclaration = factory.createPropertyDeclaration, updatePropertyDeclaration = factory.updatePropertyDeclaration, createMethodDeclaration = factory.createMethodDeclaration, updateMethodDeclaration = factory.updateMethodDeclaration, createConstructorDeclaration = factory.createConstructorDeclaration, updateConstructorDeclaration = factory.updateConstructorDeclaration, createGetAccessorDeclaration = factory.createGetAccessorDeclaration, updateGetAccessorDeclaration = factory.updateGetAccessorDeclaration, createSetAccessorDeclaration = factory.createSetAccessorDeclaration, updateSetAccessorDeclaration = factory.updateSetAccessorDeclaration, createIndexSignature = factory.createIndexSignature, updateIndexSignature = factory.updateIndexSignature, createClassStaticBlockDeclaration = factory.createClassStaticBlockDeclaration, updateClassStaticBlockDeclaration = factory.updateClassStaticBlockDeclaration, createClassExpression = factory.createClassExpression, updateClassExpression = factory.updateClassExpression, createFunctionDeclaration = factory.createFunctionDeclaration, updateFunctionDeclaration = factory.updateFunctionDeclaration, createClassDeclaration = factory.createClassDeclaration, updateClassDeclaration = factory.updateClassDeclaration, createInterfaceDeclaration = factory.createInterfaceDeclaration, updateInterfaceDeclaration = factory.updateInterfaceDeclaration, createTypeAliasDeclaration = factory.createTypeAliasDeclaration, updateTypeAliasDeclaration = factory.updateTypeAliasDeclaration, createEnumDeclaration = factory.createEnumDeclaration, updateEnumDeclaration = factory.updateEnumDeclaration, createModuleDeclaration = factory.createModuleDeclaration, updateModuleDeclaration = factory.updateModuleDeclaration, createImportEqualsDeclaration = factory.createImportEqualsDeclaration, updateImportEqualsDeclaration = factory.updateImportEqualsDeclaration, createImportDeclaration = factory.createImportDeclaration, updateImportDeclaration = factory.updateImportDeclaration, createExportAssignment = factory.createExportAssignment, updateExportAssignment = factory.updateExportAssignment, createExportDeclaration = factory.createExportDeclaration, updateExportDeclaration = factory.updateExportDeclaration; + factory.createParameterDeclaration = ts.buildOverload("createParameterDeclaration") + .overload({ + 0: function (modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer); + }, + 1: function (decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return createParameterDeclaration(ts.concatenate(decorators, modifiers), dotDotDotToken, name, questionToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var dotDotDotToken = _a[1], name = _a[2], questionToken = _a[3], type = _a[4], initializer = _a[5], other = _a[6]; + return (other === undefined) && + (dotDotDotToken === undefined || !ts.isArray(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[1], dotDotDotToken = _a[2], name = _a[3], questionToken = _a[4], type = _a[5], initializer = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (dotDotDotToken === undefined || typeof dotDotDotToken === "object" && ts.isDotDotDotToken(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateParameterDeclaration = ts.buildOverload("updateParameterDeclaration") + .overload({ + 0: function (node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer); + }, + 1: function (node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return updateParameterDeclaration(node, ts.concatenate(decorators, modifiers), dotDotDotToken, name, questionToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var dotDotDotToken = _a[2], name = _a[3], questionToken = _a[4], type = _a[5], initializer = _a[6], other = _a[7]; + return (other === undefined) && + (dotDotDotToken === undefined || !ts.isArray(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[2], dotDotDotToken = _a[3], name = _a[4], questionToken = _a[5], type = _a[6], initializer = _a[7]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (dotDotDotToken === undefined || typeof dotDotDotToken === "object" && ts.isDotDotDotToken(dotDotDotToken)) && + (name === undefined || typeof name === "string" || ts.isBindingName(name)) && + (questionToken === undefined || ts.isQuestionToken(questionToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createPropertyDeclaration = ts.buildOverload("createPropertyDeclaration") + .overload({ + 0: function (modifiers, name, questionOrExclamationToken, type, initializer) { + return createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer); + }, + 1: function (decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return createPropertyDeclaration(ts.concatenate(decorators, modifiers), name, questionOrExclamationToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], questionOrExclamationToken = _a[2], type = _a[3], initializer = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (questionOrExclamationToken === undefined || typeof questionOrExclamationToken === "object" && ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], questionOrExclamationToken = _a[3], type = _a[4], initializer = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionOrExclamationToken === undefined || ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updatePropertyDeclaration = ts.buildOverload("updatePropertyDeclaration") + .overload({ + 0: function (node, modifiers, name, questionOrExclamationToken, type, initializer) { + return updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer); + }, + 1: function (node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { + return updatePropertyDeclaration(node, ts.concatenate(decorators, modifiers), name, questionOrExclamationToken, type, initializer); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], questionOrExclamationToken = _a[3], type = _a[4], initializer = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (questionOrExclamationToken === undefined || typeof questionOrExclamationToken === "object" && ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], questionOrExclamationToken = _a[4], type = _a[5], initializer = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionOrExclamationToken === undefined || ts.isQuestionOrExclamationToken(questionOrExclamationToken)) && + (type === undefined || ts.isTypeNode(type)) && + (initializer === undefined || ts.isExpression(initializer)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createMethodDeclaration = ts.buildOverload("createMethodDeclaration") + .overload({ + 0: function (modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + 1: function (decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return createMethodDeclaration(ts.concatenate(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[1], name = _a[2], questionToken = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7], other = _a[8]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || !ts.some(parameters, ts.isTypeParameterDeclaration)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], asteriskToken = _a[2], name = _a[3], questionToken = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken === "object" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || !ts.isArray(questionToken)) && + (typeParameters === undefined || !ts.some(typeParameters, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateMethodDeclaration = ts.buildOverload("updateMethodDeclaration") + .overload({ + 0: function (node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + 1: function (node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return updateMethodDeclaration(node, ts.concatenate(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[2], name = _a[3], questionToken = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8], other = _a[9]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || typeof questionToken === "object" && ts.isQuestionToken(questionToken)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || !ts.some(parameters, ts.isTypeParameterDeclaration)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], asteriskToken = _a[3], name = _a[4], questionToken = _a[5], typeParameters = _a[6], parameters = _a[7], type = _a[8], body = _a[9]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken === "object" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isPropertyName(name)) && + (questionToken === undefined || !ts.isArray(questionToken)) && + (typeParameters === undefined || !ts.some(typeParameters, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createConstructorDeclaration = ts.buildOverload("createConstructorDeclaration") + .overload({ + 0: function (modifiers, parameters, body) { + return createConstructorDeclaration(modifiers, parameters, body); + }, + 1: function (_decorators, modifiers, parameters, body) { + return createConstructorDeclaration(modifiers, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], parameters = _a[1], body = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || !ts.some(modifiers, ts.isDecorator)) && + (parameters === undefined || !ts.some(parameters, ts.isModifier)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], parameters = _a[2], body = _a[3]; + return (decorators === undefined || !ts.some(decorators, ts.isModifier)) && + (modifiers === undefined || !ts.some(modifiers, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateConstructorDeclaration = ts.buildOverload("updateConstructorDeclaration") + .overload({ + 0: function (node, modifiers, parameters, body) { + return updateConstructorDeclaration(node, modifiers, parameters, body); + }, + 1: function (node, _decorators, modifiers, parameters, body) { + return updateConstructorDeclaration(node, modifiers, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], parameters = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || !ts.some(modifiers, ts.isDecorator)) && + (parameters === undefined || !ts.some(parameters, ts.isModifier)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], parameters = _a[3], body = _a[4]; + return (decorators === undefined || !ts.some(decorators, ts.isModifier)) && + (modifiers === undefined || !ts.some(modifiers, ts.isParameter)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createGetAccessorDeclaration = ts.buildOverload("createGetAccessorDeclaration") + .overload({ + 0: function (modifiers, name, parameters, type, body) { + return createGetAccessorDeclaration(modifiers, name, parameters, type, body); + }, + 1: function (decorators, modifiers, name, parameters, type, body) { + return createGetAccessorDeclaration(ts.concatenate(decorators, modifiers), name, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], parameters = _a[2], type = _a[3], body = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], parameters = _a[3], type = _a[4], body = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateGetAccessorDeclaration = ts.buildOverload("updateGetAccessorDeclaration") + .overload({ + 0: function (node, modifiers, name, parameters, type, body) { + return updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body); + }, + 1: function (node, decorators, modifiers, name, parameters, type, body) { + return updateGetAccessorDeclaration(node, ts.concatenate(decorators, modifiers), name, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], parameters = _a[3], type = _a[4], body = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], parameters = _a[4], type = _a[5], body = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createSetAccessorDeclaration = ts.buildOverload("createSetAccessorDeclaration") + .overload({ + 0: function (modifiers, name, parameters, body) { + return createSetAccessorDeclaration(modifiers, name, parameters, body); + }, + 1: function (decorators, modifiers, name, parameters, body) { + return createSetAccessorDeclaration(ts.concatenate(decorators, modifiers), name, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], parameters = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], parameters = _a[3], body = _a[4]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateSetAccessorDeclaration = ts.buildOverload("updateSetAccessorDeclaration") + .overload({ + 0: function (node, modifiers, name, parameters, body) { + return updateSetAccessorDeclaration(node, modifiers, name, parameters, body); + }, + 1: function (node, decorators, modifiers, name, parameters, body) { + return updateSetAccessorDeclaration(node, ts.concatenate(decorators, modifiers), name, parameters, body); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], parameters = _a[3], body = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], parameters = _a[4], body = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (parameters === undefined || ts.isArray(parameters)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createIndexSignature = ts.buildOverload("createIndexSignature") + .overload({ + 0: function (modifiers, parameters, type) { + return createIndexSignature(modifiers, parameters, type); + }, + 1: function (_decorators, modifiers, parameters, type) { + return createIndexSignature(modifiers, parameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], parameters = _a[1], type = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], parameters = _a[2], type = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateIndexSignature = ts.buildOverload("updateIndexSignature") + .overload({ + 0: function (node, modifiers, parameters, type) { + return updateIndexSignature(node, modifiers, parameters, type); + }, + 1: function (node, _decorators, modifiers, parameters, type) { + return updateIndexSignature(node, modifiers, parameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], parameters = _a[2], type = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], parameters = _a[3], type = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createClassStaticBlockDeclaration = ts.buildOverload("createClassStaticBlockDeclaration") + .overload({ + 0: function (body) { + return createClassStaticBlockDeclaration(body); + }, + 1: function (_decorators, _modifiers, body) { + return createClassStaticBlockDeclaration(body); + }, + }) + .bind({ + 0: function (_a) { + var body = _a[0], other1 = _a[1], other2 = _a[2]; + return (other1 === undefined) && + (other2 === undefined) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], body = _a[2]; + return (decorators === undefined || ts.isArray(decorators)) && + (modifiers === undefined || ts.isArray(decorators)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS_AND_MODIFIERS + }) + .finish(); + factory.updateClassStaticBlockDeclaration = ts.buildOverload("updateClassStaticBlockDeclaration") + .overload({ + 0: function (node, body) { + return updateClassStaticBlockDeclaration(node, body); + }, + 1: function (node, _decorators, _modifiers, body) { + return updateClassStaticBlockDeclaration(node, body); + }, + }) + .bind({ + 0: function (_a) { + var body = _a[1], other1 = _a[2], other2 = _a[3]; + return (other1 === undefined) && + (other2 === undefined) && + (body === undefined || !ts.isArray(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], body = _a[3]; + return (decorators === undefined || ts.isArray(decorators)) && + (modifiers === undefined || ts.isArray(decorators)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS_AND_MODIFIERS + }) + .finish(); + factory.createClassExpression = ts.buildOverload("createClassExpression") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createClassExpression(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createClassExpression(ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateClassExpression = ts.buildOverload("updateClassExpression") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassExpression(node, ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createFunctionDeclaration = ts.buildOverload("createFunctionDeclaration") + .overload({ + 0: function (modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + 1: function (_decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[1], name = _a[2], typeParameters = _a[3], parameters = _a[4], type = _a[5], body = _a[6], other = _a[7]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || typeof name === "string" || ts.isIdentifier(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[1], asteriskToken = _a[2], name = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken !== "string" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateFunctionDeclaration = ts.buildOverload("updateFunctionDeclaration") + .overload({ + 0: function (node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + 1: function (node, _decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + }, + }) + .bind({ + 0: function (_a) { + var asteriskToken = _a[2], name = _a[3], typeParameters = _a[4], parameters = _a[5], type = _a[6], body = _a[7], other = _a[8]; + return (other === undefined) && + (asteriskToken === undefined || !ts.isArray(asteriskToken)) && + (name === undefined || ts.isIdentifier(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (parameters === undefined || ts.every(parameters, ts.isParameter)) && + (type === undefined || !ts.isArray(type)) && + (body === undefined || ts.isBlock(body)); + }, + 1: function (_a) { + var modifiers = _a[2], asteriskToken = _a[3], name = _a[4], typeParameters = _a[5], parameters = _a[6], type = _a[7], body = _a[8]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (asteriskToken === undefined || typeof asteriskToken !== "string" && ts.isAsteriskToken(asteriskToken)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (parameters === undefined || ts.isArray(parameters)) && + (type === undefined || ts.isTypeNode(type)) && + (body === undefined || ts.isBlock(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createClassDeclaration = ts.buildOverload("createClassDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createClassDeclaration(ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function () { return true; }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.updateClassDeclaration = ts.buildOverload("updateClassDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isClassElement)); + }, + 1: function (_a) { + var modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: MUST_MERGE + }) + .finish(); + factory.createInterfaceDeclaration = ts.buildOverload("createInterfaceDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, heritageClauses, members) { + return createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (_decorators, modifiers, name, typeParameters, heritageClauses, members) { + return createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], typeParameters = _a[2], heritageClauses = _a[3], members = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateInterfaceDeclaration = ts.buildOverload("updateInterfaceDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, heritageClauses, members) { + return updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + 1: function (node, _decorators, modifiers, name, typeParameters, heritageClauses, members) { + return updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], heritageClauses = _a[4], members = _a[5], other = _a[6]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], typeParameters = _a[4], heritageClauses = _a[5], members = _a[6]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.every(typeParameters, ts.isTypeParameterDeclaration)) && + (heritageClauses === undefined || ts.every(heritageClauses, ts.isHeritageClause)) && + (members === undefined || ts.every(members, ts.isTypeElement)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createTypeAliasDeclaration = ts.buildOverload("createTypeAliasDeclaration") + .overload({ + 0: function (modifiers, name, typeParameters, type) { + return createTypeAliasDeclaration(modifiers, name, typeParameters, type); + }, + 1: function (_decorators, modifiers, name, typeParameters, type) { + return createTypeAliasDeclaration(modifiers, name, typeParameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], typeParameters = _a[2], type = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], typeParameters = _a[3], type = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateTypeAliasDeclaration = ts.buildOverload("updateTypeAliasDeclaration") + .overload({ + 0: function (node, modifiers, name, typeParameters, type) { + return updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type); + }, + 1: function (node, _decorators, modifiers, name, typeParameters, type) { + return updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], typeParameters = _a[3], type = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || !ts.isArray(type)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], typeParameters = _a[4], type = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (typeParameters === undefined || ts.isArray(typeParameters)) && + (type === undefined || ts.isTypeNode(type)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createEnumDeclaration = ts.buildOverload("createEnumDeclaration") + .overload({ + 0: function (modifiers, name, members) { + return createEnumDeclaration(modifiers, name, members); + }, + 1: function (_decorators, modifiers, name, members) { + return createEnumDeclaration(modifiers, name, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], members = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], members = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateEnumDeclaration = ts.buildOverload("updateEnumDeclaration") + .overload({ + 0: function (node, modifiers, name, members) { + return updateEnumDeclaration(node, modifiers, name, members); + }, + 1: function (node, _decorators, modifiers, name, members) { + return updateEnumDeclaration(node, modifiers, name, members); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], members = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], members = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name === undefined || !ts.isArray(name)) && + (members === undefined || ts.isArray(members)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createModuleDeclaration = ts.buildOverload("createModuleDeclaration") + .overload({ + 0: function (modifiers, name, body, flags) { + return createModuleDeclaration(modifiers, name, body, flags); + }, + 1: function (_decorators, modifiers, name, body, flags) { + return createModuleDeclaration(modifiers, name, body, flags); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], name = _a[1], body = _a[2], flags = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name !== undefined && !ts.isArray(name)) && + (body === undefined || ts.isModuleBody(body)) && + (flags === undefined || typeof flags === "number"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], name = _a[2], body = _a[3], flags = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name !== undefined && ts.isModuleName(name)) && + (body === undefined || typeof body === "object") && + (flags === undefined || typeof flags === "number"); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateModuleDeclaration = ts.buildOverload("updateModuleDeclaration") + .overload({ + 0: function (node, modifiers, name, body) { + return updateModuleDeclaration(node, modifiers, name, body); + }, + 1: function (node, _decorators, modifiers, name, body) { + return updateModuleDeclaration(node, modifiers, name, body); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], name = _a[2], body = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (name === undefined || !ts.isArray(name)) && + (body === undefined || ts.isModuleBody(body)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], name = _a[3], body = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (name !== undefined && ts.isModuleName(name)) && + (body === undefined || ts.isModuleBody(body)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createImportEqualsDeclaration = ts.buildOverload("createImportEqualsDeclaration") + .overload({ + 0: function (modifiers, isTypeOnly, name, moduleReference) { + return createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference); + }, + 1: function (_decorators, modifiers, isTypeOnly, name, moduleReference) { + return createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isTypeOnly = _a[1], name = _a[2], moduleReference = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name !== "boolean") && + (typeof moduleReference !== "string"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isTypeOnly = _a[2], name = _a[3], moduleReference = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name === "string" || ts.isIdentifier(name)) && + (moduleReference !== undefined && ts.isModuleReference(moduleReference)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateImportEqualsDeclaration = ts.buildOverload("updateImportEqualsDeclaration") + .overload({ + 0: function (node, modifiers, isTypeOnly, name, moduleReference) { + return updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference); + }, + 1: function (node, _decorators, modifiers, isTypeOnly, name, moduleReference) { + return updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], isTypeOnly = _a[2], name = _a[3], moduleReference = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name !== "boolean") && + (typeof moduleReference !== "string"); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], isTypeOnly = _a[3], name = _a[4], moduleReference = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isTypeOnly === undefined || typeof isTypeOnly === "boolean") && + (typeof name === "string" || ts.isIdentifier(name)) && + (moduleReference !== undefined && ts.isModuleReference(moduleReference)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createImportDeclaration = ts.buildOverload("createImportDeclaration") + .overload({ + 0: function (modifiers, importClause, moduleSpecifier, assertClause) { + return createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + }, + 1: function (_decorators, modifiers, importClause, moduleSpecifier, assertClause) { + return createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], importClause = _a[1], moduleSpecifier = _a[2], assertClause = _a[3], other = _a[4]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (importClause === undefined || !ts.isArray(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], importClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (importClause === undefined || ts.isImportClause(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateImportDeclaration = ts.buildOverload("updateImportDeclaration") + .overload({ + 0: function (node, modifiers, importClause, moduleSpecifier, assertClause) { + return updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause); + }, + 1: function (node, _decorators, modifiers, importClause, moduleSpecifier, assertClause) { + return updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], importClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (importClause === undefined || !ts.isArray(importClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], importClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (importClause === undefined || ts.isImportClause(importClause)) && + (moduleSpecifier !== undefined && ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createExportAssignment = ts.buildOverload("createExportAssignment") + .overload({ + 0: function (modifiers, isExportEquals, expression) { + return createExportAssignment(modifiers, isExportEquals, expression); + }, + 1: function (_decorators, modifiers, isExportEquals, expression) { + return createExportAssignment(modifiers, isExportEquals, expression); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isExportEquals = _a[1], expression = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (isExportEquals === undefined || typeof isExportEquals === "boolean") && + (typeof expression === "object"); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isExportEquals = _a[2], expression = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (isExportEquals === undefined || typeof isExportEquals === "boolean") && + (expression !== undefined && ts.isExpression(expression)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateExportAssignment = ts.buildOverload("updateExportAssignment") + .overload({ + 0: function (node, modifiers, expression) { + return updateExportAssignment(node, modifiers, expression); + }, + 1: function (node, _decorators, modifiers, expression) { + return updateExportAssignment(node, modifiers, expression); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], expression = _a[2], other = _a[3]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (expression !== undefined && !ts.isArray(expression)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], expression = _a[3]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (expression !== undefined && ts.isExpression(expression)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.createExportDeclaration = ts.buildOverload("createExportDeclaration") + .overload({ + 0: function (modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + 1: function (_decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[0], isTypeOnly = _a[1], exportClause = _a[2], moduleSpecifier = _a[3], assertClause = _a[4], other = _a[5]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (typeof isTypeOnly === "boolean") && + (typeof exportClause !== "boolean") && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[0], modifiers = _a[1], isTypeOnly = _a[2], exportClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (typeof isTypeOnly === "boolean") && + (exportClause === undefined || ts.isNamedExportBindings(exportClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + factory.updateExportDeclaration = ts.buildOverload("updateExportDeclaration") + .overload({ + 0: function (node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + 1: function (node, _decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + }, + }) + .bind({ + 0: function (_a) { + var modifiers = _a[1], isTypeOnly = _a[2], exportClause = _a[3], moduleSpecifier = _a[4], assertClause = _a[5], other = _a[6]; + return (other === undefined) && + (modifiers === undefined || ts.every(modifiers, ts.isModifier)) && + (typeof isTypeOnly === "boolean") && + (typeof exportClause !== "boolean") && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + 1: function (_a) { + var decorators = _a[1], modifiers = _a[2], isTypeOnly = _a[3], exportClause = _a[4], moduleSpecifier = _a[5], assertClause = _a[6]; + return (decorators === undefined || ts.every(decorators, ts.isDecorator)) && + (modifiers === undefined || ts.isArray(modifiers)) && + (typeof isTypeOnly === "boolean") && + (exportClause === undefined || ts.isNamedExportBindings(exportClause)) && + (moduleSpecifier === undefined || ts.isExpression(moduleSpecifier)) && + (assertClause === undefined || ts.isAssertClause(assertClause)); + }, + }) + .deprecate({ + 1: DISALLOW_DECORATORS + }) + .finish(); + } + // Patch `createNodeFactory` because it creates the factories that are provided to transformers + // in the public API. + var prevCreateNodeFactory = ts.createNodeFactory; + // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier + ts.createNodeFactory = function (flags, baseFactory) { + var factory = prevCreateNodeFactory(flags, baseFactory); + patchNodeFactory(factory); + return factory; + }; + // Patch `ts.factory` because its public + patchNodeFactory(ts.factory); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + if (typeof console !== "undefined") { + ts.Debug.loggingHost = { + log: function (level, s) { + switch (level) { + case ts.LogLevel.Error: return console.error(s); + case ts.LogLevel.Warning: return console.warn(s); + case ts.LogLevel.Info: return console.log(s); + case ts.LogLevel.Verbose: return console.log(s); + } + } + }; + } })(ts || (ts = {})); //# sourceMappingURL=typescriptServices.js.map diff --git a/tsserver/typingsInstaller.js b/tsserver/typingsInstaller.js index 38ae0d01..8ab14c82 100644 --- a/tsserver/typingsInstaller.js +++ b/tsserver/typingsInstaller.js @@ -85,11 +85,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.7"; + ts.versionMajorMinor = "4.8"; // 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 = "4.7.2"; + ts.version = "4.8.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -295,8 +295,10 @@ var ts; return true; } ts.every = every; - function find(array, predicate) { - for (var i = 0; i < array.length; i++) { + function find(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { var value = array[i]; if (predicate(value, i)) { return value; @@ -305,8 +307,10 @@ var ts; return undefined; } ts.find = find; - function findLast(array, predicate) { - for (var i = array.length - 1; i >= 0; i--) { + function findLast(array, predicate, startIndex) { + if (array === undefined) + return undefined; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { var value = array[i]; if (predicate(value, i)) { return value; @@ -317,7 +321,9 @@ var ts; ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate, startIndex) { - for (var i = startIndex || 0; i < array.length; i++) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -326,7 +332,9 @@ var ts; } ts.findIndex = findIndex; function findLastIndex(array, predicate, startIndex) { - for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (array === undefined) + return -1; + for (var i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { if (predicate(array[i], i)) { return i; } @@ -1104,7 +1112,7 @@ var ts; * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return array.length === 0 ? undefined : array[0]; + return array === undefined || array.length === 0 ? undefined : array[0]; } ts.firstOrUndefined = firstOrUndefined; function first(array) { @@ -1116,7 +1124,7 @@ var ts; * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return array.length === 0 ? undefined : array[array.length - 1]; + return array === undefined || array.length === 0 ? undefined : array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; function last(array) { @@ -1457,6 +1465,43 @@ var ts; return createMultiMap(); } ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; + function createQueue(items) { + var elements = (items === null || items === void 0 ? void 0 : items.slice()) || []; + var headIndex = 0; + function isEmpty() { + return headIndex === elements.length; + } + function enqueue() { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + elements.push.apply(elements, items); + } + function dequeue() { + if (isEmpty()) { + throw new Error("Queue is empty"); + } + var result = elements[headIndex]; + elements[headIndex] = undefined; // Don't keep referencing dequeued item + headIndex++; + // If more than half of the queue is empty, copy the remaining elements to the + // front and shrink the array (unless we'd be saving fewer than 100 slots) + if (headIndex > 100 && headIndex > (elements.length >> 1)) { + var newLength = elements.length - headIndex; + elements.copyWithin(/*target*/ 0, /*start*/ headIndex); + elements.length = newLength; + headIndex = 0; + } + return result; + } + return { + enqueue: enqueue, + dequeue: dequeue, + isEmpty: isEmpty, + }; + } + ts.createQueue = createQueue; /** * Creates a Set with custom equality and hash code functionality. This is useful when you * want to use something looser than object identity - e.g. "has the same span". @@ -1645,6 +1690,10 @@ var ts; /** Does nothing. */ function noop(_) { } ts.noop = noop; + ts.noopPush = { + push: noop, + length: 0 + }; /** Do nothing and return false */ function returnFalse() { return false; @@ -2000,7 +2049,7 @@ var ts; * and 1 insertion/deletion at 3 characters) */ function getSpellingSuggestion(name, candidates, getName) { - var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var maximumLengthDifference = Math.max(2, Math.floor(name.length * 0.34)); var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother. var bestCandidate; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { @@ -2227,6 +2276,7 @@ var ts; startsWith(candidate, prefix) && endsWith(candidate, suffix); } + ts.isPatternMatch = isPatternMatch; function and(f, g) { return function (arg) { return f(arg) && g(arg); }; } @@ -2419,6 +2469,7 @@ var ts; var currentAssertionLevel = 0 /* AssertionLevel.None */; Debug.currentLogLevel = LogLevel.Warning; Debug.isDebugging = false; + Debug.enableDeprecationWarnings = true; function getTypeScriptVersion() { return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version)); } @@ -2637,7 +2688,7 @@ var ts; return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; } if (isFlags) { - var result = ""; + var result = []; var remainingFlags = value; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var _a = members_1[_i], enumValue = _a[0], enumName = _a[1]; @@ -2645,12 +2696,12 @@ var ts; break; } if (enumValue !== 0 && enumValue & value) { - result = "".concat(result).concat(result ? "|" : "").concat(enumName); + result.push(enumName); remainingFlags &= ~enumValue; } } if (remainingFlags === 0) { - return result; + return result.join("|"); } } else { @@ -2664,7 +2715,15 @@ var ts; return value.toString(); } Debug.formatEnum = formatEnum; + var enumMemberCache = new ts.Map(); function getEnumMembers(enumObject) { + // Assuming enum objects do not change at runtime, we can cache the enum members list + // to reuse later. This saves us from reconstructing this each and every time we call + // a formatting function (which can be expensive for large enums like SyntaxKind). + var existing = enumMemberCache.get(enumObject); + if (existing) { + return existing; + } var result = []; for (var name in enumObject) { var value = enumObject[name]; @@ -2672,7 +2731,9 @@ var ts; result.push([value, name]); } } - return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + var sorted = ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + enumMemberCache.set(enumObject, sorted); + return sorted; } function formatSyntaxKind(kind) { return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); @@ -2718,6 +2779,22 @@ var ts; return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true); } Debug.formatFlowFlags = formatFlowFlags; + function formatRelationComparisonResult(result) { + return formatEnum(result, ts.RelationComparisonResult, /*isFlags*/ true); + } + Debug.formatRelationComparisonResult = formatRelationComparisonResult; + function formatCheckMode(mode) { + return formatEnum(mode, ts.CheckMode, /*isFlags*/ true); + } + Debug.formatCheckMode = formatCheckMode; + function formatSignatureCheckMode(mode) { + return formatEnum(mode, ts.SignatureCheckMode, /*isFlags*/ true); + } + Debug.formatSignatureCheckMode = formatSignatureCheckMode; + function formatTypeFacts(facts) { + return formatEnum(facts, ts.TypeFacts, /*isFlags*/ true); + } + Debug.formatTypeFacts = formatTypeFacts; var isDebugInfoEnabled = false; var extendedDebugModule; function extendedDebug() { @@ -3016,7 +3093,7 @@ var ts; function createWarningDeprecation(name, errorAfter, since, message) { var hasWrittenDeprecation = false; return function () { - if (!hasWrittenDeprecation) { + if (Debug.enableDeprecationWarnings && !hasWrittenDeprecation) { log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message)); hasWrittenDeprecation = true; } @@ -3035,6 +3112,7 @@ var ts; warn ? createWarningDeprecation(name, errorAfter, since, options.message) : ts.noop; } + Debug.createDeprecation = createDeprecation; function wrapFunction(deprecation, func) { return function () { deprecation(); @@ -3042,10 +3120,53 @@ var ts; }; } function deprecate(func, options) { - var deprecation = createDeprecation(getFunctionName(func), options); + var _a; + var deprecation = createDeprecation((_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : getFunctionName(func), options); return wrapFunction(deprecation, func); } Debug.deprecate = deprecate; + function formatVariance(varianceFlags) { + var variance = varianceFlags & 7 /* VarianceFlags.VarianceMask */; + var result = variance === 0 /* VarianceFlags.Invariant */ ? "in out" : + variance === 3 /* VarianceFlags.Bivariant */ ? "[bivariant]" : + variance === 2 /* VarianceFlags.Contravariant */ ? "in" : + variance === 1 /* VarianceFlags.Covariant */ ? "out" : + variance === 4 /* VarianceFlags.Independent */ ? "[independent]" : ""; + if (varianceFlags & 8 /* VarianceFlags.Unmeasurable */) { + result += " (unmeasurable)"; + } + else if (varianceFlags & 16 /* VarianceFlags.Unreliable */) { + result += " (unreliable)"; + } + return result; + } + Debug.formatVariance = formatVariance; + var DebugTypeMapper = /** @class */ (function () { + function DebugTypeMapper() { + } + DebugTypeMapper.prototype.__debugToString = function () { + var _a; + type(this); + switch (this.kind) { + case 3 /* TypeMapKind.Function */: return ((_a = this.debugInfo) === null || _a === void 0 ? void 0 : _a.call(this)) || "(function mapper)"; + case 0 /* TypeMapKind.Simple */: return "".concat(this.source.__debugTypeToString(), " -> ").concat(this.target.__debugTypeToString()); + case 1 /* TypeMapKind.Array */: return ts.zipWith(this.sources, this.targets || ts.map(this.sources, function () { return "any"; }), function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(typeof t === "string" ? t : t.__debugTypeToString()); }).join(", "); + case 2 /* TypeMapKind.Deferred */: return ts.zipWith(this.sources, this.targets, function (s, t) { return "".concat(s.__debugTypeToString(), " -> ").concat(t().__debugTypeToString()); }).join(", "); + case 5 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: return "m1: ".concat(this.mapper1.__debugToString().split("\n").join("\n "), "\nm2: ").concat(this.mapper2.__debugToString().split("\n").join("\n ")); + default: return assertNever(this); + } + }; + return DebugTypeMapper; + }()); + Debug.DebugTypeMapper = DebugTypeMapper; + function attachDebugPrototypeIfDebug(mapper) { + if (Debug.isDebugging) { + return Object.setPrototypeOf(mapper, DebugTypeMapper.prototype); + } + return mapper; + } + Debug.attachDebugPrototypeIfDebug = attachDebugPrototypeIfDebug; })(Debug = ts.Debug || (ts.Debug = {})); })(ts || (ts = {})); /* @internal */ @@ -3787,9 +3908,9 @@ var ts; eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } tracingEnabled.push = push; - function pop() { + function pop(results) { ts.Debug.assert(eventStack.length > 0); - writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); + writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp(), results); eventStack.length--; } tracingEnabled.pop = pop; @@ -3803,14 +3924,15 @@ var ts; tracingEnabled.popAll = popAll; // sample every 10ms var sampleInterval = 1000 * 10; - function writeStackEvent(index, endTime) { + function writeStackEvent(index, endTime, results) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { + ts.Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`"); writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } // test if [time,endTime) straddles a sampling point else if (sampleInterval - (time % sampleInterval) <= endTime - time) { - writeEvent("X", phase, name, args, "\"dur\":".concat(endTime - time), time); + writeEvent("X", phase, name, __assign(__assign({}, args), { results: results }), "\"dur\":".concat(endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { @@ -4309,6 +4431,7 @@ var ts; SyntaxKind[SyntaxKind["JSDocFunctionType"] = 317] = "JSDocFunctionType"; SyntaxKind[SyntaxKind["JSDocVariadicType"] = 318] = "JSDocVariadicType"; SyntaxKind[SyntaxKind["JSDocNamepathType"] = 319] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; /** @deprecated Use SyntaxKind.JSDoc */ SyntaxKind[SyntaxKind["JSDocComment"] = 320] = "JSDocComment"; SyntaxKind[SyntaxKind["JSDocText"] = 321] = "JSDocText"; @@ -4383,7 +4506,6 @@ var ts; SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 347] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 126] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 160] = "LastContextualKeyword"; - SyntaxKind[SyntaxKind["JSDoc"] = 320] = "JSDoc"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4457,6 +4579,7 @@ var ts; ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["In"] = 32768] = "In"; ModifierFlags[ModifierFlags["Out"] = 65536] = "Out"; + ModifierFlags[ModifierFlags["Decorator"] = 131072] = "Decorator"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. @@ -4464,7 +4587,8 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 116958] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 125951] = "All"; + ModifierFlags[ModifierFlags["All"] = 257023] = "All"; + ModifierFlags[ModifierFlags["Modifier"] = 125951] = "Modifier"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4649,6 +4773,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + NodeBuilderFlags[NodeBuilderFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; @@ -4689,6 +4814,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; + TypeFormatFlags[TypeFormatFlags["OmitThisParameter"] = 33554432] = "OmitThisParameter"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -4700,7 +4826,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 848330091] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -5089,6 +5215,11 @@ var ts; // Flags that require TypeFlags.Union /* @internal */ ObjectFlags[ObjectFlags["ContainsIntersections"] = 16777216] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnionComputed"] = 33554432] = "IsUnknownLikeUnionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsUnknownLikeUnion"] = 67108864] = "IsUnknownLikeUnion"; + /* @internal */ // Flags that require TypeFlags.Intersection /* @internal */ ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 16777216] = "IsNeverIntersectionComputed"; @@ -5174,9 +5305,10 @@ var ts; (function (TypeMapKind) { TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple"; TypeMapKind[TypeMapKind["Array"] = 1] = "Array"; - TypeMapKind[TypeMapKind["Function"] = 2] = "Function"; - TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite"; - TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged"; + TypeMapKind[TypeMapKind["Deferred"] = 2] = "Deferred"; + TypeMapKind[TypeMapKind["Function"] = 3] = "Function"; + TypeMapKind[TypeMapKind["Composite"] = 4] = "Composite"; + TypeMapKind[TypeMapKind["Merged"] = 5] = "Merged"; })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {})); var InferencePriority; (function (InferencePriority) { @@ -5555,25 +5687,24 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 4096] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; - TransformFlags[TransformFlags["ContainsLexicalSuper"] = 33554432] = "ContainsLexicalSuper"; - TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 67108864] = "ContainsUpdateExpressionForIdentifier"; - // Please leave this as 1 << 29. - // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. - // It is a good reminder of how much room we have left - TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 8192] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 32768] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 65536] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 131072] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 262144] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 524288] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 1048576] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 2097152] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 4194304] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 8388608] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 16777216] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsDecorators"] = 33554432] = "ContainsDecorators"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 67108864] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsLexicalSuper"] = 134217728] = "ContainsLexicalSuper"; + TransformFlags[TransformFlags["ContainsUpdateExpressionForIdentifier"] = 268435456] = "ContainsUpdateExpressionForIdentifier"; + TransformFlags[TransformFlags["ContainsPrivateIdentifierInExpression"] = 536870912] = "ContainsPrivateIdentifierInExpression"; + TransformFlags[TransformFlags["HasComputedFlags"] = -2147483648] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; @@ -5592,27 +5723,27 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 591310848] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 591306752] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 574529536] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 570433536] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 589443072] = "ModuleExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = -2147483648] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = -2147483648] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = -2147483648] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = -2072174592] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = -1937940480] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = -1937948672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = -2005057536] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = -2013249536] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = -2147344384] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = -1941676032] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; - TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 33562624] = "ContainsLexicalThisOrSuper"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = -2147278848] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = -2147450880] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = -2146893824] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = -2147483648] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = -2147418112] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = -2147450880] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ContainsLexicalThisOrSuper"] = 134234112] = "ContainsLexicalThisOrSuper"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 33562624] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 134234112] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -5785,7 +5916,7 @@ var ts; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; + ListFormat[ListFormat["Modifiers"] = 2359808] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers"; ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers"; @@ -6180,7 +6311,7 @@ var ts; }; } function createDirectoryWatcher(dirName, dirPath, fallbackOptions) { - var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName) { + var watcher = fsWatch(dirName, 1 /* FileSystemEntryKind.Directory */, function (_eventName, relativeFileName, modifiedTime) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" if (!ts.isString(relativeFileName)) return; @@ -6190,7 +6321,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName, FileWatcherEventKind.Changed); + fileCallback(fileName, FileWatcherEventKind.Changed, modifiedTime); } } }, @@ -6244,7 +6375,7 @@ var ts; } else { cache.set(path, { - watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options), + watcher: watchFile(fileName, function (fileName, eventKind, modifiedTime) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind, modifiedTime); }); }, pollingInterval, options), refCount: 1 }); } @@ -6272,7 +6403,8 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); + // Pass modified times so tsc --build can use it + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime), modifiedTime); return true; } return false; @@ -6307,7 +6439,7 @@ var ts; */ /*@internal*/ function createDirectoryWatcherSupportingRecursive(_a) { - var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, directoryExists = _a.directoryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; + var watchDirectory = _a.watchDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, fileSystemEntryExists = _a.fileSystemEntryExists, realpath = _a.realpath, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; var cache = new ts.Map(); var callbackCache = ts.createMultiMap(); var cacheToUpdateChildWatches = new ts.Map(); @@ -6407,7 +6539,7 @@ var ts; function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) { // Iterate through existing children and update the watches if needed var parentWatcher = cache.get(dirPath); - if (parentWatcher && directoryExists(dirName)) { + if (parentWatcher && fileSystemEntryExists(dirName, 1 /* FileSystemEntryKind.Directory */)) { // Schedule the update and postpone invoke for callbacks scheduleUpdateChildWatches(dirName, dirPath, fileName, options); return; @@ -6480,7 +6612,7 @@ var ts; if (!parentWatcher) return false; var newChildWatches; - var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { + var hasChanges = ts.enumerateInsertsAndDeletes(fileSystemEntryExists(parentDir, 1 /* FileSystemEntryKind.Directory */) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch @@ -6523,17 +6655,19 @@ var ts; })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {})); /*@internal*/ function createFileWatcherCallback(callback) { - return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); }; + return function (_fileName, eventKind, modifiedTime) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", "", modifiedTime); }; } ts.createFileWatcherCallback = createFileWatcherCallback; - function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) { - return function (eventName) { + function createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime) { + return function (eventName, _relativeFileName, modifiedTime) { if (eventName === "rename") { - callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted); + // Check time stamps rather than file system entry checks + modifiedTime || (modifiedTime = getModifiedTime(fileName) || ts.missingFileModifiedTime); + callback(fileName, modifiedTime !== ts.missingFileModifiedTime ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted, modifiedTime); } else { // Change - callback(fileName, FileWatcherEventKind.Changed); + callback(fileName, FileWatcherEventKind.Changed, modifiedTime); } }; } @@ -6557,11 +6691,12 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; + var pollingWatchFile = _a.pollingWatchFile, 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 dynamicPollingWatchFile; var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; + var hitSystemWatcherLimit = false; return { watchFile: watchFile, watchDirectory: watchDirectory @@ -6579,7 +6714,7 @@ var ts; case ts.WatchFileKind.FixedChunkSizePolling: return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: - return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), + return fsWatch(fileName, 0 /* FileSystemEntryKind.File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); case ts.WatchFileKind.UseFsEventsOnParentDirectory: if (!nonPollingWatchFile) { @@ -6640,7 +6775,7 @@ var ts; hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - directoryExists: directoryExists, + fileSystemEntryExists: fileSystemEntryExists, getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories, watchDirectory: nonRecursiveWatchDirectory, realpath: realpath, @@ -6691,6 +6826,124 @@ var ts; }; } } + function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { + var lastDirectoryPartWithDirectorySeparator; + var lastDirectoryPart; + if (inodeWatching) { + lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substring(fileOrDirectory.lastIndexOf(ts.directorySeparator)); + lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); + } + /** Watcher for the file system entry depending on whether it is missing or present */ + var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? + watchMissingFileSystemEntry() : + watchPresentFileSystemEntry(); + return { + close: function () { + // Close the watcher (either existing file system entry watcher or missing file system entry watcher) + if (watcher) { + watcher.close(); + watcher = undefined; + } + } + }; + function updateWatcher(createWatcher) { + // If watcher is not closed, update it + if (watcher) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); + watcher.close(); + watcher = createWatcher(); + } + } + /** + * Watch the file or directory that is currently present + * and when the watched file or directory is deleted, switch to missing file system entry watcher + */ + function watchPresentFileSystemEntry() { + if (hitSystemWatcherLimit) { + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + try { + var presentWatcher = fsWatchWorker(fileOrDirectory, recursive, inodeWatching ? + callbackChangingToMissingFileSystemEntry : + callback); + // Watch the missing file or directory or error + presentWatcher.on("error", function () { + callback("rename", ""); + updateWatcher(watchMissingFileSystemEntry); + }); + return presentWatcher; + } + catch (e) { + // Catch the exception and use polling instead + // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + // so instead of throwing error, use fs.watchFile + hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to watchFile")); + return watchPresentFileSystemEntryWithFsWatchFile(); + } + } + function callbackChangingToMissingFileSystemEntry(event, relativeName) { + // In some scenarios, file save operation fires event with fileName.ext~ instead of fileName.ext + // To ensure we see the file going missing and coming back up (file delete and then recreated) + // and watches being updated correctly we are calling back with fileName.ext as well as fileName.ext~ + // The worst is we have fired event that was not needed but we wont miss any changes + // especially in cases where file goes missing and watches wrong inode + var originalRelativeName; + if (relativeName && ts.endsWith(relativeName, "~")) { + originalRelativeName = relativeName; + relativeName = relativeName.slice(0, relativeName.length - 1); + } + // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations + // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path + if (event === "rename" && + (!relativeName || + relativeName === lastDirectoryPart || + ts.endsWith(relativeName, lastDirectoryPartWithDirectorySeparator))) { + var modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime; + if (originalRelativeName) + callback(event, originalRelativeName, modifiedTime); + callback(event, relativeName, modifiedTime); + if (inodeWatching) { + // If this was rename event, inode has changed means we need to update watcher + updateWatcher(modifiedTime === ts.missingFileModifiedTime ? watchMissingFileSystemEntry : watchPresentFileSystemEntry); + } + else if (modifiedTime === ts.missingFileModifiedTime) { + updateWatcher(watchMissingFileSystemEntry); + } + } + else { + if (originalRelativeName) + callback(event, originalRelativeName); + callback(event, relativeName); + } + } + /** + * Watch the file or directory using fs.watchFile since fs.watch threw exception + * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point + */ + function watchPresentFileSystemEntryWithFsWatchFile() { + return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); + } + /** + * Watch the file or directory that is missing + * and switch to existing file or directory when the missing filesystem entry is created + */ + function watchMissingFileSystemEntry() { + return watchFile(fileOrDirectory, function (_fileName, eventKind, modifiedTime) { + if (eventKind === FileWatcherEventKind.Created) { + modifiedTime || (modifiedTime = getModifiedTime(fileOrDirectory) || ts.missingFileModifiedTime); + if (modifiedTime !== ts.missingFileModifiedTime) { + callback("rename", "", modifiedTime); + // Call the callback for current file or directory + // For now it could be callback for the inner directory creation, + // but just return current directory, better than current no-op + updateWatcher(watchPresentFileSystemEntry); + } + } + }, fallbackPollingInterval, fallbackOptions); + } + } } ts.createSystemWatchFunctions = createSystemWatchFunctions; /** @@ -6728,7 +6981,6 @@ var ts; // not actually work. var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { - var _a; var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/; var _fs = require("fs"); var _path = require("path"); @@ -6738,41 +6990,41 @@ var ts; try { _crypto = require("crypto"); } - catch (_b) { + catch (_a) { _crypto = undefined; } var activeSession; var profilePath = "./profile.cpuprofile"; - var hitSystemWatcherLimit = false; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; + var fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); - var _c = createSystemWatchFunctions({ + var _b = createSystemWatchFunctions({ pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames), getModifiedTime: getModifiedTime, setTimeout: setTimeout, clearTimeout: clearTimeout, - fsWatch: fsWatch, + fsWatchWorker: fsWatchWorker, useCaseSensitiveFileNames: useCaseSensitiveFileNames, getCurrentDirectory: getCurrentDirectory, - fileExists: fileExists, + fileSystemEntryExists: fileSystemEntryExists, // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch, - directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, realpath: realpath, 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); }, - }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; + inodeWatching: isLinuxOrMacOs, + sysLog: sysLog, + }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; var nodeSystem = { args: process.argv.slice(2), newLine: _os.EOL, @@ -7021,110 +7273,14 @@ var ts; // File changed eventKind = FileWatcherEventKind.Changed; } - callback(fileName, eventKind); + callback(fileName, eventKind, curr.mtime); } } - function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { - var options; - var lastDirectoryPartWithDirectorySeparator; - var lastDirectoryPart; - if (isLinuxOrMacOs) { - lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator)); - lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length); - } - /** Watcher for the file system entry depending on whether it is missing or present */ - var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? - watchMissingFileSystemEntry() : - watchPresentFileSystemEntry(); - return { - close: function () { - // Close the watcher (either existing file system entry watcher or missing file system entry watcher) - watcher.close(); - watcher = undefined; - } - }; - /** - * Invoke the callback with rename and update the watcher if not closed - * @param createWatcher - */ - function invokeCallbackAndUpdateWatcher(createWatcher) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); - // Call the callback for current directory - callback("rename", ""); - // If watcher is not closed, update it - if (watcher) { - watcher.close(); - watcher = createWatcher(); - } - } - /** - * Watch the file or directory that is currently present - * and when the watched file or directory is deleted, switch to missing file system entry watcher - */ - function watchPresentFileSystemEntry() { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows - // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) - if (options === undefined) { - if (fsSupportsRecursiveFsWatch) { - options = { persistent: true, recursive: !!recursive }; - } - else { - options = { persistent: true }; - } - } - if (hitSystemWatcherLimit) { - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - try { - var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ? - callbackChangingToMissingFileSystemEntry : - callback); - // Watch the missing file or directory or error - presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); }); - return presentWatcher; - } - catch (e) { - // Catch the exception and use polling instead - // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - // so instead of throwing error, use fs.watchFile - hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); - sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile")); - return watchPresentFileSystemEntryWithFsWatchFile(); - } - } - function callbackChangingToMissingFileSystemEntry(event, relativeName) { - // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations - // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path - return event === "rename" && - (!relativeName || - relativeName === lastDirectoryPart || - (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && - !fileSystemEntryExists(fileOrDirectory, entryKind) ? - invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : - callback(event, relativeName); - } - /** - * Watch the file or directory using fs.watchFile since fs.watch threw exception - * Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point - */ - function watchPresentFileSystemEntryWithFsWatchFile() { - return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); - } - /** - * Watch the file or directory that is missing - * and switch to existing file or directory when the missing filesystem entry is created - */ - function watchMissingFileSystemEntry() { - return watchFile(fileOrDirectory, function (_fileName, eventKind) { - if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) { - // Call the callback for current file or directory - // For now it could be callback for the inner directory creation, - // but just return current directory, better than current no-op - invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry); - } - }, fallbackPollingInterval, fallbackOptions); - } + function fsWatchWorker(fileOrDirectory, recursive, callback) { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + return _fs.watch(fileOrDirectory, fsSupportsRecursiveFsWatch ? + { persistent: true, recursive: !!recursive } : { persistent: true }, callback); } function readFileWorker(fileName, _encoding) { var buffer; @@ -7261,9 +7417,12 @@ var ts; function getDirectories(path) { return getAccessibleFileSystemEntries(path).directories.slice(); } + function fsRealPathHandlingLongPath(path) { + return path.length < 260 ? _fs.realpathSync.native(path) : _fs.realpathSync(path); + } function realpath(path) { try { - return realpathSync(path); + return fsRealpath(path); } catch (_a) { return path; @@ -7271,12 +7430,19 @@ var ts; } function getModifiedTime(path) { var _a; + // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve + // the CPU time performance. + var originalStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; try { return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime; } catch (e) { return undefined; } + finally { + Error.stackTraceLimit = originalStackTraceLimit; + } } function setModifiedTime(path, time) { try { @@ -8131,6 +8297,7 @@ var ts; String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + or_JSX_element_expected: diag(1145, ts.DiagnosticCategory.Error, "or_JSX_element_expected_1145", "'{' or JSX element expected."), Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), @@ -8184,6 +8351,7 @@ var ts; Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), _0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module: diag(1208, ts.DiagnosticCategory.Error, "_0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_imp_1208", "'{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module."), + Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0: diag(1209, ts.DiagnosticCategory.Error, "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209", "Invalid optional chain from new expression. Did you mean to call '{0}()'?"), Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode: diag(1210, ts.DiagnosticCategory.Error, "Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of__1210", "Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of '{0}'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode."), A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), @@ -8276,6 +8444,7 @@ var ts; infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Class_constructor_may_not_be_an_accessor: diag(1341, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_an_accessor_1341", "Class constructor may not be an accessor."), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), @@ -8294,6 +8463,7 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), + Class_constructor_may_not_be_a_generator: diag(1360, ts.DiagnosticCategory.Error, "Class_constructor_may_not_be_a_generator_1360", "Class constructor may not be a generator."), _0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type: diag(1361, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361", "'{0}' cannot be used as a value because it was imported using 'import type'."), _0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type: diag(1362, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362", "'{0}' cannot be used as a value because it was exported using 'export type'."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), @@ -8378,18 +8548,30 @@ var ts; Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, ts.DiagnosticCategory.Message, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."), Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments: diag(1450, ts.DiagnosticCategory.Message, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional assertion as arguments"), Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"), - Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "Resolution modes are only supported when `moduleResolution` is `node16` or `nodenext`."), + resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452", "'resolution-mode' assertions are only supported when `moduleResolution` is `node16` or `nodenext`."), resolution_mode_should_be_either_require_or_import: diag(1453, ts.DiagnosticCategory.Error, "resolution_mode_should_be_either_require_or_import_1453", "`resolution-mode` should be either `require` or `import`."), resolution_mode_can_only_be_set_for_type_only_imports: diag(1454, ts.DiagnosticCategory.Error, "resolution_mode_can_only_be_set_for_type_only_imports_1454", "`resolution-mode` can only be set for type-only imports."), resolution_mode_is_the_only_valid_key_for_type_import_assertions: diag(1455, ts.DiagnosticCategory.Error, "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455", "`resolution-mode` is the only valid key for type import assertions."), Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require: diag(1456, ts.DiagnosticCategory.Error, "Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require_1456", "Type import assertions should have exactly one key - `resolution-mode` - with value `import` or `require`."), + Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk: diag(1457, ts.DiagnosticCategory.Message, "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457", "Matched by default include pattern '**/*'"), + File_is_ECMAScript_module_because_0_has_field_type_with_value_module: diag(1458, ts.DiagnosticCategory.Message, "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458", "File is ECMAScript module because '{0}' has field \"type\" with value \"module\""), + File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module: diag(1459, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459", "File is CommonJS module because '{0}' has field \"type\" whose value is not \"module\""), + File_is_CommonJS_module_because_0_does_not_have_field_type: diag(1460, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_0_does_not_have_field_type_1460", "File is CommonJS module because '{0}' does not have field \"type\""), + File_is_CommonJS_module_because_package_json_was_not_found: diag(1461, ts.DiagnosticCategory.Message, "File_is_CommonJS_module_because_package_json_was_not_found_1461", "File is CommonJS module because 'package.json' was not found"), The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."), - Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."), + Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported with 'require'. Use an ECMAScript import instead."), catch_or_finally_expected: diag(1472, ts.DiagnosticCategory.Error, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), An_import_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1473, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473", "An import declaration can only be used at the top level of a module."), An_export_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1474, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474", "An export declaration can only be used at the top level of a module."), Control_what_method_is_used_to_detect_module_format_JS_files: diag(1475, ts.DiagnosticCategory.Message, "Control_what_method_is_used_to_detect_module_format_JS_files_1475", "Control what method is used to detect module-format JS files."), auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules: diag(1476, ts.DiagnosticCategory.Message, "auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_w_1476", "\"auto\": Treat files with imports, exports, import.meta, jsx (with jsx: react-jsx), or esm format (with module: node16+) as modules."), + An_instantiation_expression_cannot_be_followed_by_a_property_access: diag(1477, ts.DiagnosticCategory.Error, "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477", "An instantiation expression cannot be followed by a property access."), + Identifier_or_string_literal_expected: diag(1478, ts.DiagnosticCategory.Error, "Identifier_or_string_literal_expected_1478", "Identifier or string literal expected."), + The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead: diag(1479, ts.DiagnosticCategory.Error, "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479", "The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import(\"{0}\")' call instead."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module: diag(1480, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480", "To convert this file to an ECMAScript module, change its file extension to '{0}' or create a local package.json file with `{ \"type\": \"module\" }`."), + To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1: diag(1481, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481", "To convert this file to an ECMAScript module, change its file extension to '{0}', or add the field `\"type\": \"module\"` to '{1}'."), + To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0: diag(1482, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0_1482", "To convert this file to an ECMAScript module, add the field `\"type\": \"module\"` to '{0}'."), + To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module: diag(1483, ts.DiagnosticCategory.Message, "To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483", "To convert this file to an ECMAScript module, create a local package.json file with `{ \"type\": \"module\" }`."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8398,8 +8580,11 @@ var ts; Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, ts.DiagnosticCategory.Error, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."), The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, ts.DiagnosticCategory.Error, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."), + This_type_parameter_might_need_an_extends_0_constraint: diag(2208, ts.DiagnosticCategory.Error, "This_type_parameter_might_need_an_extends_0_constraint_2208", "This type parameter might need an `extends {0}` constraint."), The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2209, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_roo_2209", "The project root is ambiguous, but is required to resolve export map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate: diag(2210, ts.DiagnosticCategory.Error, "The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_roo_2210", "The project root is ambiguous, but is required to resolve import map entry '{0}' in file '{1}'. Supply the `rootDir` compiler option to disambiguate."), + Add_extends_constraint: diag(2211, ts.DiagnosticCategory.Message, "Add_extends_constraint_2211", "Add `extends` constraint."), + Add_extends_constraint_to_all_type_parameters: diag(2212, ts.DiagnosticCategory.Message, "Add_extends_constraint_to_all_type_parameters_2212", "Add `extends` constraint to all type parameters"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -8600,6 +8785,7 @@ var ts; Cannot_create_an_instance_of_an_abstract_class: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_an_abstract_class_2511", "Cannot create an instance of an abstract class."), Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + A_tuple_type_cannot_be_indexed_with_a_negative_value: diag(2514, ts.DiagnosticCategory.Error, "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514", "A tuple type cannot be indexed with a negative value."), Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), @@ -8882,6 +9068,12 @@ var ts; Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls: diag(2836, ts.DiagnosticCategory.Error, "Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls_2836", "Import assertions are not allowed on statements that transpile to commonjs 'require' calls."), Import_assertion_values_must_be_string_literal_expressions: diag(2837, ts.DiagnosticCategory.Error, "Import_assertion_values_must_be_string_literal_expressions_2837", "Import assertion values must be string literal expressions."), All_declarations_of_0_must_have_identical_constraints: diag(2838, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_constraints_2838", "All declarations of '{0}' must have identical constraints."), + This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value: diag(2839, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839", "This condition will always return '{0}' since JavaScript compares objects by reference, not value."), + An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes: diag(2840, ts.DiagnosticCategory.Error, "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840", "An interface cannot extend a primitive type like '{0}'; an interface can only extend named types and classes"), + The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(2841, ts.DiagnosticCategory.Error, "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841", "The type of this expression cannot be named without a 'resolution-mode' assertion, which is an unstable feature. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + _0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation: diag(2842, ts.DiagnosticCategory.Error, "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842", "'{0}' is an unused renaming of '{1}'. Did you intend to use it as a type annotation?"), + We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here: diag(2843, ts.DiagnosticCategory.Error, "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843", "We can only write a type for '{0}' by adding a type for the entire parameter here."), + Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2844, ts.DiagnosticCategory.Error, "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844", "Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8989,7 +9181,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), - Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "Resolution mode assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), + resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4125, ts.DiagnosticCategory.Error, "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125", "'resolution-mode' assertions are unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -9292,8 +9484,8 @@ var ts; Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), Referenced_project_0_may_not_disable_emit: diag(6310, ts.DiagnosticCategory.Error, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."), - Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), - Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_1_is_older_than_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350", "Project '{0}' is out of date because output '{1}' is older than input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than output '{2}'"), Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), @@ -9337,6 +9529,8 @@ var ts; Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3: diag(6396, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6396", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_successfully_resolved_to_3_with_Package_ID_4: diag(6397, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_succes_6397", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was successfully resolved to '{3}' with Package ID '{4}'."), Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_resolved: diag(6398, ts.DiagnosticCategory.Message, "Reusing_resolution_of_type_reference_directive_0_from_1_found_in_cache_from_location_2_it_was_not_re_6398", "Reusing resolution of type reference directive '{0}' from '{1}' found in cache from location '{2}', it was not resolved."), + 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"), 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."), @@ -9577,6 +9771,8 @@ var ts; Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, ts.DiagnosticCategory.Error, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."), The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."), + You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder: diag(8035, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035", "You cannot rename elements that are defined in a 'node_modules' folder."), + You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, ts.DiagnosticCategory.Error, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -9847,6 +10043,9 @@ var ts; For_await_loops_cannot_be_used_inside_a_class_static_block: diag(18038, ts.DiagnosticCategory.Error, "For_await_loops_cannot_be_used_inside_a_class_static_block_18038", "'For await' loops cannot be used inside a class static block."), Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block: diag(18039, ts.DiagnosticCategory.Error, "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039", "Invalid use of '{0}'. It cannot be used inside a class static block."), A_return_statement_cannot_be_used_inside_a_class_static_block: diag(18041, ts.DiagnosticCategory.Error, "A_return_statement_cannot_be_used_inside_a_class_static_block_18041", "A 'return' statement cannot be used inside a class static block."), + _0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation: diag(18042, ts.DiagnosticCategory.Error, "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042", "'{0}' is a type and cannot be imported in JavaScript files. Use '{1}' in a JSDoc type annotation."), + Types_cannot_appear_in_export_declarations_in_JavaScript_files: diag(18043, ts.DiagnosticCategory.Error, "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043", "Types cannot appear in export declarations in JavaScript files."), + _0_is_automatically_exported_here: diag(18044, ts.DiagnosticCategory.Message, "_0_is_automatically_exported_here_18044", "'{0}' is automatically exported here."), }; })(ts || (ts = {})); var ts; @@ -12734,6 +12933,18 @@ var ts; } } ts.getAssignedName = getAssignedName; + function getDecorators(node) { + if (ts.hasDecorators(node)) { + return ts.filter(node.modifiers, ts.isDecorator); + } + } + ts.getDecorators = getDecorators; + function getModifiers(node) { + if (ts.hasSyntacticModifier(node, 125951 /* ModifierFlags.Modifier */)) { + return ts.filter(node.modifiers, isModifier); + } + } + ts.getModifiers = getModifiers; function getJSDocParameterTagsWorker(param, noCache) { if (param.name) { if (ts.isIdentifier(param.name)) { @@ -13004,6 +13215,12 @@ var ts; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + * + * This does *not* return type parameters from a jsdoc reference to a generic type, eg + * + * type Id = (x: T) => T + * /** @type {Id} / + * function id(x) { return x } */ function getEffectiveTypeParameterDeclarations(node) { if (ts.isJSDocSignature(node)) { @@ -13016,6 +13233,9 @@ var ts; if (node.typeParameters) { return node.typeParameters; } + if (ts.canHaveIllegalTypeParameters(node) && node.typeParameters) { + return node.typeParameters; + } if (ts.isInJSFile(node)) { var decls = ts.getJSDocTypeParameterDeclarations(node); if (decls.length) { @@ -13192,6 +13412,19 @@ var ts; return isLiteralKind(node.kind); } ts.isLiteralExpression = isLiteralExpression; + /** @internal */ + function isLiteralExpressionOfObject(node) { + switch (node.kind) { + case 205 /* SyntaxKind.ObjectLiteralExpression */: + case 204 /* SyntaxKind.ArrayLiteralExpression */: + case 13 /* SyntaxKind.RegularExpressionLiteral */: + case 213 /* SyntaxKind.FunctionExpression */: + case 226 /* SyntaxKind.ClassExpression */: + return true; + } + return false; + } + ts.isLiteralExpressionOfObject = isLiteralExpressionOfObject; // Pseudo-literals /* @internal */ function isTemplateLiteralKind(kind) { @@ -13401,6 +13634,10 @@ var ts; } ts.isMethodOrAccessor = isMethodOrAccessor; // Type members + function isModifierLike(node) { + return isModifier(node) || ts.isDecorator(node); + } + ts.isModifierLike = isModifierLike; function isTypeElement(node) { var kind = node.kind; return kind === 175 /* SyntaxKind.ConstructSignature */ @@ -14010,7 +14247,6 @@ var ts; case 254 /* SyntaxKind.VariableDeclaration */: case 164 /* SyntaxKind.Parameter */: case 203 /* SyntaxKind.BindingElement */: - case 166 /* SyntaxKind.PropertySignature */: case 167 /* SyntaxKind.PropertyDeclaration */: case 296 /* SyntaxKind.PropertyAssignment */: case 299 /* SyntaxKind.EnumMember */: @@ -14062,6 +14298,16 @@ var ts; return node.kind === 324 /* SyntaxKind.JSDocLink */ || node.kind === 325 /* SyntaxKind.JSDocLinkCode */ || node.kind === 326 /* SyntaxKind.JSDocLinkPlain */; } ts.isJSDocLinkLike = isJSDocLinkLike; + function hasRestParameter(s) { + var last = ts.lastOrUndefined(s.parameters); + return !!last && isRestParameter(last); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; + } + ts.isRestParameter = isRestParameter; // #endregion })(ts || (ts = {})); /* @internal */ @@ -14542,10 +14788,11 @@ var ts; } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { - if (nodeIsMissing(node) || !node.decorators) { + var lastDecorator = !nodeIsMissing(node) && ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + if (!lastDecorator) { return getTokenPosOfNode(node, sourceFile); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastDecorator.end); } ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { @@ -15931,7 +16178,7 @@ var ts; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { - return node.decorators !== undefined + return hasDecorators(node) && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; @@ -16007,6 +16254,8 @@ var ts; case 218 /* SyntaxKind.AwaitExpression */: case 231 /* SyntaxKind.MetaProperty */: return true; + case 228 /* SyntaxKind.ExpressionWithTypeArguments */: + return !ts.isHeritageClause(node.parent); case 161 /* SyntaxKind.QualifiedName */: while (node.parent.kind === 161 /* SyntaxKind.QualifiedName */) { node = node.parent; @@ -16178,9 +16427,6 @@ var ts; } ts.isVariableDeclarationInitializedToBareOrAccessedRequire = isVariableDeclarationInitializedToBareOrAccessedRequire; function isVariableDeclarationInitializedWithRequireHelper(node, allowAccessedRequire) { - if (node.kind === 203 /* SyntaxKind.BindingElement */) { - node = node.parent.parent; - } return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, /*requireStringLiteralLikeArgument*/ true); @@ -16832,16 +17078,6 @@ var ts; return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function hasRestParameter(s) { - var last = ts.lastOrUndefined(s.parameters); - return !!last && isRestParameter(last); - } - ts.hasRestParameter = hasRestParameter; - function isRestParameter(node) { - var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 318 /* SyntaxKind.JSDocVariadicType */; - } - ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { return !!node.typeArguments; } @@ -16963,6 +17199,12 @@ var ts; return [child, node]; } ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild; + function skipTypeParentheses(node) { + while (ts.isParenthesizedTypeNode(node)) + node = node.type; + return node; + } + ts.skipTypeParentheses = skipTypeParentheses; function skipParentheses(node, excludeJSDocTypeAssertions) { var flags = excludeJSDocTypeAssertions ? 1 /* OuterExpressionKinds.Parentheses */ | 16 /* OuterExpressionKinds.ExcludeJSDocTypeAssertion */ : @@ -18709,6 +18951,10 @@ var ts; return hasEffectiveModifier(node, 64 /* ModifierFlags.Readonly */); } ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier; + function hasDecorators(node) { + return hasSyntacticModifier(node, 131072 /* ModifierFlags.Decorator */); + } + ts.hasDecorators = hasDecorators; function getSelectedEffectiveModifierFlags(node, flags) { return getEffectiveModifierFlags(node) & flags; } @@ -18786,7 +19032,7 @@ var ts; * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc. */ function getSyntacticModifierFlagsNoCache(node) { - var flags = modifiersToFlags(node.modifiers); + var flags = ts.canHaveModifiers(node) ? modifiersToFlags(node.modifiers) : 0 /* ModifierFlags.None */; if (node.flags & 4 /* NodeFlags.NestedNamespace */ || (node.kind === 79 /* SyntaxKind.Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* ModifierFlags.Export */; } @@ -18820,6 +19066,7 @@ var ts; case 159 /* SyntaxKind.OverrideKeyword */: return 16384 /* ModifierFlags.Override */; case 101 /* SyntaxKind.InKeyword */: return 32768 /* ModifierFlags.In */; case 144 /* SyntaxKind.OutKeyword */: return 65536 /* ModifierFlags.Out */; + case 165 /* SyntaxKind.Decorator */: return 131072 /* ModifierFlags.Decorator */; } return 0 /* ModifierFlags.None */; } @@ -19197,8 +19444,9 @@ var ts; * Moves the start position of a range past any decorators. */ function moveRangePastDecorators(node) { - return node.decorators && node.decorators.length > 0 - ? moveRangePos(node, node.decorators.end) + var lastDecorator = ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; + return lastDecorator && !positionIsSynthesized(lastDecorator.end) + ? moveRangePos(node, lastDecorator.end) : node; } ts.moveRangePastDecorators = moveRangePastDecorators; @@ -19206,8 +19454,9 @@ var ts; * Moves the start position of a range past any decorators or modifiers. */ function moveRangePastModifiers(node) { - return node.modifiers && node.modifiers.length > 0 - ? moveRangePos(node, node.modifiers.end) + var lastModifier = ts.canHaveModifiers(node) ? ts.lastOrUndefined(node.modifiers) : undefined; + return lastModifier && !positionIsSynthesized(lastModifier.end) + ? moveRangePos(node, lastModifier.end) : moveRangePastDecorators(node); } ts.moveRangePastModifiers = moveRangePastModifiers; @@ -19329,7 +19578,8 @@ var ts; function getDeclarationModifierFlagsFromSymbol(s, isWrite) { if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 173 /* SyntaxKind.SetAccessor */; })) || s.valueDeclaration; + var declaration = (isWrite && s.declarations && ts.find(s.declarations, ts.isSetAccessorDeclaration)) + || (s.flags & 32768 /* SymbolFlags.GetAccessor */ && ts.find(s.declarations, ts.isGetAccessorDeclaration)) || s.valueDeclaration; var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* SymbolFlags.Class */ ? flags : flags & ~28 /* ModifierFlags.AccessibilityModifier */; } @@ -20002,8 +20252,9 @@ var ts; */ function isFileForcedToBeModuleByFormat(file) { // Excludes declaration files - they still require an explicit `export {}` or the like - // for back compat purposes. - return file.impliedNodeFormat === ts.ModuleKind.ESNext && !file.isDeclarationFile ? true : undefined; + // for back compat purposes. The only non-declaration files _not_ forced to be a module are `.js` files + // that aren't esm-mode (meaning not in a `type: module` scope). + return (file.impliedNodeFormat === ts.ModuleKind.ESNext || (ts.fileExtensionIsOneOf(file.fileName, [".cjs" /* Extension.Cjs */, ".cts" /* Extension.Cts */, ".mjs" /* Extension.Mjs */, ".mts" /* Extension.Mts */]))) && !file.isDeclarationFile ? true : undefined; } function getSetExternalModuleIndicator(options) { // TODO: Should this callback be cached? @@ -20011,7 +20262,7 @@ var ts; case ts.ModuleDetectionKind.Force: // All non-declaration files are modules, declaration files still do the usual isFileProbablyExternalModule return function (file) { - file.externalModuleIndicator = !file.isDeclarationFile || ts.isFileProbablyExternalModule(file); + file.externalModuleIndicator = ts.isFileProbablyExternalModule(file) || !file.isDeclarationFile || undefined; }; case ts.ModuleDetectionKind.Legacy: // Files are modules if they have imports, exports, or import.meta @@ -20026,10 +20277,7 @@ var ts; if (options.jsx === 4 /* JsxEmit.ReactJSX */ || options.jsx === 5 /* JsxEmit.ReactJSXDev */) { checks.push(isFileModuleFromUsingJSXTag); } - var moduleKind = getEmitModuleKind(options); - if (moduleKind === ts.ModuleKind.Node16 || moduleKind === ts.ModuleKind.NodeNext) { - checks.push(isFileForcedToBeModuleByFormat); - } + checks.push(isFileForcedToBeModuleByFormat); var combined_1 = ts.or.apply(void 0, checks); var callback = function (file) { return void (file.externalModuleIndicator = combined_1(file)); }; return callback; @@ -20071,7 +20319,8 @@ var ts; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; function getEmitModuleDetectionKind(options) { - return options.moduleDetection || ts.ModuleDetectionKind.Auto; + return options.moduleDetection || + (getEmitModuleKind(options) === ts.ModuleKind.Node16 || getEmitModuleKind(options) === ts.ModuleKind.NodeNext ? ts.ModuleDetectionKind.Force : ts.ModuleDetectionKind.Auto); } ts.getEmitModuleDetectionKind = getEmitModuleDetectionKind; function hasJsonModuleEmitEnabled(options) { @@ -20154,6 +20403,10 @@ var ts; return optionsHaveChanges(oldOptions, newOptions, ts.affectsEmitOptionDeclarations); } ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit; + function compilerOptionsAffectDeclarationPath(newOptions, oldOptions) { + return optionsHaveChanges(oldOptions, newOptions, ts.affectsDeclarationPathOptionDeclarations); + } + ts.compilerOptionsAffectDeclarationPath = compilerOptionsAffectDeclarationPath; function getCompilerOptionValue(options, option) { return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; } @@ -21094,8 +21347,12 @@ var ts; return node.parent.templateSpans; case 233 /* SyntaxKind.TemplateSpan */: return node.parent.templateSpans; - case 165 /* SyntaxKind.Decorator */: - return node.parent.decorators; + case 165 /* SyntaxKind.Decorator */: { + var parent_2 = node.parent; + return ts.canHaveDecorators(parent_2) ? parent_2.modifiers : + ts.canHaveIllegalDecorators(parent_2) ? parent_2.illegalDecorators : + undefined; + } case 291 /* SyntaxKind.HeritageClause */: return node.parent.heritageClauses; } @@ -21609,7 +21866,7 @@ var ts; * Wraps an expression in parentheses if it is needed in order to use the expression for * property or element access. */ - function parenthesizeLeftSideOfAccess(expression) { + function parenthesizeLeftSideOfAccess(expression, optionalChain) { // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exception is: // @@ -21618,7 +21875,8 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 209 /* SyntaxKind.NewExpression */ || emittedExpression.arguments) + && (optionalChain || !ts.isOptionalChain(emittedExpression))) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -22565,13 +22823,8 @@ var ts; function createBaseNode(kind) { return baseFactory.createBaseNode(kind); } - function createBaseDeclaration(kind, decorators, modifiers) { + function createBaseDeclaration(kind) { var node = createBaseNode(kind); - node.decorators = asNodeArray(decorators); - node.modifiers = asNodeArray(modifiers); - node.transformFlags |= - propagateChildrenFlags(node.decorators) | - propagateChildrenFlags(node.modifiers); // NOTE: The following properties are commonly set by the binder and are added here to // ensure declarations have a stable shape. node.symbol = undefined; // initialized by binder @@ -22580,10 +22833,15 @@ var ts; node.nextContainer = undefined; // initialized by binder return node; } - function createBaseNamedDeclaration(kind, decorators, modifiers, name) { - var node = createBaseDeclaration(kind, decorators, modifiers); + function createBaseNamedDeclaration(kind, modifiers, name) { + var node = createBaseDeclaration(kind); name = asName(name); node.name = name; + if (ts.canHaveModifiers(node)) { + node.modifiers = asNodeArray(modifiers); + node.transformFlags |= propagateChildrenFlags(node.modifiers); + // node.decorators = filter(node.modifiers, isDecorator); + } // The PropertyName of a member is allowed to be `await`. // We don't need to exclude `await` for type signatures since types // don't propagate child flags. @@ -22606,16 +22864,16 @@ var ts; } return node; } - function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.typeParameters = asNodeArray(typeParameters); node.transformFlags |= propagateChildrenFlags(node.typeParameters); if (typeParameters) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.parameters = createNodeArray(parameters); node.type = type; node.transformFlags |= @@ -22623,50 +22881,45 @@ var ts; propagateChildFlags(node.type); if (type) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used for quick info + node.typeArguments = undefined; return node; } - function updateBaseSignatureDeclaration(updated, original) { - // copy children used only for error reporting - if (original.typeArguments) + function finishUpdateBaseSignatureDeclaration(updated, original) { + if (updated !== original) { + // copy children used for quick info updated.typeArguments = original.typeArguments; + } return update(updated, original); } - function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { - var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); + function createBaseFunctionLikeDeclaration(kind, modifiers, name, typeParameters, parameters, type, body) { + var node = createBaseSignatureDeclaration(kind, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateBaseFunctionLikeDeclaration(updated, original) { - // copy children used only for error reporting - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - if (original.typeArguments) - updated.typeArguments = original.typeArguments; - return updateBaseSignatureDeclaration(updated, original); - } - function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) { - var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters); + function createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses) { + var node = createBaseGenericNamedDeclaration(kind, modifiers, name, typeParameters); node.heritageClauses = asNodeArray(heritageClauses); node.transformFlags |= propagateChildrenFlags(node.heritageClauses); return node; } - function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses); + function createBaseClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(kind, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members); return node; } - function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) { - var node = createBaseNamedDeclaration(kind, decorators, modifiers, name); + function createBaseBindingLikeDeclaration(kind, modifiers, name, initializer) { + var node = createBaseNamedDeclaration(kind, modifiers, name); node.initializer = initializer; node.transformFlags |= propagateChildFlags(node.initializer); return node; } - function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) { - var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer); + function createBaseVariableLikeDeclaration(kind, modifiers, name, type, initializer) { + var node = createBaseBindingLikeDeclaration(kind, modifiers, name, initializer); node.type = type; node.transformFlags |= propagateChildFlags(type); if (type) @@ -22762,7 +23015,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 132 /* SyntaxKind.AwaitKeyword */) { - node.transformFlags |= 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } return node; } @@ -22814,7 +23067,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(80 /* SyntaxKind.PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags |= 16777216 /* TransformFlags.ContainsClassFields */; return node; } // @@ -22861,14 +23114,14 @@ var ts; transformFlags = 1 /* TransformFlags.ContainsTypeScript */; break; case 106 /* SyntaxKind.SuperKeyword */: - transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 33554432 /* TransformFlags.ContainsLexicalSuper */; + transformFlags = 1024 /* TransformFlags.ContainsES2015 */ | 134217728 /* TransformFlags.ContainsLexicalSuper */; break; case 124 /* SyntaxKind.StaticKeyword */: transformFlags = 1024 /* TransformFlags.ContainsES2015 */; break; case 108 /* SyntaxKind.ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 8192 /* TransformFlags.ContainsLexicalThis */; + transformFlags = 16384 /* TransformFlags.ContainsLexicalThis */; break; } if (transformFlags) { @@ -22966,7 +23219,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 65536 /* TransformFlags.ContainsComputedPropertyName */; + 131072 /* TransformFlags.ContainsComputedPropertyName */; return node; } // @api @@ -22975,41 +23228,19 @@ var ts; ? update(createComputedPropertyName(expression), node) : node; } - function createTypeParameterDeclaration(modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } - var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, - /*decorators*/ undefined, modifiers, name); + // + // Signature elements + // + // @api + function createTypeParameterDeclaration(modifiers, name, constraint, defaultType) { + var node = createBaseNamedDeclaration(163 /* SyntaxKind.TypeParameter */, modifiers, name); node.constraint = constraint; node.default = defaultType; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateTypeParameterDeclaration(node, modifiersOrName, nameOrConstraint, constraintOrDefault, defaultType) { - var name; - var modifiers; - var constraint; - if (modifiersOrName === undefined || ts.isArray(modifiersOrName)) { - modifiers = modifiersOrName; - name = nameOrConstraint; - constraint = constraintOrDefault; - } - else { - modifiers = undefined; - name = modifiersOrName; - constraint = nameOrConstraint; - } + // @api + function updateTypeParameterDeclaration(node, modifiers, name, constraint, defaultType) { return node.modifiers !== modifiers || node.name !== name || node.constraint !== constraint @@ -23018,8 +23249,8 @@ var ts; : node; } // @api - function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + function createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(164 /* SyntaxKind.Parameter */, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -23032,32 +23263,32 @@ var ts; if (questionToken) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; if (ts.modifiersToFlags(node.modifiers) & 16476 /* ModifierFlags.ParameterPropertyModifier */) - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; } return node; } // @api - function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateParameterDeclaration(node, modifiers, dotDotDotToken, name, questionToken, type, initializer) { + return node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } // @api function createDecorator(expression) { var node = createBaseNode(165 /* SyntaxKind.Decorator */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */ | - 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */ | + 33554432 /* TransformFlags.ContainsDecorators */; return node; } // @api @@ -23071,11 +23302,12 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, - /*decorators*/ undefined, modifiers, name); + var node = createBaseNamedDeclaration(166 /* SyntaxKind.PropertySignature */, modifiers, name); node.type = type; node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.initializer = undefined; return node; } // @api @@ -23084,20 +23316,27 @@ var ts; || node.name !== name || node.questionToken !== questionToken || node.type !== type - ? update(createPropertySignature(modifiers, name, questionToken, type), node) + ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) : node; } + function finishUpdatePropertySignature(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.initializer = original.initializer; + } + return update(updated, original); + } // @api - function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, decorators, modifiers, name, type, initializer); + function createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer) { + var node = createBaseVariableLikeDeclaration(167 /* SyntaxKind.PropertyDeclaration */, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 8388608 /* TransformFlags.ContainsClassFields */; + 16777216 /* TransformFlags.ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */; + node.transformFlags |= 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; @@ -23105,21 +23344,19 @@ var ts; return node; } // @api - function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updatePropertyDeclaration(node, modifiers, name, questionOrExclamationToken, type, initializer) { + return node.modifiers !== modifiers || node.name !== name || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) || node.type !== type || node.initializer !== initializer - ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node) + ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(168 /* SyntaxKind.MethodSignature */, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23132,12 +23369,12 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node; } // @api - function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(169 /* SyntaxKind.MethodDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= @@ -23158,12 +23395,13 @@ var ts; else if (asteriskToken) { node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } + // The following properties are used only to report grammar errors + node.exclamationToken = undefined; return node; } // @api - function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateMethodDeclaration(node, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.questionToken !== questionToken @@ -23171,80 +23409,123 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) + ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } + function finishUpdateMethodDeclaration(updated, original) { + if (updated !== original) { + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api - function createClassStaticBlockDeclaration(decorators, modifiers, body) { - var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, decorators, modifiers, + function createClassStaticBlockDeclaration(body) { + var node = createBaseGenericNamedDeclaration(170 /* SyntaxKind.ClassStaticBlockDeclaration */, + /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined); node.body = body; - node.transformFlags = propagateChildFlags(body) | 8388608 /* TransformFlags.ContainsClassFields */; + node.transformFlags = propagateChildFlags(body) | 16777216 /* TransformFlags.ContainsClassFields */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api - function updateClassStaticBlockDeclaration(node, decorators, modifiers, body) { - return node.decorators !== decorators - || node.modifier !== modifiers - || node.body !== body - ? update(createClassStaticBlockDeclaration(decorators, modifiers, body), node) + function updateClassStaticBlockDeclaration(node, body) { + return node.body !== body + ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) : node; } + function finishUpdateClassStaticBlockDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, decorators, modifiers, + function createConstructorDeclaration(modifiers, parameters, body) { + var node = createBaseFunctionLikeDeclaration(171 /* SyntaxKind.Constructor */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.typeParameters = undefined; + node.type = undefined; return node; } // @api - function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateConstructorDeclaration(node, modifiers, parameters, body) { + return node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node) + ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) : node; } + function finishUpdateConstructorDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, decorators, modifiers, name, + function createGetAccessorDeclaration(modifiers, name, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(172 /* SyntaxKind.GetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + return node; } // @api - function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateGetAccessorDeclaration(node, modifiers, name, parameters, type, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node) + ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) : node; } + function finishUpdateGetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, decorators, modifiers, name, + function createSetAccessorDeclaration(modifiers, name, parameters, body) { + var node = createBaseFunctionLikeDeclaration(173 /* SyntaxKind.SetAccessor */, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); + // The following properties are used only to report grammar errors + node.typeParameters = undefined; + node.type = undefined; + return node; } // @api - function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateSetAccessorDeclaration(node, modifiers, name, parameters, body) { + return node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body - ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node) + ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) : node; } + function finishUpdateSetAccessorDeclaration(updated, original) { + if (updated !== original) { + updated.typeParameters = original.typeParameters; + updated.type = original.type; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createCallSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(174 /* SyntaxKind.CallSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23255,13 +23536,12 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node; } // @api function createConstructSignature(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(175 /* SyntaxKind.ConstructSignature */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -23272,24 +23552,23 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node; } // @api - function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, decorators, modifiers, + function createIndexSignature(modifiers, parameters, type) { + var node = createBaseSignatureDeclaration(176 /* SyntaxKind.IndexSignature */, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } // @api - function updateIndexSignature(node, decorators, modifiers, parameters, type) { + function updateIndexSignature(node, modifiers, parameters, type) { return node.parameters !== parameters || node.type !== type - || node.decorators !== decorators || node.modifiers !== modifiers - ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node; } // @api @@ -23349,10 +23628,11 @@ var ts; // @api function createFunctionTypeNode(typeParameters, parameters, type) { var node = createBaseSignatureDeclaration(179 /* SyntaxKind.FunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.modifiers = undefined; return node; } // @api @@ -23360,9 +23640,15 @@ var ts; return node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node) + ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) : node; } + function finishUpdateFunctionTypeNode(updated, original) { + if (updated !== original) { + updated.modifiers = original.modifiers; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api function createConstructorTypeNode() { var args = []; @@ -23374,8 +23660,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, - /*decorators*/ undefined, modifiers, + var node = createBaseSignatureDeclaration(180 /* SyntaxKind.ConstructorType */, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; @@ -23399,7 +23684,7 @@ var ts; || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type - ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) + ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node; } /** @deprecated */ @@ -23579,33 +23864,27 @@ var ts; ? update(createTemplateLiteralType(head, templateSpans), node) : node; } - function createImportTypeNode(argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : false; + // @api + function createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = false; } var node = createBaseNode(200 /* SyntaxKind.ImportType */); node.argument = argument; - node.assertions = assertion; + node.assertions = assertions; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.isTypeOf = isTypeOf; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; return node; } - function updateImportTypeNode(node, argument, qualifierOrAssertions, typeArgumentsOrQualifier, isTypeOfOrTypeArguments, isTypeOf) { - var assertion = qualifierOrAssertions && qualifierOrAssertions.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */ ? qualifierOrAssertions : undefined; - var qualifier = qualifierOrAssertions && ts.isEntityName(qualifierOrAssertions) ? qualifierOrAssertions - : typeArgumentsOrQualifier && !ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : undefined; - var typeArguments = ts.isArray(typeArgumentsOrQualifier) ? typeArgumentsOrQualifier : ts.isArray(isTypeOfOrTypeArguments) ? isTypeOfOrTypeArguments : undefined; - isTypeOf = typeof isTypeOfOrTypeArguments === "boolean" ? isTypeOfOrTypeArguments : typeof isTypeOf === "boolean" ? isTypeOf : node.isTypeOf; + // @api + function updateImportTypeNode(node, argument, assertions, qualifier, typeArguments, isTypeOf) { + if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; } return node.argument !== argument - || node.assertions !== assertion + || node.assertions !== assertions || node.qualifier !== qualifier || node.typeArguments !== typeArguments || node.isTypeOf !== isTypeOf - ? update(createImportTypeNode(argument, assertion, qualifier, typeArguments, isTypeOf), node) + ? update(createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf), node) : node; } // @api @@ -23704,11 +23983,11 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + 524288 /* TransformFlags.ContainsBindingPattern */; + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } return node; } @@ -23725,7 +24004,7 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.elements) | 1024 /* TransformFlags.ContainsES2015 */ | - 262144 /* TransformFlags.ContainsBindingPattern */; + 524288 /* TransformFlags.ContainsBindingPattern */; return node; } // @api @@ -23737,7 +24016,6 @@ var ts; // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { var node = createBaseBindingLikeDeclaration(203 /* SyntaxKind.BindingElement */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; @@ -23750,7 +24028,7 @@ var ts; propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 16384 /* TransformFlags.ContainsRestOrSpread */; + node.transformFlags |= 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -23806,13 +24084,13 @@ var ts; // @api function createPropertyAccessExpression(expression, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.name = asName(name); node.transformFlags = propagateChildFlags(node.expression) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); if (ts.isSuperKeyword(expression)) { // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators @@ -23836,7 +24114,7 @@ var ts; function createPropertyAccessChain(expression, questionDotToken, name) { var node = createBaseExpression(206 /* SyntaxKind.PropertyAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= @@ -23845,7 +24123,7 @@ var ts; propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name)); + propagateChildFlags(node.name) | 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); return node; } // @api @@ -23862,7 +24140,7 @@ var ts; // @api function createElementAccessExpression(expression, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.argumentExpression = asExpression(index); node.transformFlags |= propagateChildFlags(node.expression) | @@ -23890,7 +24168,7 @@ var ts; function createElementAccessChain(expression, questionDotToken, index) { var node = createBaseExpression(207 /* SyntaxKind.ElementAccessExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.argumentExpression = asExpression(index); node.transformFlags |= @@ -23914,7 +24192,7 @@ var ts; // @api function createCallExpression(expression, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); node.transformFlags |= @@ -23925,10 +24203,10 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 4194304 /* TransformFlags.ContainsDynamicImport */; + node.transformFlags |= 8388608 /* TransformFlags.ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -23947,7 +24225,7 @@ var ts; function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { var node = createBaseExpression(208 /* SyntaxKind.CallExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.questionDotToken = questionDotToken; node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -23961,7 +24239,7 @@ var ts; node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24002,7 +24280,7 @@ var ts; // @api function createTaggedTemplateExpression(tag, typeArguments, template) { var node = createBaseExpression(210 /* SyntaxKind.TaggedTemplateExpression */); - node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); + node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.template = template; node.transformFlags |= @@ -24059,8 +24337,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, - /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(213 /* SyntaxKind.FunctionExpression */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); if (node.typeParameters) { @@ -24088,20 +24365,19 @@ var ts; || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, - /*decorators*/ undefined, modifiers, + var node = createBaseFunctionLikeDeclaration(214 /* SyntaxKind.ArrowFunction */, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* SyntaxKind.EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | 1024 /* TransformFlags.ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { - node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 8192 /* TransformFlags.ContainsLexicalThis */; + node.transformFlags |= 256 /* TransformFlags.ContainsES2017 */ | 16384 /* TransformFlags.ContainsLexicalThis */; } return node; } @@ -24113,7 +24389,7 @@ var ts; || node.type !== type || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } // @api @@ -24163,7 +24439,7 @@ var ts; propagateChildFlags(node.expression) | 256 /* TransformFlags.ContainsES2017 */ | 128 /* TransformFlags.ContainsES2018 */ | - 1048576 /* TransformFlags.ContainsAwait */; + 2097152 /* TransformFlags.ContainsAwait */; return node; } // @api @@ -24184,7 +24460,7 @@ var ts; ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -24205,7 +24481,7 @@ var ts; if (ts.isIdentifier(node.operand) && !ts.isGeneratedIdentifier(node.operand) && !ts.isLocalName(node.operand)) { - node.transformFlags |= 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; + node.transformFlags |= 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */; } return node; } @@ -24251,11 +24527,14 @@ var ts; else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { node.transformFlags |= 16 /* TransformFlags.ContainsES2021 */; } + if (operatorKind === 101 /* SyntaxKind.InKeyword */ && ts.isPrivateIdentifier(node.left)) { + node.transformFlags |= 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */; + } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; if (node.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer @@ -24263,8 +24542,8 @@ var ts; var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { - return 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + if (target.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { + return 65536 /* TransformFlags.ContainsObjectRestOrSpread */; } if (target.transformFlags & 128 /* TransformFlags.ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); @@ -24390,7 +24669,7 @@ var ts; propagateChildFlags(node.asteriskToken) | 1024 /* TransformFlags.ContainsES2015 */ | 128 /* TransformFlags.ContainsES2018 */ | - 524288 /* TransformFlags.ContainsYield */; + 1048576 /* TransformFlags.ContainsYield */; return node; } // @api @@ -24407,7 +24686,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 1024 /* TransformFlags.ContainsES2015 */ | - 16384 /* TransformFlags.ContainsRestOrSpread */; + 32768 /* TransformFlags.ContainsRestOrSpread */; return node; } // @api @@ -24417,20 +24696,19 @@ var ts; : node; } // @api - function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(226 /* SyntaxKind.ClassExpression */, modifiers, name, typeParameters, heritageClauses, members); node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; return node; } // @api - function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api @@ -24440,7 +24718,7 @@ var ts; // @api function createExpressionWithTypeArguments(expression, typeArguments) { var node = createBaseNode(228 /* SyntaxKind.ExpressionWithTypeArguments */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | @@ -24476,7 +24754,7 @@ var ts; // @api function createNonNullExpression(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -24495,7 +24773,7 @@ var ts; function createNonNullChain(expression) { var node = createBaseExpression(230 /* SyntaxKind.NonNullExpression */); node.flags |= 32 /* NodeFlags.OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* TransformFlags.ContainsTypeScript */; @@ -24578,10 +24856,12 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(237 /* SyntaxKind.VariableStatement */); + node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= - propagateChildFlags(node.declarationList); + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.declarationList); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } @@ -24740,7 +25020,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24755,7 +25035,7 @@ var ts; node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24772,7 +25052,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -24872,7 +25152,6 @@ var ts; // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { var node = createBaseVariableLikeDeclaration(254 /* SyntaxKind.VariableDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; node.transformFlags |= propagateChildFlags(node.exclamationToken); @@ -24898,11 +25177,11 @@ var ts; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* NodeFlags.BlockScoped */) { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */ | - 131072 /* TransformFlags.ContainsBlockScopedBinding */; + 262144 /* TransformFlags.ContainsBlockScopedBinding */; } return node; } @@ -24913,8 +25192,8 @@ var ts; : node; } // @api - function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + function createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + var node = createBaseFunctionLikeDeclaration(256 /* SyntaxKind.FunctionDeclaration */, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; @@ -24922,7 +25201,7 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; + 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* ModifierFlags.Async */) { if (node.asteriskToken) { node.transformFlags |= 128 /* TransformFlags.ContainsES2018 */; @@ -24935,104 +25214,133 @@ var ts; node.transformFlags |= 2048 /* TransformFlags.ContainsGenerator */; } } + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateFunctionDeclaration(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { + return node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body - ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } + function finishUpdateFunctionDeclaration(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.illegalDecorators = original.illegalDecorators; + } + return finishUpdateBaseSignatureDeclaration(updated, original); + } // @api - function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + function createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseClassLikeDeclaration(257 /* SyntaxKind.ClassDeclaration */, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* ModifierFlags.Ambient */) { node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; } else { node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; - if (node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */) { + if (node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } } return node; } // @api - function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateClassDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } // @api - function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + function createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members) { + var node = createBaseInterfaceOrClassLikeDeclaration(258 /* SyntaxKind.InterfaceDeclaration */, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateInterfaceDeclaration(node, modifiers, name, typeParameters, heritageClauses, members) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members - ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node) + ? finishUpdateInterfaceDeclaration(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } + function finishUpdateInterfaceDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + function createTypeAliasDeclaration(modifiers, name, typeParameters, type) { + var node = createBaseGenericNamedDeclaration(259 /* SyntaxKind.TypeAliasDeclaration */, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateTypeAliasDeclaration(node, modifiers, name, typeParameters, type) { + return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.type !== type - ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node) + ? finishUpdateTypeAliasDeclaration(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; } + function finishUpdateTypeAliasDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, decorators, modifiers, name); + function createEnumDeclaration(modifiers, name, members) { + var node = createBaseNamedDeclaration(260 /* SyntaxKind.EnumDeclaration */, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateEnumDeclaration(node, decorators, modifiers, name, members) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateEnumDeclaration(node, modifiers, name, members) { + return node.modifiers !== modifiers || node.name !== name || node.members !== members - ? update(createEnumDeclaration(decorators, modifiers, name, members), node) + ? finishUpdateEnumDeclaration(createEnumDeclaration(modifiers, name, members), node) : node; } + function finishUpdateEnumDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createModuleDeclaration(decorators, modifiers, name, body, flags) { + function createModuleDeclaration(modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* NodeFlags.None */; } - var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(261 /* SyntaxKind.ModuleDeclaration */); + node.modifiers = asNodeArray(modifiers); node.flags |= flags & (16 /* NodeFlags.Namespace */ | 4 /* NodeFlags.NestedNamespace */ | 1024 /* NodeFlags.GlobalAugmentation */); node.name = name; node.body = body; @@ -25041,22 +25349,30 @@ var ts; } else { node.transformFlags |= - propagateChildFlags(node.name) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateModuleDeclaration(node, decorators, modifiers, name, body) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateModuleDeclaration(node, modifiers, name, body) { + return node.modifiers !== modifiers || node.name !== name || node.body !== body - ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node) + ? finishUpdateModuleDeclaration(createModuleDeclaration(modifiers, name, body, node.flags), node) : node; } + function finishUpdateModuleDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createModuleBlock(statements) { var node = createBaseNode(262 /* SyntaxKind.ModuleBlock */); @@ -25086,60 +25402,84 @@ var ts; // @api function createNamespaceExportDeclaration(name) { var node = createBaseNamedDeclaration(264 /* SyntaxKind.NamespaceExportDeclaration */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* TransformFlags.ContainsTypeScript */; + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; return node; } // @api function updateNamespaceExportDeclaration(node, name) { return node.name !== name - ? update(createNamespaceExportDeclaration(name), node) + ? finishUpdateNamespaceExportDeclaration(createNamespaceExportDeclaration(name), node) : node; } + function finishUpdateNamespaceExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + } + return update(updated, original); + } // @api - function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, decorators, modifiers, name); + function createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference) { + var node = createBaseNamedDeclaration(265 /* SyntaxKind.ImportEqualsDeclaration */, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportEqualsDeclaration(node, modifiers, isTypeOnly, name, moduleReference) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.name !== name || node.moduleReference !== moduleReference - ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node) + ? finishUpdateImportEqualsDeclaration(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; } + function finishUpdateImportEqualsDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */, decorators, modifiers); + function createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(266 /* SyntaxKind.ImportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateImportDeclaration(node, modifiers, importClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause), node) + ? finishUpdateImportDeclaration(createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateImportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createImportClause(isTypeOnly, name, namedBindings) { var node = createBaseNode(267 /* SyntaxKind.ImportClause */); @@ -25152,7 +25492,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* TransformFlags.ContainsTypeScript */; } - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25212,7 +25552,7 @@ var ts; var node = createBaseNode(268 /* SyntaxKind.NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25228,7 +25568,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.name) | 4 /* TransformFlags.ContainsESNext */; - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25242,7 +25582,7 @@ var ts; var node = createBaseNode(269 /* SyntaxKind.NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25260,7 +25600,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25272,54 +25612,71 @@ var ts; : node; } // @api - function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */, decorators, modifiers); + function createExportAssignment(modifiers, isExportEquals, expression) { + var node = createBaseDeclaration(271 /* SyntaxKind.ExportAssignment */); + node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(63 /* SyntaxKind.EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); - node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportAssignment(node, decorators, modifiers, expression) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportAssignment(node, modifiers, expression) { + return node.modifiers !== modifiers || node.expression !== expression - ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node) + ? finishUpdateExportAssignment(createExportAssignment(modifiers, node.isExportEquals, expression), node) : node; } + function finishUpdateExportAssignment(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api - function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */, decorators, modifiers); + function createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + var node = createBaseDeclaration(272 /* SyntaxKind.ExportDeclaration */); + node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; node.transformFlags |= - propagateChildFlags(node.exportClause) | + propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; return node; } // @api - function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { - return node.decorators !== decorators - || node.modifiers !== modifiers + function updateExportDeclaration(node, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause) { + return node.modifiers !== modifiers || node.isTypeOnly !== isTypeOnly || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier || node.assertClause !== assertClause - ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) + ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) : node; } + function finishUpdateExportDeclaration(updated, original) { + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + } + return update(updated, original); + } // @api function createNamedExports(elements) { var node = createBaseNode(273 /* SyntaxKind.NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25337,7 +25694,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25350,9 +25707,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */, - /*decorators*/ undefined, - /*modifiers*/ undefined); + var node = createBaseDeclaration(276 /* SyntaxKind.MissingDeclaration */); return node; } // @@ -25363,7 +25718,7 @@ var ts; var node = createBaseNode(277 /* SyntaxKind.ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -25419,7 +25774,6 @@ var ts; // @api function createJSDocFunctionType(parameters, type) { var node = createBaseSignatureDeclaration(317 /* SyntaxKind.JSDocFunctionType */, - /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); @@ -26071,26 +26425,18 @@ var ts; // @api function createPropertyAssignment(name, initializer) { var node = createBaseNamedDeclaration(296 /* SyntaxKind.PropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer); + // The following properties are used only to report grammar errors + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdatePropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updatePropertyAssignment(node, name, initializer) { return node.name !== name @@ -26098,31 +26444,32 @@ var ts; ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) : node; } + function finishUpdatePropertyAssignment(updated, original) { + // copy children used only for error reporting + if (updated !== original) { + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { var node = createBaseNamedDeclaration(297 /* SyntaxKind.ShorthandPropertyAssignment */, - /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | 1024 /* TransformFlags.ContainsES2015 */; + // The following properties are used only to report grammar errors + node.equalsToken = undefined; + node.illegalDecorators = undefined; + node.modifiers = undefined; + node.questionToken = undefined; + node.exclamationToken = undefined; return node; } - function finishUpdateShorthandPropertyAssignment(updated, original) { - // copy children used only for error reporting - if (original.decorators) - updated.decorators = original.decorators; - if (original.modifiers) - updated.modifiers = original.modifiers; - if (original.equalsToken) - updated.equalsToken = original.equalsToken; - if (original.questionToken) - updated.questionToken = original.questionToken; - if (original.exclamationToken) - updated.exclamationToken = original.exclamationToken; - return update(updated, original); - } // @api function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) { return node.name !== name @@ -26130,6 +26477,17 @@ var ts; ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) : node; } + function finishUpdateShorthandPropertyAssignment(updated, original) { + if (updated !== original) { + // copy children used only for error reporting + updated.equalsToken = original.equalsToken; + updated.illegalDecorators = original.illegalDecorators; + updated.modifiers = original.modifiers; + updated.questionToken = original.questionToken; + updated.exclamationToken = original.exclamationToken; + } + return update(updated, original); + } // @api function createSpreadAssignment(expression) { var node = createBaseNode(298 /* SyntaxKind.SpreadAssignment */); @@ -26137,7 +26495,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | 128 /* TransformFlags.ContainsES2018 */ | - 32768 /* TransformFlags.ContainsObjectRestOrSpread */; + 65536 /* TransformFlags.ContainsObjectRestOrSpread */; return node; } // @api @@ -26457,13 +26815,11 @@ var ts; } function createExportDefault(expression) { return createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression); } function createExternalModuleExport(exportName) { return createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, createNamedExports([ createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName) @@ -26621,7 +26977,7 @@ var ts; } else if (ts.getEmitFlags(callee) & 4096 /* EmitFlags.HelperName */) { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee, /*optionalChain*/ false); } else if (ts.isPropertyAccessExpression(callee)) { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { @@ -26650,7 +27006,7 @@ var ts; else { // for `a()` target is `a` and thisArg is `void 0` thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); } return { target: target, thisArg: thisArg }; } @@ -26659,9 +27015,7 @@ var ts; // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560) createParenthesizedExpression(createObjectLiteralExpression([ createSetAccessorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, "value", [createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, paramName, /*questionToken*/ undefined, @@ -26963,30 +27317,32 @@ var ts; else { modifierArray = modifiers; } - return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : - ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : - ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : - ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifierArray, node.parameters, node.body) : - ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.type, node.body) : - ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.body) : - ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifierArray, node.parameters, node.type) : - ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : - ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : - ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.type) : - ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifierArray, node.name, node.members) : - ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifierArray, node.name, node.body) : - ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : - ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : - ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifierArray, node.expression) : - ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : - ts.Debug.assertNever(node); + return ts.isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : + ts.isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : + ts.isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : + ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : + ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : + ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : + ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : + ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : + ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : + ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : + ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : + ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : + ts.isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : + ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : + ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : + ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : + ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : + ts.isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : + ts.isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : + ts.isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : + ts.Debug.assertNever(node); } function asNodeArray(array) { return array ? createNodeArray(array) : undefined; @@ -27094,10 +27450,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 33562624 /* TransformFlags.PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 134234112 /* TransformFlags.PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -27128,29 +27484,29 @@ var ts; case 208 /* SyntaxKind.CallExpression */: case 209 /* SyntaxKind.NewExpression */: case 204 /* SyntaxKind.ArrayLiteralExpression */: - return 536887296 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; + return -2147450880 /* TransformFlags.ArrayLiteralOrCallOrNewExcludes */; case 261 /* SyntaxKind.ModuleDeclaration */: - return 589443072 /* TransformFlags.ModuleExcludes */; + return -1941676032 /* TransformFlags.ModuleExcludes */; case 164 /* SyntaxKind.Parameter */: - return 536870912 /* TransformFlags.ParameterExcludes */; + return -2147483648 /* TransformFlags.ParameterExcludes */; case 214 /* SyntaxKind.ArrowFunction */: - return 557748224 /* TransformFlags.ArrowFunctionExcludes */; + return -2072174592 /* TransformFlags.ArrowFunctionExcludes */; case 213 /* SyntaxKind.FunctionExpression */: case 256 /* SyntaxKind.FunctionDeclaration */: - return 591310848 /* TransformFlags.FunctionExcludes */; + return -1937940480 /* TransformFlags.FunctionExcludes */; case 255 /* SyntaxKind.VariableDeclarationList */: - return 537165824 /* TransformFlags.VariableDeclarationListExcludes */; + return -2146893824 /* TransformFlags.VariableDeclarationListExcludes */; case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return 536940544 /* TransformFlags.ClassExcludes */; + return -2147344384 /* TransformFlags.ClassExcludes */; case 171 /* SyntaxKind.Constructor */: - return 591306752 /* TransformFlags.ConstructorExcludes */; + return -1937948672 /* TransformFlags.ConstructorExcludes */; case 167 /* SyntaxKind.PropertyDeclaration */: - return 570433536 /* TransformFlags.PropertyExcludes */; + return -2013249536 /* TransformFlags.PropertyExcludes */; case 169 /* SyntaxKind.MethodDeclaration */: case 172 /* SyntaxKind.GetAccessor */: case 173 /* SyntaxKind.SetAccessor */: - return 574529536 /* TransformFlags.MethodOrAccessorExcludes */; + return -2005057536 /* TransformFlags.MethodOrAccessorExcludes */; case 130 /* SyntaxKind.AnyKeyword */: case 147 /* SyntaxKind.NumberKeyword */: case 158 /* SyntaxKind.BigIntKeyword */: @@ -27170,23 +27526,23 @@ var ts; case 259 /* SyntaxKind.TypeAliasDeclaration */: return -2 /* TransformFlags.TypeExcludes */; case 205 /* SyntaxKind.ObjectLiteralExpression */: - return 536973312 /* TransformFlags.ObjectLiteralExcludes */; + return -2147278848 /* TransformFlags.ObjectLiteralExcludes */; case 292 /* SyntaxKind.CatchClause */: - return 536903680 /* TransformFlags.CatchClauseExcludes */; + return -2147418112 /* TransformFlags.CatchClauseExcludes */; case 201 /* SyntaxKind.ObjectBindingPattern */: case 202 /* SyntaxKind.ArrayBindingPattern */: - return 536887296 /* TransformFlags.BindingPatternExcludes */; + return -2147450880 /* TransformFlags.BindingPatternExcludes */; case 211 /* SyntaxKind.TypeAssertionExpression */: case 229 /* SyntaxKind.AsExpression */: case 350 /* SyntaxKind.PartiallyEmittedExpression */: case 212 /* SyntaxKind.ParenthesizedExpression */: case 106 /* SyntaxKind.SuperKeyword */: - return 536870912 /* TransformFlags.OuterExpressionExcludes */; + return -2147483648 /* TransformFlags.OuterExpressionExcludes */; case 206 /* SyntaxKind.PropertyAccessExpression */: case 207 /* SyntaxKind.ElementAccessExpression */: - return 536870912 /* TransformFlags.PropertyAccessExcludes */; + return -2147483648 /* TransformFlags.PropertyAccessExcludes */; default: - return 536870912 /* TransformFlags.NodeExcludes */; + return -2147483648 /* TransformFlags.NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -28596,6 +28952,11 @@ var ts; return node.kind === 126 /* SyntaxKind.AbstractKeyword */; } ts.isAbstractModifier = isAbstractModifier; + /* @internal */ + function isOverrideModifier(node) { + return node.kind === 159 /* SyntaxKind.OverrideKeyword */; + } + ts.isOverrideModifier = isOverrideModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 106 /* SyntaxKind.SuperKeyword */; @@ -29051,6 +29412,10 @@ var ts; return node.kind === 267 /* SyntaxKind.ImportClause */; } ts.isImportClause = isImportClause; + function isImportTypeAssertionContainer(node) { + return node.kind === 295 /* SyntaxKind.ImportTypeAssertionContainer */; + } + ts.isImportTypeAssertionContainer = isImportTypeAssertionContainer; function isAssertClause(node) { return node.kind === 293 /* SyntaxKind.AssertClause */; } @@ -29388,7 +29753,7 @@ var ts; (function (ts) { // Compound nodes function createEmptyExports(factory) { - return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); + return factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); } ts.createEmptyExports = createEmptyExports; function createMemberAccessForPropertyName(factory, target, memberName, location) { @@ -29538,13 +29903,13 @@ var ts; return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({ enumerable: factory.createFalse(), configurable: true, - get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, + get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(getAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, /*type*/ undefined, getAccessor.body // TODO: GH#18217 ), getAccessor), getAccessor), - set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, + set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(ts.getModifiers(setAccessor), /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, @@ -29563,7 +29928,7 @@ var ts; /*original*/ property); } function createExpressionForMethodDeclaration(factory, method, receiver) { - return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken, + return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(ts.getModifiers(method), method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, /*type*/ undefined, method.body // TODO: GH#18217 @@ -29796,7 +30161,6 @@ var ts; } if (namedBindings) { var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText), /*assertClause*/ undefined); ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* EmitFlags.NeverApplyImportHelper */); @@ -30115,33 +30479,50 @@ var ts; } } ts.getJSDocTypeAliasName = getJSDocTypeAliasName; - function canHaveModifiers(node) { + function canHaveIllegalType(node) { var kind = node.kind; - return kind === 164 /* SyntaxKind.Parameter */ - || kind === 166 /* SyntaxKind.PropertySignature */ - || kind === 167 /* SyntaxKind.PropertyDeclaration */ - || kind === 168 /* SyntaxKind.MethodSignature */ - || kind === 169 /* SyntaxKind.MethodDeclaration */ - || kind === 171 /* SyntaxKind.Constructor */ + return kind === 171 /* SyntaxKind.Constructor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalType = canHaveIllegalType; + function canHaveIllegalTypeParameters(node) { + var kind = node.kind; + return kind === 171 /* SyntaxKind.Constructor */ || kind === 172 /* SyntaxKind.GetAccessor */ - || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */; + } + ts.canHaveIllegalTypeParameters = canHaveIllegalTypeParameters; + function canHaveIllegalDecorators(node) { + var kind = node.kind; + return kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ || kind === 176 /* SyntaxKind.IndexSignature */ - || kind === 213 /* SyntaxKind.FunctionExpression */ - || kind === 214 /* SyntaxKind.ArrowFunction */ - || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ || kind === 237 /* SyntaxKind.VariableStatement */ - || kind === 256 /* SyntaxKind.FunctionDeclaration */ - || kind === 257 /* SyntaxKind.ClassDeclaration */ || kind === 258 /* SyntaxKind.InterfaceDeclaration */ || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ || kind === 260 /* SyntaxKind.EnumDeclaration */ || kind === 261 /* SyntaxKind.ModuleDeclaration */ || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ || kind === 266 /* SyntaxKind.ImportDeclaration */ - || kind === 271 /* SyntaxKind.ExportAssignment */ - || kind === 272 /* SyntaxKind.ExportDeclaration */; + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */ + || kind === 272 /* SyntaxKind.ExportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */; } - ts.canHaveModifiers = canHaveModifiers; + ts.canHaveIllegalDecorators = canHaveIllegalDecorators; + function canHaveIllegalModifiers(node) { + var kind = node.kind; + return kind === 170 /* SyntaxKind.ClassStaticBlockDeclaration */ + || kind === 296 /* SyntaxKind.PropertyAssignment */ + || kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ + || kind === 179 /* SyntaxKind.FunctionType */ + || kind === 276 /* SyntaxKind.MissingDeclaration */ + || kind === 264 /* SyntaxKind.NamespaceExportDeclaration */; + } + ts.canHaveIllegalModifiers = canHaveIllegalModifiers; ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); @@ -30405,6 +30786,14 @@ var ts; } } ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; + function elideNodes(factory, nodes) { + if (nodes === undefined) + return undefined; + if (nodes.length === 0) + return nodes; + return ts.setTextRange(factory.createNodeArray([], nodes.hasTrailingComma), nodes); + } + ts.elideNodes = elideNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -30412,6 +30801,46 @@ var ts; return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range; } ts.setTextRange = setTextRange; + function canHaveModifiers(node) { + var kind = node.kind; + return kind === 163 /* SyntaxKind.TypeParameter */ + || kind === 164 /* SyntaxKind.Parameter */ + || kind === 166 /* SyntaxKind.PropertySignature */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 168 /* SyntaxKind.MethodSignature */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 171 /* SyntaxKind.Constructor */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 176 /* SyntaxKind.IndexSignature */ + || kind === 180 /* SyntaxKind.ConstructorType */ + || kind === 213 /* SyntaxKind.FunctionExpression */ + || kind === 214 /* SyntaxKind.ArrowFunction */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 237 /* SyntaxKind.VariableStatement */ + || kind === 256 /* SyntaxKind.FunctionDeclaration */ + || kind === 257 /* SyntaxKind.ClassDeclaration */ + || kind === 258 /* SyntaxKind.InterfaceDeclaration */ + || kind === 259 /* SyntaxKind.TypeAliasDeclaration */ + || kind === 260 /* SyntaxKind.EnumDeclaration */ + || kind === 261 /* SyntaxKind.ModuleDeclaration */ + || kind === 265 /* SyntaxKind.ImportEqualsDeclaration */ + || kind === 266 /* SyntaxKind.ImportDeclaration */ + || kind === 271 /* SyntaxKind.ExportAssignment */ + || kind === 272 /* SyntaxKind.ExportDeclaration */; + } + ts.canHaveModifiers = canHaveModifiers; + function canHaveDecorators(node) { + var kind = node.kind; + return kind === 164 /* SyntaxKind.Parameter */ + || kind === 167 /* SyntaxKind.PropertyDeclaration */ + || kind === 169 /* SyntaxKind.MethodDeclaration */ + || kind === 172 /* SyntaxKind.GetAccessor */ + || kind === 173 /* SyntaxKind.SetAccessor */ + || kind === 226 /* SyntaxKind.ClassExpression */ + || kind === 257 /* SyntaxKind.ClassDeclaration */; + } + ts.canHaveDecorators = canHaveDecorators; })(ts || (ts = {})); var ts; (function (ts) { @@ -30481,7 +30910,7 @@ var ts; } ts.isFileProbablyExternalModule = isFileProbablyExternalModule; function isAnExternalModuleIndicatorNode(node) { - return hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) + return ts.canHaveModifiers(node) && hasModifierOfKind(node, 93 /* SyntaxKind.ExportKeyword */) || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) || ts.isImportDeclaration(node) || ts.isExportAssignment(node) @@ -30530,7 +30959,7 @@ var ts; visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || @@ -30540,79 +30969,128 @@ var ts; case 298 /* SyntaxKind.SpreadAssignment */: return visitNode(cbNode, node.expression); case 164 /* SyntaxKind.Parameter */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 167 /* SyntaxKind.PropertyDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 166 /* SyntaxKind.PropertySignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 296 /* SyntaxKind.PropertyAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.initializer); case 254 /* SyntaxKind.VariableDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || + return visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); case 203 /* SyntaxKind.BindingElement */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.dotDotDotToken) || + return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - case 174 /* SyntaxKind.CallSignature */: - case 175 /* SyntaxKind.ConstructSignature */: case 176 /* SyntaxKind.IndexSignature */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); + case 180 /* SyntaxKind.ConstructorType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 179 /* SyntaxKind.FunctionType */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 174 /* SyntaxKind.CallSignature */: + case 175 /* SyntaxKind.ConstructSignature */: + return visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 169 /* SyntaxKind.MethodDeclaration */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 168 /* SyntaxKind.MethodSignature */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 171 /* SyntaxKind.Constructor */: + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 172 /* SyntaxKind.GetAccessor */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 173 /* SyntaxKind.SetAccessor */: - case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); case 256 /* SyntaxKind.FunctionDeclaration */: - case 214 /* SyntaxKind.ArrowFunction */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.exclamationToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 213 /* SyntaxKind.FunctionExpression */: + return visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.body); + case 214 /* SyntaxKind.ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.body); case 178 /* SyntaxKind.TypeReference */: @@ -30740,7 +31218,7 @@ var ts; return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); case 237 /* SyntaxKind.VariableStatement */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); case 255 /* SyntaxKind.VariableDeclarationList */: @@ -30805,27 +31283,26 @@ var ts; return visitNode(cbNode, node.expression); case 257 /* SyntaxKind.ClassDeclaration */: case 226 /* SyntaxKind.ClassExpression */: - return visitNodes(cbNode, cbNodes, node.decorators) || - visitNodes(cbNode, cbNodes, node.modifiers) || + return visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 258 /* SyntaxKind.InterfaceDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); case 259 /* SyntaxKind.TypeAliasDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); case 260 /* SyntaxKind.EnumDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); @@ -30833,17 +31310,17 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 261 /* SyntaxKind.ModuleDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); case 265 /* SyntaxKind.ImportEqualsDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); case 266 /* SyntaxKind.ImportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -30857,7 +31334,8 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.value); case 264 /* SyntaxKind.NamespaceExportDeclaration */: - return visitNode(cbNode, node.name); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNode(cbNode, node.name); case 268 /* SyntaxKind.NamespaceImport */: return visitNode(cbNode, node.name); case 274 /* SyntaxKind.NamespaceExport */: @@ -30866,7 +31344,7 @@ var ts; case 273 /* SyntaxKind.NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); case 272 /* SyntaxKind.ExportDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier) || @@ -30876,17 +31354,21 @@ var ts; return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); case 271 /* SyntaxKind.ExportAssignment */: - return visitNodes(cbNode, cbNodes, node.decorators) || + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); case 223 /* SyntaxKind.TemplateExpression */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 233 /* SyntaxKind.TemplateSpan */: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.literal); case 198 /* SyntaxKind.TemplateLiteralType */: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + return visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans); case 199 /* SyntaxKind.TemplateLiteralTypeSpan */: - return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.literal); case 162 /* SyntaxKind.ComputedPropertyName */: return visitNode(cbNode, node.expression); case 291 /* SyntaxKind.HeritageClause */: @@ -30897,7 +31379,8 @@ var ts; case 277 /* SyntaxKind.ExternalModuleReference */: return visitNode(cbNode, node.expression); case 276 /* SyntaxKind.MissingDeclaration */: - return visitNodes(cbNode, cbNodes, node.decorators); + return visitNodes(cbNode, cbNodes, node.illegalDecorators) || + visitNodes(cbNode, cbNodes, node.modifiers); case 351 /* SyntaxKind.CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 278 /* SyntaxKind.JsxElement */: @@ -31576,7 +32059,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* NodeFlags.AwaitContext */) - && !!(node.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -31617,7 +32100,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setFields(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* TransformFlags.ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); setFields(sourceFile); } @@ -32545,7 +33028,7 @@ var ts; } return parseElement(); } - function currentNode(parsingContext) { + function currentNode(parsingContext, pos) { // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. // // If there is an outstanding parse error that we've encountered, but not attached to @@ -32558,7 +33041,7 @@ var ts; if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } - var node = syntaxCursor.currentNode(scanner.getStartPos()); + var node = syntaxCursor.currentNode(pos !== null && pos !== void 0 ? pos : scanner.getStartPos()); // Can't reuse a missing node. // Can't reuse a node that intersected the change range. // Can't reuse a node that contains a parse error. This is necessary so that we @@ -32833,7 +33316,9 @@ var ts; case 23 /* ParsingContext.ImportOrExportSpecifiers */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 13 /* ParsingContext.JsxAttributes */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); case 14 /* ParsingContext.JsxChildren */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - default: return [undefined]; // TODO: GH#18217 `default: Debug.assertNever(context);` + case 24 /* ParsingContext.AssertEntries */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_or_string_literal_expected); // AssertionKey. + case 25 /* ParsingContext.Count */: return ts.Debug.fail("ParsingContext.Count used as a context"); // Not a real context, only a marker. + default: ts.Debug.assertNever(context); } } function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { @@ -33149,7 +33634,6 @@ var ts; parseExpected(58 /* SyntaxKind.ColonToken */); } return finishNode(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier? @@ -33275,10 +33759,9 @@ var ts; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : doOutsideOfAwaitContext(parseDecorators); if (token() === 108 /* SyntaxKind.ThisKeyword */) { var node_1 = factory.createParameterDeclaration(decorators, - /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); @@ -33289,12 +33772,12 @@ var ts; } var savedTopLevel = topLevel; topLevel = false; - var modifiers = parseModifiers(); + var modifiers = combineDecoratorsAndModifiers(decorators, parseModifiers()); var dotDotDotToken = parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */); if (!allowAmbiguity && !isParameterNameStart()) { return undefined; } - var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createParameterDeclaration(modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(57 /* SyntaxKind.QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); topLevel = savedTopLevel; return node; } @@ -33446,7 +33929,8 @@ var ts; var parameters = parseBracketedList(16 /* ParsingContext.Parameters */, function () { return parseParameter(/*inOuterAwaitContext*/ false); }, 22 /* SyntaxKind.OpenBracketToken */, 23 /* SyntaxKind.CloseBracketToken */); var type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - var node = factory.createIndexSignature(decorators, modifiers, parameters, type); + var node = factory.createIndexSignature(modifiers, parameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) { @@ -33519,10 +34003,10 @@ var ts; var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 172 /* SyntaxKind.GetAccessor */, 4 /* SignatureFlags.Type */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 173 /* SyntaxKind.SetAccessor */, 4 /* SignatureFlags.Type */); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); @@ -34160,10 +34644,10 @@ var ts; setDecoratorContext(/*val*/ false); } var pos = getNodePos(); - var expr = parseAssignmentExpressionOrHigher(); + var expr = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); var operatorToken; while ((operatorToken = parseOptionalToken(27 /* SyntaxKind.CommaToken */))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos); + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), pos); } if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -34171,9 +34655,9 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(63 /* SyntaxKind.EqualsToken */) ? parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true) : undefined; } - function parseAssignmentExpressionOrHigher() { + function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) { // AssignmentExpression[in,yield]: // 1) ConditionalExpression[?in,?yield] // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] @@ -34199,7 +34683,7 @@ var ts; // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + var arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction); if (arrowExpression) { return arrowExpression; } @@ -34218,7 +34702,7 @@ var ts; // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. if (expr.kind === 79 /* SyntaxKind.Identifier */ && token() === 38 /* SyntaxKind.EqualsGreaterThanToken */) { - return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, /*asyncModifier*/ undefined); } // Now see if we might be in cases '2' or '3'. // If the expression was a LHS expression, and we have an assignment operator, then @@ -34227,10 +34711,10 @@ var ts; // Note: we call reScanGreaterToken so that we get an appropriately merged token // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos); + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); } // It wasn't an assignment or a lambda. This is a conditional expression: - return parseConditionalExpressionRest(expr, pos); + return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction); } function isYieldExpression() { if (token() === 125 /* SyntaxKind.YieldKeyword */) { @@ -34270,7 +34754,7 @@ var ts; nextToken(); if (!scanner.hasPrecedingLineBreak() && (token() === 41 /* SyntaxKind.AsteriskToken */ || isStartOfExpression())) { - return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher()), pos); + return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* SyntaxKind.AsteriskToken */), parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)), pos); } else { // if the next token is not on the same line as yield. or we don't have an '*' or @@ -34278,10 +34762,9 @@ var ts; return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos); } } - function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) { + function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, asyncModifier) { ts.Debug.assert(token() === 38 /* SyntaxKind.EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var parameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, identifier, /*questionToken*/ undefined, @@ -34290,11 +34773,11 @@ var ts; finishNode(parameter, identifier.pos); var parameters = createNodeArray([parameter], parameter.pos, parameter.end); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); - var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier, allowReturnTypeInArrowFunction); var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body); return addJSDocComment(finishNode(node, pos)); } - function tryParseParenthesizedArrowFunctionExpression() { + function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var triState = isParenthesizedArrowFunctionExpression(); if (triState === 0 /* Tristate.False */) { // It's definitely not a parenthesized arrow function expression. @@ -34305,8 +34788,8 @@ var ts; // it out, but don't allow any ambiguity, and return 'undefined' if this could be an // expression instead. return triState === 1 /* Tristate.True */ ? - parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) : - tryParse(parsePossibleParenthesizedArrowFunctionExpression); + parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true, /*allowReturnTypeInArrowFunction*/ true) : + tryParse(function () { return parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction); }); } // True -> We definitely expect a parenthesized arrow function here. // False -> There *cannot* be a parenthesized arrow function here. @@ -34371,7 +34854,7 @@ var ts; // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. if (ts.isModifierKind(second) && second !== 131 /* SyntaxKind.AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { - if (lookAhead(function () { return nextToken() === 127 /* SyntaxKind.AsKeyword */; })) { + if (nextToken() === 127 /* SyntaxKind.AsKeyword */) { // https://github.com/microsoft/TypeScript/issues/44466 return 0 /* Tristate.False */; } @@ -34440,25 +34923,25 @@ var ts; return 2 /* Tristate.Unknown */; } } - function parsePossibleParenthesizedArrowFunctionExpression() { + function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { var tokenPos = scanner.getTokenPos(); if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) { return undefined; } - var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false); + var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false, allowReturnTypeInArrowFunction); if (!result) { (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos); } return result; } - function tryParseAsyncSimpleArrowFunctionExpression() { + function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction) { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() === 131 /* SyntaxKind.AsyncKeyword */) { if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* Tristate.True */) { var pos = getNodePos(); var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0 /* OperatorPrecedence.Lowest */); - return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, asyncModifier); } } return undefined; @@ -34482,7 +34965,7 @@ var ts; } return 0 /* Tristate.False */; } - function parseParenthesizedArrowFunctionExpression(allowAmbiguity) { + function parseParenthesizedArrowFunctionExpression(allowAmbiguity, allowReturnTypeInArrowFunction) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiersForArrowFunction(); @@ -34517,6 +35000,7 @@ var ts; return undefined; } } + var hasReturnColon = token() === 58 /* SyntaxKind.ColonToken */; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) { return undefined; @@ -34545,12 +35029,37 @@ var ts; var lastToken = token(); var equalsGreaterThanToken = parseExpectedToken(38 /* SyntaxKind.EqualsGreaterThanToken */); var body = (lastToken === 38 /* SyntaxKind.EqualsGreaterThanToken */ || lastToken === 18 /* SyntaxKind.OpenBraceToken */) - ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier)) + ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier), allowReturnTypeInArrowFunction) : parseIdentifier(); + // Given: + // x ? y => ({ y }) : z => ({ z }) + // We try to parse the body of the first arrow function by looking at: + // ({ y }) : z => ({ z }) + // This is a valid arrow function with "z" as the return type. + // + // But, if we're in the true side of a conditional expression, this colon + // terminates the expression, so we cannot allow a return type if we aren't + // certain whether or not the preceding text was parsed as a parameter list. + // + // For example, + // a() ? (b: number, c?: string): void => d() : e + // is determined by isParenthesizedArrowFunctionExpression to unambiguously + // be an arrow expression, so we allow a return type. + if (!allowReturnTypeInArrowFunction && hasReturnColon) { + // However, if the arrow function we were able to parse is followed by another colon + // as in: + // a ? (x): string => x : null + // Then allow the arrow function, and treat the second colon as terminating + // the conditional expression. It's okay to do this because this code would + // be a syntax error in JavaScript (as the second colon shouldn't be there). + if (token() !== 58 /* SyntaxKind.ColonToken */) { + return undefined; + } + } var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseArrowFunctionExpressionBody(isAsync) { + function parseArrowFunctionExpressionBody(isAsync, allowReturnTypeInArrowFunction) { if (token() === 18 /* SyntaxKind.OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* SignatureFlags.Await */ : 0 /* SignatureFlags.None */); } @@ -34578,12 +35087,12 @@ var ts; var savedTopLevel = topLevel; topLevel = false; var node = isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + ? doInAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }) + : doOutsideOfAwaitContext(function () { return parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction); }); topLevel = savedTopLevel; return node; } - function parseConditionalExpressionRest(leftOperand, pos) { + function parseConditionalExpressionRest(leftOperand, pos, allowReturnTypeInArrowFunction) { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. var questionToken = parseOptionalToken(57 /* SyntaxKind.QuestionToken */); if (!questionToken) { @@ -34592,8 +35101,8 @@ var ts; // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. var colonToken; - return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) - ? parseAssignmentExpressionOrHigher() + return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ false); }), colonToken = parseExpectedToken(58 /* SyntaxKind.ColonToken */), ts.nodeIsPresent(colonToken) + ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(79 /* SyntaxKind.Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* SyntaxKind.ColonToken */))), pos); } function parseBinaryExpressionOrHigher(precedence) { @@ -34978,6 +35487,9 @@ var ts; var typeArguments = tryParse(parseTypeArgumentsInExpression); if (typeArguments !== undefined) { parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments); + if (!isTemplateStartOfTaggedTemplate()) { + expression = factory.createExpressionWithTypeArguments(expression, typeArguments); + } } } if (token() === 20 /* SyntaxKind.OpenParenToken */ || token() === 24 /* SyntaxKind.DotToken */ || token() === 22 /* SyntaxKind.OpenBracketToken */) { @@ -35190,9 +35702,22 @@ var ts; } scanJsxIdentifier(); var pos = getNodePos(); - return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 63 /* SyntaxKind.EqualsToken */ ? undefined : - scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */ ? parseLiteralNode() : - parseJsxExpression(/*inExpressionContext*/ true)), pos); + return finishNode(factory.createJsxAttribute(parseIdentifierName(), parseJsxAttributeValue()), pos); + } + function parseJsxAttributeValue() { + if (token() === 63 /* SyntaxKind.EqualsToken */) { + if (scanJsxAttributeValue() === 10 /* SyntaxKind.StringLiteral */) { + return parseLiteralNode(); + } + if (token() === 18 /* SyntaxKind.OpenBraceToken */) { + return parseJsxExpression(/*inExpressionContext*/ true); + } + if (token() === 29 /* SyntaxKind.LessThanToken */) { + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + } + parseErrorAtCurrentToken(ts.Diagnostics.or_JSX_element_expected); + } + return undefined; } function parseJsxSpreadAttribute() { var pos = getNodePos(); @@ -35282,6 +35807,11 @@ var ts; if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) { parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers); } + if (ts.isExpressionWithTypeArguments(expression) && expression.typeArguments) { + var pos_2 = expression.typeArguments.pos - 1; + var end = ts.skipTrivia(sourceText, expression.typeArguments.end) + 1; + parseErrorAt(pos_2, end, ts.Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access); + } return finishNode(propertyAccess, pos); } function parseElementAccessExpressionRest(pos, expression, questionDotToken) { @@ -35407,10 +35937,11 @@ var ts; } nextToken(); var typeArguments = parseDelimitedList(20 /* ParsingContext.TypeArguments */, parseType); - if (!parseExpected(31 /* SyntaxKind.GreaterThanToken */)) { + if (reScanGreaterToken() !== 31 /* SyntaxKind.GreaterThanToken */) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } + nextToken(); // We successfully parsed a type argument list. The next token determines whether we want to // treat it as such. If the type argument list is followed by `(` or a template literal, as in // `f(42)`, we favor the type argument interpretation even though JavaScript would view @@ -35424,9 +35955,18 @@ var ts; case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: // foo `...` case 15 /* SyntaxKind.TemplateHead */: // foo `...${100}...` return true; + // A type argument list followed by `<` never makes sense, and a type argument list followed + // by `>` is ambiguous with a (re-scanned) `>>` operator, so we disqualify both. Also, in + // this context, `+` and `-` are unary operators, not binary operators. + case 29 /* SyntaxKind.LessThanToken */: + case 31 /* SyntaxKind.GreaterThanToken */: + case 39 /* SyntaxKind.PlusToken */: + case 40 /* SyntaxKind.MinusToken */: + return false; } - // Consider something a type argument list only if the following token can't start an expression. - return !isStartOfExpression(); + // We favor the type argument list interpretation when it is immediately followed by + // a line break, a binary operator, or something that can't start an expression. + return scanner.hasPrecedingLineBreak() || isBinaryOperator() || !isStartOfExpression(); } function parsePrimaryExpression() { switch (token()) { @@ -35485,13 +36025,13 @@ var ts; function parseSpreadElement() { var pos = getNodePos(); parseExpected(25 /* SyntaxKind.DotDotDotToken */); - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createSpreadElement(expression), pos); } function parseArgumentOrArrayLiteralElement() { return token() === 25 /* SyntaxKind.DotDotDotToken */ ? parseSpreadElement() : token() === 27 /* SyntaxKind.CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) : - parseAssignmentExpressionOrHigher(); + parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); @@ -35509,16 +36049,16 @@ var ts; var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); if (parseOptionalToken(25 /* SyntaxKind.DotDotDotToken */)) { - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc); } var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } var asteriskToken = parseOptionalToken(41 /* SyntaxKind.AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -35538,7 +36078,7 @@ var ts; var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* SyntaxKind.ColonToken */); if (isShorthandPropertyAssignment) { var equalsToken = parseOptionalToken(63 /* SyntaxKind.EqualsToken */); - var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined; + var objectAssignmentInitializer = equalsToken ? allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }) : undefined; node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer); // Save equals token for error reporting. // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful. @@ -35546,11 +36086,11 @@ var ts; } else { parseExpected(58 /* SyntaxKind.ColonToken */); - var initializer = allowInAnd(parseAssignmentExpressionOrHigher); + var initializer = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); node = factory.createPropertyAssignment(name, initializer); } // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; node.questionToken = questionToken; node.exclamationToken = exclamationToken; @@ -35610,6 +36150,9 @@ var ts; typeArguments = expression.typeArguments; expression = expression.expression; } + if (token() === 28 /* SyntaxKind.QuestionDotToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, ts.getTextOfNodeFromSourceText(sourceText, expression)); + } var argumentList = token() === 20 /* SyntaxKind.OpenParenToken */ ? parseArgumentList() : undefined; return finishNode(factory.createNewExpression(expression, typeArguments, argumentList), pos); } @@ -35720,7 +36263,7 @@ var ts; } var node; if (awaitToken ? parseExpected(160 /* SyntaxKind.OfKeyword */) : parseOptional(160 /* SyntaxKind.OfKeyword */)) { - var expression = allowInAnd(parseAssignmentExpressionOrHigher); + var expression = allowInAnd(function () { return parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); }); parseExpected(21 /* SyntaxKind.CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); } @@ -36125,24 +36668,19 @@ var ts; return modifier.kind === 135 /* SyntaxKind.DeclareKeyword */; } function parseDeclaration() { - // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner - // if we can't reuse the declaration, so that we don't do this work twice? - // // `parseListElement` attempted to get the reused node at this position, // but the ambient context flag was not yet set, so the node appeared // not reusable in that context. - var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier); - if (isAmbient) { - var node = tryReuseAmbientDeclaration(); - if (node) { - return node; - } - } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var decorators = parseDecorators(); var modifiers = parseModifiers(); + var isAmbient = ts.some(modifiers, isDeclareModifier); if (isAmbient) { + var node = tryReuseAmbientDeclaration(pos); + if (node) { + return node; + } for (var _i = 0, _a = modifiers; _i < _a.length; _i++) { var m = _a[_i]; m.flags |= 16777216 /* NodeFlags.Ambient */; @@ -36153,9 +36691,9 @@ var ts; return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); } } - function tryReuseAmbientDeclaration() { + function tryReuseAmbientDeclaration(pos) { return doInsideOfContext(16777216 /* NodeFlags.Ambient */, function () { - var node = currentNode(parsingContext); + var node = currentNode(parsingContext, pos); if (node) { return consumeNode(node); } @@ -36200,7 +36738,7 @@ var ts; // would follow. For recovery and error reporting purposes, return an incomplete declaration. var missing = createMissingNode(276 /* SyntaxKind.MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); - missing.decorators = decorators; + missing.illegalDecorators = decorators; missing.modifiers = modifiers; return missing; } @@ -36212,9 +36750,15 @@ var ts; return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* SyntaxKind.StringLiteral */); } function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { - if (token() !== 18 /* SyntaxKind.OpenBraceToken */ && canParseSemicolon()) { - parseSemicolon(); - return; + if (token() !== 18 /* SyntaxKind.OpenBraceToken */) { + if (flags & 4 /* SignatureFlags.Type */) { + parseTypeMemberSemicolon(); + return; + } + if (canParseSemicolon()) { + parseSemicolon(); + return; + } } return parseFunctionBlock(flags, diagnosticMessage); } @@ -36337,7 +36881,7 @@ var ts; parseSemicolon(); var node = factory.createVariableStatement(modifiers, declarationList); // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker. - node.decorators = decorators; + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36356,7 +36900,8 @@ var ts; var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); setAwaitContext(savedAwaitContext); - var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body); + var node = factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseConstructorName() { @@ -36377,8 +36922,9 @@ var ts; var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */, ts.Diagnostics.or_expected); - var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body); - // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker. + var node = factory.createConstructorDeclaration(modifiers, parameters, body); + // Attach invalid nodes if they exist so that we can report them in the grammar checker. + node.illegalDecorators = decorators; node.typeParameters = typeParameters; node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36392,7 +36938,7 @@ var ts; var parameters = parseParameters(isGenerator | isAsync); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); + var node = factory.createMethodDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), asteriskToken, name, questionToken, typeParameters, parameters, type, body); // An exclamation token on a method is invalid syntax and will be handled by the grammar checker node.exclamationToken = exclamationToken; return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -36402,7 +36948,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = doOutsideOfContext(8192 /* NodeFlags.YieldContext */ | 32768 /* NodeFlags.AwaitContext */ | 4096 /* NodeFlags.DisallowInContext */, parseInitializer); parseSemicolonAfterPropertyName(name, type, initializer); - var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer); + var node = factory.createPropertyDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, questionToken || exclamationToken, type, initializer); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36416,18 +36962,18 @@ var ts; } return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken); } - function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) { + function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind, flags) { var name = parsePropertyName(); var typeParameters = parseTypeParameters(); var parameters = parseParameters(0 /* SignatureFlags.None */); var type = parseReturnType(58 /* SyntaxKind.ColonToken */, /*isType*/ false); - var body = parseFunctionBlockOrSemicolon(0 /* SignatureFlags.None */); + var body = parseFunctionBlockOrSemicolon(flags); var node = kind === 172 /* SyntaxKind.GetAccessor */ - ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) - : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); + ? factory.createGetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, type, body) + : factory.createSetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 173 /* SyntaxKind.SetAccessor */) + if (ts.isSetAccessorDeclaration(node)) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -36493,7 +37039,10 @@ var ts; function parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers) { parseExpectedToken(124 /* SyntaxKind.StaticKeyword */); var body = parseClassStaticBlockBody(); - return withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(decorators, modifiers, body), pos), hasJSDoc); + var node = withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(body), pos), hasJSDoc); + node.illegalDecorators = decorators; + node.modifiers = modifiers; + return node; } function parseClassStaticBlockBody() { var savedYieldContext = inYieldContext(); @@ -36556,6 +37105,15 @@ var ts; } return finishNode(factory.createToken(kind), pos); } + function combineDecoratorsAndModifiers(decorators, modifiers) { + if (!decorators) + return modifiers; + if (!modifiers) + return decorators; + var decoratorsAndModifiers = factory.createNodeArray(ts.concatenate(decorators, modifiers)); + ts.setTextRangePosEnd(decoratorsAndModifiers, decorators.pos, modifiers.end); + return decoratorsAndModifiers; + } /* * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect @@ -36596,10 +37154,10 @@ var ts; return parseClassStaticBlockDeclaration(pos, hasJSDoc, decorators, modifiers); } if (parseContextualModifier(136 /* SyntaxKind.GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 172 /* SyntaxKind.GetAccessor */, 0 /* SignatureFlags.None */); } if (parseContextualModifier(149 /* SyntaxKind.SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 173 /* SyntaxKind.SetAccessor */, 0 /* SignatureFlags.None */); } if (token() === 134 /* SyntaxKind.ConstructorKeyword */ || token() === 10 /* SyntaxKind.StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -36664,8 +37222,8 @@ var ts; } setAwaitContext(savedAwaitContext); var node = kind === 257 /* SyntaxKind.ClassDeclaration */ - ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) - : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); + ? factory.createClassDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members) + : factory.createClassExpression(combineDecoratorsAndModifiers(decorators, modifiers), name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseNameOfClassDeclarationOrExpression() { @@ -36722,7 +37280,8 @@ var ts; var typeParameters = parseTypeParameters(); var heritageClauses = parseHeritageClauses(); var members = parseObjectTypeMembers(); - var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = factory.createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36732,7 +37291,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var type = token() === 138 /* SyntaxKind.IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType(); parseSemicolon(); - var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type); + var node = factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } // In an ambient declaration, the grammar only allows integer literals as initializers. @@ -36757,7 +37317,8 @@ var ts; else { members = createMissingList(); } - var node = factory.createEnumDeclaration(decorators, modifiers, name, members); + var node = factory.createEnumDeclaration(modifiers, name, members); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleBlock() { @@ -36780,7 +37341,8 @@ var ts; var body = parseOptional(24 /* SyntaxKind.DotToken */) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NodeFlags.NestedNamespace */ | namespaceFlag) : parseModuleBlock(); - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36802,7 +37364,8 @@ var ts; else { parseSemicolon(); } - var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); + var node = factory.createModuleDeclaration(modifiers, name, body, flags); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) { @@ -36842,7 +37405,7 @@ var ts; parseSemicolon(); var node = factory.createNamespaceExportDeclaration(name); // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker - node.decorators = decorators; + node.illegalDecorators = decorators; node.modifiers = modifiers; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -36881,14 +37444,15 @@ var ts; assertClause = parseAssertClause(); } parseSemicolon(); - var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause); + var node = factory.createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseAssertEntry() { var pos = getNodePos(); var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* SyntaxKind.StringLiteral */); parseExpected(58 /* SyntaxKind.ColonToken */); - var value = parseAssignmentExpressionOrHigher(); + var value = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); return finishNode(factory.createAssertEntry(name, value), pos); } function parseAssertClause(skipAssertKeyword) { @@ -36925,7 +37489,8 @@ var ts; parseExpected(63 /* SyntaxKind.EqualsToken */); var moduleReference = parseModuleReference(); parseSemicolon(); - var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference); + var node = factory.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference); + node.illegalDecorators = decorators; var finished = withJSDoc(finishNode(node, pos), hasJSDoc); return finished; } @@ -37114,7 +37679,8 @@ var ts; } parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + var node = factory.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) { @@ -37127,10 +37693,11 @@ var ts; else { parseExpected(88 /* SyntaxKind.DefaultKeyword */); } - var expression = parseAssignmentExpressionOrHigher(); + var expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); parseSemicolon(); setAwaitContext(savedAwaitContext); - var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression); + var node = factory.createExportAssignment(modifiers, isExportEquals, expression); + node.illegalDecorators = decorators; return withJSDoc(finishNode(node, pos), hasJSDoc); } var ParsingContext; @@ -37921,7 +38488,6 @@ var ts; if (parseOptional(24 /* SyntaxKind.DotToken */)) { var body = parseJSDocTypeNameWithNamespace(/*nested*/ true); var jsDocNamespaceNode = factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NodeFlags.NestedNamespace */ : undefined); return finishNode(jsDocNamespaceNode, pos); } @@ -38358,10 +38924,10 @@ var ts; } function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { - var pos_2 = node.pos; + var pos_3 = node.pos; var visitNode_1 = function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; + ts.Debug.assert(child.pos >= pos_3); + pos_3 = child.end; }; if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -38370,7 +38936,7 @@ var ts; } } forEachChild(node, visitNode_1); - ts.Debug.assert(pos_2 <= node.end); + ts.Debug.assert(pos_3 <= node.end); } } function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { @@ -38968,6 +39534,7 @@ var ts; ["es2022.error", "lib.es2022.error.d.ts"], ["es2022.intl", "lib.es2022.intl.d.ts"], ["es2022.object", "lib.es2022.object.d.ts"], + ["es2022.sharedmemory", "lib.es2022.sharedmemory.d.ts"], ["es2022.string", "lib.es2022.string.d.ts"], ["esnext.array", "lib.es2022.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], @@ -39181,6 +39748,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, defaultValueDescription: false, @@ -39215,12 +39783,40 @@ var ts; affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, defaultValueDescription: 0 /* ScriptTarget.ES3 */, }; + /*@internal*/ + ts.moduleOptionDeclaration = { + name: "module", + shortName: "m", + type: new ts.Map(ts.getEntries({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + es2020: ts.ModuleKind.ES2020, + es2022: ts.ModuleKind.ES2022, + esnext: ts.ModuleKind.ESNext, + node16: ts.ModuleKind.Node16, + nodenext: ts.ModuleKind.NodeNext, + })), + affectsModuleResolution: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Modules, + description: ts.Diagnostics.Specify_what_module_code_is_generated, + defaultValueDescription: undefined, + }; var commandOptionsWithoutBuild = [ // CommandLine only options { @@ -39282,37 +39878,14 @@ var ts; category: ts.Diagnostics.Command_line_Options, affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, isCommandLineOnly: true, description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, defaultValueDescription: false, }, // Basic ts.targetOptionDeclaration, - { - name: "module", - shortName: "m", - type: new ts.Map(ts.getEntries({ - none: ts.ModuleKind.None, - commonjs: ts.ModuleKind.CommonJS, - amd: ts.ModuleKind.AMD, - system: ts.ModuleKind.System, - umd: ts.ModuleKind.UMD, - es6: ts.ModuleKind.ES2015, - es2015: ts.ModuleKind.ES2015, - es2020: ts.ModuleKind.ES2020, - es2022: ts.ModuleKind.ES2022, - esnext: ts.ModuleKind.ESNext, - node16: ts.ModuleKind.Node16, - nodenext: ts.ModuleKind.NodeNext, - })), - affectsModuleResolution: true, - affectsEmit: true, - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Modules, - description: ts.Diagnostics.Specify_what_module_code_is_generated, - defaultValueDescription: undefined, - }, + ts.moduleOptionDeclaration, { name: "lib", type: "list", @@ -39349,6 +39922,7 @@ var ts; type: jsxOptionMap, affectsSourceFile: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, @@ -39361,6 +39935,7 @@ var ts; shortName: "d", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -39371,6 +39946,7 @@ var ts; name: "declarationMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, @@ -39381,6 +39957,7 @@ var ts; name: "emitDeclarationOnly", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, @@ -39391,6 +39968,7 @@ var ts; name: "sourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -39400,6 +39978,9 @@ var ts; name: "outFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, showInSimplifiedHelpView: true, @@ -39411,6 +39992,8 @@ var ts; name: "outDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, showInSimplifiedHelpView: true, @@ -39421,6 +40004,8 @@ var ts; name: "rootDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Modules, @@ -39431,6 +40016,8 @@ var ts; name: "composite", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isTSConfigOnly: true, category: ts.Diagnostics.Projects, transpileOptionValue: undefined, @@ -39441,6 +40028,8 @@ var ts; name: "tsBuildInfoFile", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsBundleEmitBuildInfo: true, isFilePath: true, paramType: ts.Diagnostics.FILE, category: ts.Diagnostics.Projects, @@ -39452,6 +40041,7 @@ var ts; name: "removeComments", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, defaultValueDescription: false, @@ -39470,6 +40060,7 @@ var ts; name: "importHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, defaultValueDescription: false, @@ -39483,6 +40074,7 @@ var ts; })), affectsEmit: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, defaultValueDescription: 0 /* ImportsNotUsedAsValues.Remove */, @@ -39491,6 +40083,7 @@ var ts; name: "downlevelIteration", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, defaultValueDescription: false, @@ -39509,6 +40102,9 @@ var ts; type: "boolean", // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here // The value of each strictFlag depends on own strictFlag value or this and never accessed directly. + // But we need to store `strict` in builf info, even though it won't be examined directly, so that the + // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_all_strict_type_checking_options, @@ -39518,6 +40114,7 @@ var ts; name: "noImplicitAny", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, @@ -39527,6 +40124,7 @@ var ts; name: "strictNullChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_type_checking_take_into_account_null_and_undefined, @@ -39535,6 +40133,8 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, @@ -39543,6 +40143,8 @@ var ts; { name: "strictBindCallApply", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, @@ -39552,6 +40154,7 @@ var ts; name: "strictPropertyInitialization", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, @@ -39561,6 +40164,7 @@ var ts; name: "noImplicitThis", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, @@ -39570,6 +40174,7 @@ var ts; name: "useUnknownInCatchVariables", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, @@ -39579,6 +40184,8 @@ var ts; name: "alwaysStrict", type: "boolean", affectsSourceFile: true, + affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_use_strict_is_always_emitted, @@ -39589,6 +40196,7 @@ var ts; name: "noUnusedLocals", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, defaultValueDescription: false, @@ -39597,6 +40205,7 @@ var ts; name: "noUnusedParameters", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, defaultValueDescription: false, @@ -39605,6 +40214,7 @@ var ts; name: "exactOptionalPropertyTypes", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, defaultValueDescription: false, @@ -39613,6 +40223,7 @@ var ts; name: "noImplicitReturns", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, defaultValueDescription: false, @@ -39622,6 +40233,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, defaultValueDescription: false, @@ -39630,6 +40242,7 @@ var ts; name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, defaultValueDescription: false, @@ -39638,6 +40251,7 @@ var ts; name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, defaultValueDescription: false, @@ -39645,6 +40259,8 @@ var ts; { name: "noPropertyAccessFromIndexSignature", type: "boolean", + affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: false, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, @@ -39730,6 +40346,7 @@ var ts; name: "allowSyntheticDefaultImports", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, defaultValueDescription: ts.Diagnostics.module_system_or_esModuleInterop @@ -39739,6 +40356,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, @@ -39755,6 +40373,7 @@ var ts; name: "allowUmdGlobalAccess", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules, defaultValueDescription: false, @@ -39776,6 +40395,7 @@ var ts; name: "sourceRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code, @@ -39784,6 +40404,7 @@ var ts; name: "mapRoot", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, @@ -39792,6 +40413,7 @@ var ts; name: "inlineSourceMap", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -39800,6 +40422,7 @@ var ts; name: "inlineSources", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, defaultValueDescription: false, @@ -39809,6 +40432,7 @@ var ts; name: "experimentalDecorators", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, defaultValueDescription: false, @@ -39818,6 +40442,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, defaultValueDescription: false, @@ -39842,6 +40467,7 @@ var ts; type: "string", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, affectsModuleResolution: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, @@ -39859,6 +40485,9 @@ var ts; name: "out", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, + affectsBundleEmitBuildInfo: true, isFilePath: false, // for correct behaviour, please use outFile category: ts.Diagnostics.Backwards_Compatibility, @@ -39870,6 +40499,7 @@ var ts; name: "reactNamespace", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, defaultValueDescription: "`React`", @@ -39877,6 +40507,8 @@ var ts; { name: "skipDefaultLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, defaultValueDescription: false, @@ -39892,6 +40524,7 @@ var ts; name: "emitBOM", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, defaultValueDescription: false, @@ -39903,6 +40536,7 @@ var ts; lf: 1 /* NewLineKind.LineFeed */ })), affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, paramType: ts.Diagnostics.NEWLINE, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Set_the_newline_character_for_emitting_files, @@ -39912,6 +40546,7 @@ var ts; name: "noErrorTruncation", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_truncating_types_in_error_messages, defaultValueDescription: false, @@ -39942,6 +40577,7 @@ var ts; name: "stripInternal", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, defaultValueDescription: false, @@ -39982,6 +40618,7 @@ var ts; name: "noImplicitUseStrict", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, defaultValueDescription: false, @@ -39990,6 +40627,7 @@ var ts; name: "noEmitHelpers", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, defaultValueDescription: false, @@ -39998,6 +40636,7 @@ var ts; name: "noEmitOnError", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, @@ -40007,6 +40646,7 @@ var ts; name: "preserveConstEnums", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, defaultValueDescription: false, @@ -40015,6 +40655,8 @@ var ts; name: "declarationDir", type: "string", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, + affectsDeclarationPath: true, isFilePath: true, paramType: ts.Diagnostics.DIRECTORY, category: ts.Diagnostics.Emit, @@ -40024,6 +40666,8 @@ var ts; { name: "skipLibCheck", type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_all_d_ts_files, defaultValueDescription: false, @@ -40033,6 +40677,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unused_labels, defaultValueDescription: undefined, @@ -40042,6 +40687,7 @@ var ts; type: "boolean", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code, defaultValueDescription: undefined, @@ -40050,6 +40696,7 @@ var ts; name: "suppressExcessPropertyErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, defaultValueDescription: false, @@ -40058,6 +40705,7 @@ var ts; name: "suppressImplicitAnyIndexErrors", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, defaultValueDescription: false, @@ -40082,6 +40730,7 @@ var ts; name: "noStrictGenericChecks", type: "boolean", affectsSemanticDiagnostics: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, defaultValueDescription: false, @@ -40091,6 +40740,7 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, defaultValueDescription: ts.Diagnostics.true_for_ES2022_and_above_including_ESNext @@ -40099,6 +40749,7 @@ var ts; name: "preserveValueImports", type: "boolean", affectsEmit: true, + affectsMultiFileEmitBuildInfo: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, defaultValueDescription: false, @@ -40142,6 +40793,8 @@ var ts; /* @internal */ ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; }); /* @internal */ + ts.affectsDeclarationPathOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsDeclarationPath; }); + /* @internal */ ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); /* @internal */ ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { @@ -40964,7 +41617,7 @@ var ts; return undefined; if (ts.length(specs) !== 1) return specs; - if (specs[0] === "**/*") + if (specs[0] === ts.defaultIncludeSpec) return undefined; return specs; } @@ -40997,6 +41650,7 @@ var ts; return optionDefinition.type; } } + /* @internal */ function getNameOfCompilerOptionValue(value, customTypeMap) { // There is a typeMap associated with this command-line option so use it to map value back to its name return ts.forEachEntry(customTypeMap, function (mapValue, key) { @@ -41005,6 +41659,7 @@ var ts; } }); } + ts.getNameOfCompilerOptionValue = getNameOfCompilerOptionValue; function serializeCompilerOptions(options, pathOptions) { return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); } @@ -41242,6 +41897,8 @@ var ts; // until consistent casing errors are reported return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } + /*@internal*/ + ts.defaultIncludeSpec = "**/*"; /** * Parse the contents of a config file from json or json source file (tsconfig.json). * @param json The contents of the config file to parse @@ -41307,6 +41964,7 @@ var ts; } var includeSpecs = toPropValue(getSpecsFromRaw("include")); var excludeOfRaw = getSpecsFromRaw("exclude"); + var isDefaultIncludeSpec = false; var excludeSpecs = toPropValue(excludeOfRaw); if (excludeOfRaw === "no-prop" && raw.compilerOptions) { var outDir = raw.compilerOptions.outDir; @@ -41316,7 +41974,8 @@ var ts; } } if (filesSpecs === undefined && includeSpecs === undefined) { - includeSpecs = ["**/*"]; + includeSpecs = [ts.defaultIncludeSpec]; + isDefaultIncludeSpec = true; } var validatedIncludeSpecs, validatedExcludeSpecs; // The exclude spec list is converted into a regular expression, which allows us to quickly @@ -41335,7 +41994,8 @@ var ts; validatedFilesSpec: ts.filter(filesSpecs, ts.isString), validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, - pathPatterns: undefined, // Initialized on first use + pathPatterns: undefined, + isDefaultIncludeSpec: isDefaultIncludeSpec, }; } function getFileNames(basePath) { @@ -41995,7 +42655,7 @@ var ts; } if (ts.isImplicitGlob(spec.substring(spec.lastIndexOf(ts.directorySeparator) + 1))) { return { - key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec), + key: ts.removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec)), flags: 1 /* WatchDirectoryFlags.Recursive */ }; } @@ -42165,16 +42825,18 @@ var ts; ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, diagnostics, resultFromCache) { - var _a; + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache) { + var _a, _b; if (resultFromCache) { (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = resultFromCache.affectingLocations).push.apply(_b, affectingLocations); return resultFromCache; } return { resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations, - resolutionDiagnostics: diagnostics + affectingLocations: affectingLocations, + resolutionDiagnostics: diagnostics, }; } function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { @@ -42363,6 +43025,7 @@ var ts; } } var failedLookupLocations = []; + var affectingLocations = []; var features = getDefaultNodeResolutionFeatures(options); // Unlike `import` statements, whose mode-calculating APIs are all guaranteed to return `undefined` if we're in an un-mode-ed module resolution // setting, type references will return their target mode regardless of options because of how the parser works, so we guard against the mode being @@ -42381,6 +43044,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -42397,15 +43061,17 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); + var pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host); resolvedTypeReferenceDirective = { primary: primary, - resolvedFileName: resolvedFileName, - originalPath: arePathsEqual(fileName, resolvedFileName, host) ? undefined : fileName, + // If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedFileName: pathsAreEqual ? fileName : resolvedFileName, + originalPath: pathsAreEqual ? undefined : fileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName), }; } - result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, resolutionDiagnostics: diagnostics }; + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations, affectingLocations: affectingLocations, resolutionDiagnostics: diagnostics }; perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, /*mode*/ resolutionMode, result); if (traceEnabled) traceResult(result); @@ -42480,17 +43146,7 @@ var ts; * Does not try `@types/${packageName}` - use a second pass if needed. */ function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ts.emptyArray, - features: NodeResolutionFeatures.None, - requestContainingDirectory: containingDirectory, - reportDiagnostic: ts.noop - }; + var moduleResolutionState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); return ts.forEachAncestorDirectory(containingDirectory, function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { var nodeModulesFolder = ts.combinePaths(ancestorDirectory, "node_modules"); @@ -42587,7 +43243,7 @@ var ts; ts.createCacheWithRedirects = createCacheWithRedirects; function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { var cache; - return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries }; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear, entries: entries, getInternalMap: getInternalMap }; function getPackageJsonInfo(packageJsonPath) { return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); } @@ -42601,6 +43257,9 @@ var ts; var iter = cache === null || cache === void 0 ? void 0 : cache.entries(); return iter ? ts.arrayFrom(iter) : []; } + function getInternalMap() { + return cache; + } } function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); @@ -42704,15 +43363,18 @@ var ts; } ts.zipToModeAwareCache = zipToModeAwareCache; function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, clear: clear, update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; }, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); - moduleNameToDirectoryMap.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + } function update(options) { updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); } @@ -42788,13 +43450,16 @@ var ts; } ts.createModuleResolutionCache = createModuleResolutionCache; function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { - var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + var perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); - return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + return __assign(__assign(__assign({}, packageJsonInfoCache), perDirectoryResolutionCache), { clear: clear, clearAllExceptPackageJsonInfoCache: clearAllExceptPackageJsonInfoCache }); function clear() { - preDirectoryResolutionCache.clear(); + clearAllExceptPackageJsonInfoCache(); packageJsonInfoCache.clear(); } + function clearAllExceptPackageJsonInfoCache() { + perDirectoryResolutionCache.clear(); + } } ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { @@ -43100,16 +43765,20 @@ var ts; function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.NodeNextDefault, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } + var jsOnlyExtensions = [Extensions.JavaScript]; + var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); + var tsconfigExtensions = [Extensions.TSConfig]; function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { var containingDirectory = ts.getDirectoryPath(containingFile); // es module file or cjs-like input file, use a variant of the legacy cjs resolver that supports the selected modern features var esmMode = resolutionMode === ts.ModuleKind.ESNext ? NodeResolutionFeatures.EsmMode : 0; - return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions, redirectedReference); + var extensions = compilerOptions.noDtsResolution ? [Extensions.TsOnly, Extensions.JavaScript] : tsExtensions; + if (compilerOptions.resolveJsonModule) { + extensions = __spreadArray(__spreadArray([], extensions, true), [Extensions.Json], false); + } + return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference); } - var jsOnlyExtensions = [Extensions.JavaScript]; - var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; - var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions, true), [Extensions.Json], false); - var tsconfigExtensions = [Extensions.TSConfig]; function tryResolveJSModuleWorker(moduleName, initialDir, host) { return nodeModuleNameResolverWorker(NodeResolutionFeatures.None, moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); } @@ -43135,6 +43804,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; // conditions are only used by the node16/nodenext resolver - there's no priority order in the list, //it's essentially a set (priority is determined by object insertion order in the object we look at). var conditions = features & NodeResolutionFeatures.EsmMode ? ["node", "import", "types"] : ["node", "require", "types"]; @@ -43147,6 +43817,7 @@ var ts; host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, packageJsonInfoCache: cache, features: features, conditions: conditions, @@ -43154,7 +43825,7 @@ var ts; reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; 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, diagnostics, state.resultFromCache); + 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) { var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); @@ -43180,8 +43851,10 @@ var ts; var resolvedValue = resolved_1.value; if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - var originalPath = arePathsEqual(path, resolvedValue.path, host) ? undefined : resolvedValue.path; - resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath }); + var pathsAreEqual = arePathsEqual(path, resolvedValue.path, host); + var originalPath = pathsAreEqual ? undefined : resolvedValue.path; + // If the path and realpath are differing only in casing prefer path so that we can issue correct errors for casing under forceConsistentCasingInFileNames + resolvedValue = __assign(__assign({}, resolvedValue), { path: pathsAreEqual ? resolvedValue.path : path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; @@ -43444,17 +44117,9 @@ var ts; var entrypoints; var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript; var features = getDefaultNodeResolutionFeatures(options); - var requireState = { - compilerOptions: options, - host: host, - traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], - packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), - conditions: ["node", "require", "types"], - features: features, - requestContainingDirectory: packageJsonInfo.packageDirectory, - reportDiagnostic: ts.noop - }; + var requireState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options); + requireState.conditions = ["node", "require", "types"]; + requireState.requestContainingDirectory = packageJsonInfo.packageDirectory; var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, /*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths); entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path); @@ -43527,22 +44192,27 @@ var ts; } } } - /** - * A function for locating the package.json scope for a given path - */ /*@internal*/ - function getPackageScopeForPath(fileName, packageJsonInfoCache, host, options) { - var state = { + function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) { + return { host: host, compilerOptions: options, traceEnabled: isTraceEnabled(options, host), - failedLookupLocations: [], + failedLookupLocations: ts.noopPush, + affectingLocations: ts.noopPush, packageJsonInfoCache: packageJsonInfoCache, - features: 0, - conditions: [], + features: NodeResolutionFeatures.None, + conditions: ts.emptyArray, requestContainingDirectory: undefined, reportDiagnostic: ts.noop }; + } + ts.getTemporaryModuleResolutionState = getTemporaryModuleResolutionState; + /** + * A function for locating the package.json scope for a given path + */ + /*@internal*/ + function getPackageScopeForPath(fileName, state) { var parts = ts.getPathComponents(fileName); parts.pop(); while (parts.length > 0) { @@ -43569,6 +44239,7 @@ var ts; if (typeof existing !== "boolean") { if (traceEnabled) trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + state.affectingLocations.push(packageJsonPath); return existing; } else { @@ -43587,6 +44258,7 @@ var ts; var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined }; (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + state.affectingLocations.push(packageJsonPath); return result; } else { @@ -43711,7 +44383,7 @@ var ts; var _a, _b; var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope || !scope.packageJsonContent.exports) { return undefined; } @@ -43770,7 +44442,7 @@ var ts; } var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames; var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames)); - var scope = getPackageScopeForPath(directoryPath, state.packageJsonInfoCache, state.host, state.compilerOptions); + var scope = getPackageScopeForPath(directoryPath, state); if (!scope) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath); @@ -43792,13 +44464,38 @@ var ts; } return toSearchResult(/*value*/ undefined); } + /** + * @internal + * From https://github.com/nodejs/node/blob/8f39f51cbbd3b2de14b9ee896e26421cc5b20121/lib/internal/modules/esm/resolve.js#L722 - + * "longest" has some nuance as to what "longest" means in the presence of pattern trailers + */ + function comparePatternKeys(a, b) { + var aPatternIndex = a.indexOf("*"); + var bPatternIndex = b.indexOf("*"); + var baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + var baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + if (baseLenA > baseLenB) + return -1; + if (baseLenB > baseLenA) + return 1; + if (aPatternIndex === -1) + return 1; + if (bPatternIndex === -1) + return -1; + if (a.length > b.length) + return -1; + if (b.length > a.length) + return 1; + return 0; + } + ts.comparePatternKeys = comparePatternKeys; function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { 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); } - var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), function (a, b) { return a.length - b.length; }); + 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++) { var potentialTarget = expandingKeys_1[_i]; if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) { @@ -44117,8 +44814,8 @@ var ts; var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths); if (!pathAndExtension && packageInfo - && packageInfo.packageJsonContent.exports === undefined - && packageInfo.packageJsonContent.main === undefined + // eslint-disable-next-line no-null/no-null + && (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null) && state.features & NodeResolutionFeatures.EsmMode) { // EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume // a default `index.js` entrypoint if no `main` or `exports` are present @@ -44227,12 +44924,25 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; + var affectingLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: cache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: containingDirectory, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, + /*isExternalLibraryImport*/ false, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { @@ -44275,10 +44985,23 @@ var ts; trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; + var affectingLocations = []; var diagnostics = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: undefined, reportDiagnostic: function (diag) { return void diagnostics.push(diag); } }; + var state = { + compilerOptions: compilerOptions, + host: host, + traceEnabled: traceEnabled, + failedLookupLocations: failedLookupLocations, + affectingLocations: affectingLocations, + packageJsonInfoCache: packageJsonInfoCache, + features: NodeResolutionFeatures.None, + conditions: [], + requestContainingDirectory: undefined, + reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, + }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false, /*cache*/ undefined, /*redirectedReference*/ undefined); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, diagnostics, state.resultFromCache); + return createResolvedModuleWithFailedLookupLocations(resolved, + /*isExternalLibraryImport*/ true, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -44644,7 +45367,7 @@ var ts; case 164 /* SyntaxKind.Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind, ", expected JSDocFunctionType"); }); + ts.Debug.assert(node.parent.kind === 317 /* SyntaxKind.JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind), ", expected JSDocFunctionType"); }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -45828,8 +46551,6 @@ var ts; // - `BindingElement: BindingPattern Initializer?` // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization // - `BindingElement: BindingPattern Initializer?` - bindEach(node.decorators); - bindEach(node.modifiers); bind(node.dotDotDotToken); bind(node.propertyName); bind(node.initializer); @@ -46170,37 +46891,6 @@ var ts; typeLiteralSymbol.members.set(symbol.escapedName, symbol); } function bindObjectLiteralExpression(node) { - var ElementKind; - (function (ElementKind) { - ElementKind[ElementKind["Property"] = 1] = "Property"; - ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; - })(ElementKind || (ElementKind = {})); - if (inStrictMode && !ts.isAssignmentTarget(node)) { - var seen = new ts.Map(); - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 298 /* SyntaxKind.SpreadAssignment */ || prop.name.kind !== 79 /* SyntaxKind.Identifier */) { - continue; - } - var identifier = prop.name; - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 296 /* SyntaxKind.PropertyAssignment */ || prop.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || prop.kind === 169 /* SyntaxKind.MethodDeclaration */ - ? 1 /* ElementKind.Property */ - : 2 /* ElementKind.Accessor */; - var existingKind = seen.get(identifier.escapedText); - if (!existingKind) { - seen.set(identifier.escapedText, currentKind); - continue; - } - } - } return bindAnonymousDeclaration(node, 4096 /* SymbolFlags.ObjectLiteral */, "__object" /* InternalSymbolName.Object */); } function bindJsxAttributes(node) { @@ -46857,7 +47547,7 @@ var ts; } } function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { + if (ts.some(node.modifiers)) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level @@ -46894,12 +47584,14 @@ var ts; } } function setCommonJsModuleIndicator(node) { - if (file.externalModuleIndicator) { + if (file.externalModuleIndicator && file.externalModuleIndicator !== true) { return false; } if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } } return true; } @@ -47313,7 +48005,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) && !ts.getJSDocTypeTag(node) && !(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */)) { + var possibleVariableDecl = node.kind === 254 /* SyntaxKind.VariableDeclaration */ ? node : node.parent.parent; + if (ts.isInJSFile(node) && + ts.isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && + !ts.getJSDocTypeTag(node) && + !(ts.getCombinedModifierFlags(node) & 1 /* ModifierFlags.Export */)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* SymbolFlags.Alias */, 2097152 /* SymbolFlags.AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -47503,10 +48199,11 @@ var ts; } function isExportsOrModuleExportsOrAlias(sourceFile, node) { var i = 0; - var q = [node]; - while (q.length && i < 100) { + var q = ts.createQueue(); + q.enqueue(node); + while (!q.isEmpty() && i < 100) { i++; - node = q.shift(); + node = q.dequeue(); if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) { return true; } @@ -47514,10 +48211,10 @@ var ts; var symbol = lookupSymbolForName(sourceFile, node.escapedText); if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) { var init = symbol.valueDeclaration.initializer; - q.push(init); + q.enqueue(init); if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) { - q.push(init.left); - q.push(init.right); + q.enqueue(init.left); + q.enqueue(init.right); } } } @@ -47777,7 +48474,10 @@ var ts; TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull"; TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy"; TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy"; - TypeFacts[TypeFacts["All"] = 16777215] = "All"; + TypeFacts[TypeFacts["IsUndefined"] = 16777216] = "IsUndefined"; + TypeFacts[TypeFacts["IsNull"] = 33554432] = "IsNull"; + TypeFacts[TypeFacts["IsUndefinedOrNull"] = 50331648] = "IsUndefinedOrNull"; + TypeFacts[TypeFacts["All"] = 134217727] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. @@ -47819,25 +48519,17 @@ var ts; TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts"; TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts"; TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts"; - TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts"; - TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts"; - TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["VoidFacts"] = 9830144] = "VoidFacts"; + TypeFacts[TypeFacts["UndefinedFacts"] = 26607360] = "UndefinedFacts"; + TypeFacts[TypeFacts["NullFacts"] = 42917664] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 83427327] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 83886079] = "EmptyObjectFacts"; + TypeFacts[TypeFacts["UnknownFacts"] = 83886079] = "UnknownFacts"; TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE"; - TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; // Masks TypeFacts[TypeFacts["OrFactsMask"] = 8256] = "OrFactsMask"; - TypeFacts[TypeFacts["AndFactsMask"] = 16768959] = "AndFactsMask"; - })(TypeFacts || (TypeFacts = {})); - var typeofEQFacts = new ts.Map(ts.getEntries({ - string: 1 /* TypeFacts.TypeofEQString */, - number: 2 /* TypeFacts.TypeofEQNumber */, - bigint: 4 /* TypeFacts.TypeofEQBigInt */, - boolean: 8 /* TypeFacts.TypeofEQBoolean */, - symbol: 16 /* TypeFacts.TypeofEQSymbol */, - undefined: 65536 /* TypeFacts.EQUndefined */, - object: 32 /* TypeFacts.TypeofEQObject */, - function: 64 /* TypeFacts.TypeofEQFunction */ - })); + TypeFacts[TypeFacts["AndFactsMask"] = 134209471] = "AndFactsMask"; + })(TypeFacts = ts.TypeFacts || (ts.TypeFacts = {})); var typeofNEFacts = new ts.Map(ts.getEntries({ string: 256 /* TypeFacts.TypeofNEString */, number: 512 /* TypeFacts.TypeofNENumber */, @@ -47872,7 +48564,7 @@ var ts; CheckMode[CheckMode["RestBindingElement"] = 64] = "RestBindingElement"; // e.g. in `const { a, ...rest } = foo`, when checking the type of `foo` to determine the type of `rest`, // we need to preserve generic types instead of substituting them for constraints - })(CheckMode || (CheckMode = {})); + })(CheckMode = ts.CheckMode || (ts.CheckMode = {})); var SignatureCheckMode; (function (SignatureCheckMode) { SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback"; @@ -47880,7 +48572,7 @@ var ts; SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes"; SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity"; SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback"; - })(SignatureCheckMode || (SignatureCheckMode = {})); + })(SignatureCheckMode = ts.SignatureCheckMode || (ts.SignatureCheckMode = {})); var IntersectionState; (function (IntersectionState) { IntersectionState[IntersectionState["None"] = 0] = "None"; @@ -48214,7 +48906,7 @@ var ts; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); - return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + return node ? getContextualTypeForObjectLiteralElement(node, /*contextFlags*/ undefined) : undefined; }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -48222,7 +48914,7 @@ var ts; }, getContextualTypeForJsxAttribute: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); - return node && getContextualTypeForJsxAttribute(node); + return node && getContextualTypeForJsxAttribute(node, /*contextFlags*/ undefined); }, isContextSensitive: isContextSensitive, getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, @@ -48336,9 +49028,9 @@ var ts; return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, - tryGetThisTypeAt: function (nodeIn, includeGlobalThis) { + tryGetThisTypeAt: function (nodeIn, includeGlobalThis, container) { var node = ts.getParseTreeNode(nodeIn); - return node && tryGetThisTypeAt(node, includeGlobalThis); + return node && tryGetThisTypeAt(node, includeGlobalThis, container); }, getTypeArgumentConstraint: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); @@ -48428,6 +49120,7 @@ var ts; var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); var subtypeReductionCache = new ts.Map(); + var cachedTypes = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var markerTypes = new ts.Set(); @@ -48436,11 +49129,10 @@ var ts; var unresolvedSymbols = new ts.Map(); var errorTypes = new ts.Map(); var anyType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); - var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); + var autoType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 262144 /* ObjectFlags.NonInferrableType */); var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any"); var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error"); var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved"); - var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown"); @@ -48469,8 +49161,7 @@ var ts; var esSymbolType = createIntrinsicType(4096 /* TypeFlags.ESSymbol */, "symbol"); var voidType = createIntrinsicType(16384 /* TypeFlags.Void */, "void"); var neverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); + var silentNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never", 262144 /* ObjectFlags.NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* TypeFlags.NonPrimitive */, "object"); @@ -48480,16 +49171,30 @@ var ts; var numberOrBigIntType = getUnionType([numberType, bigintType]); var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]); var numericStringType = getTemplateLiteralType(["", ""], [numberType]); // The `${number}` type - var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }); - var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }); + var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }, function () { return "(restrictive mapper)"; }); + var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? wildcardType : t; }, function () { return "(permissive mapper)"; }); var uniqueLiteralType = createIntrinsicType(131072 /* TypeFlags.Never */, "never"); // `uniqueLiteralType` is a special `never` flagged by union reduction to behave as a literal - var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }); // replace all type parameters with the unique literal type (disregarding constraints) + var uniqueLiteralMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeFlags.TypeParameter */ ? uniqueLiteralType : t; }, function () { return "(unique literal mapper)"; }); // replace all type parameters with the unique literal type (disregarding constraints) + var outofbandVarianceMarkerHandler; + var reportUnreliableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); + } + return t; + }, function () { return "(unmeasurable reporter)"; }); + var reportUnmeasurableMapper = makeFunctionTypeMapper(function (t) { + if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { + outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); + } + return t; + }, function () { return "(unreliable reporter)"; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyJsxObjectType.objectFlags |= 2048 /* ObjectFlags.JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* SymbolFlags.TypeLiteral */, "__type" /* InternalSymbolName.Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray)]) : unknownType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); emptyGenericType.instantiations = new ts.Map(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, ts.emptyArray); @@ -48503,6 +49208,9 @@ var ts; var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); + var markerSuperTypeForCheck = createTypeParameter(); + var markerSubTypeForCheck = createTypeParameter(); + markerSubTypeForCheck.constraint = markerSuperTypeForCheck; var noTypePredicate = createTypePredicate(1 /* TypePredicateKind.Identifier */, "<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* SignatureFlags.None */); @@ -48632,21 +49340,13 @@ var ts; var potentialNewTargetCollisions = []; var potentialWeakMapSetCollisions = []; var potentialReflectCollisions = []; + var potentialUnusedRenamedBindingElementsInTypes = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); - var typeofTypesByName = new ts.Map(ts.getEntries({ - string: stringType, - number: numberType, - bigint: bigintType, - boolean: booleanType, - symbol: esSymbolType, - undefined: undefinedType - })); var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var outofbandVarianceMarkerHandler; var subtypeRelation = new ts.Map(); var strictSubtypeRelation = new ts.Map(); var assignableRelation = new ts.Map(); @@ -48672,6 +49372,14 @@ var ts; ]; initializeTypeChecker(); return checker; + function getCachedType(key) { + return key ? cachedTypes.get(key) : undefined; + } + function setCachedType(key, type) { + if (key) + cachedTypes.set(key, type); + return type; + } function getJsxNamespace(location) { if (location) { var file = ts.getSourceFileOfNode(location); @@ -49536,6 +50244,7 @@ var ts; if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & 111551 /* SymbolFlags.Value */)) { // Remember the property node, it will be used later to report appropriate error + ts.Debug.assertNode(location, ts.isPropertyDeclaration); propertyWithInvalidInitializer = location; } } @@ -49725,11 +50434,27 @@ var ts; } } } + // The invalid initializer error is needed in two situation: + // 1. When result is undefined, after checking for a missing "this." + // 2. When result is defined + function checkAndReportErrorForInvalidInitializer() { + if (propertyWithInvalidInitializer && !(useDefineForClassFields && ts.getEmitScriptTarget(compilerOptions) >= 9 /* ScriptTarget.ES2022 */)) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed + // with ESNext+useDefineForClassFields because the scope semantics are different. + error(errorLocation, errorLocation && propertyWithInvalidInitializer.type && ts.textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) + ? ts.Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor + : ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg)); + return true; + } + return false; + } if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(function () { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + !checkAndReportErrorForInvalidInitializer() && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && @@ -49737,7 +50462,16 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { + var suggestedLib = void 0; + // Report missing lib first + if (nameArg) { + suggestedLib = getSuggestedLibForNonExistentName(nameArg); + if (suggestedLib) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib); + } + } + // then spelling suggestions + if (!suggestedLib && getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -49756,16 +50490,9 @@ var ts; } } } - if (!suggestion) { - if (nameArg) { - var lib = getSuggestedLibForNonExistentName(nameArg); - if (lib) { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib); - } - else { - error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); - } - } + // And then fall back to unspecified "not found" + if (!suggestion && !suggestedLib && nameArg) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); } suggestionCount++; } @@ -49773,12 +50500,7 @@ var ts; } return undefined; } - if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ScriptTarget.ESNext */ && useDefineForClassFields)) { - // We have a match, but the reference occurred within a property initializer and the identifier also binds - // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed - // with ESNext+useDefineForClassFields because the scope semantics are different. - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + else if (checkAndReportErrorForInvalidInitializer()) { return undefined; } // Perform extra checks only if error reporting was requested @@ -49880,7 +50602,7 @@ var ts; if (decl.kind === 163 /* SyntaxKind.TypeParameter */) { var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); } } } @@ -49989,7 +50711,12 @@ var ts; function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { if (isPrimitiveTypeName(name)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(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)); + } + else { + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + } return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); @@ -50009,6 +50736,16 @@ var ts; } return false; } + function isExtendedByInterface(node) { + var grandparent = node.parent.parent; + var parentOfGrandparent = grandparent.parent; + if (grandparent && parentOfGrandparent) { + var isExtending = ts.isHeritageClause(grandparent) && grandparent.token === 94 /* SyntaxKind.ExtendsKeyword */; + var isInterface = ts.isInterfaceDeclaration(parentOfGrandparent); + return isExtending && isInterface; + } + return false; + } function maybeMappedType(node, symbol) { var container = ts.findAncestor(node.parent, function (n) { return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit"; @@ -50140,7 +50877,8 @@ var ts; && isAliasableOrJsExpression(node.parent.right) || node.kind === 297 /* SyntaxKind.ShorthandPropertyAssignment */ || node.kind === 296 /* SyntaxKind.PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node); + || node.kind === 254 /* SyntaxKind.VariableDeclaration */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) + || node.kind === 203 /* SyntaxKind.BindingElement */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -50233,7 +50971,7 @@ var ts; return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker - return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); + return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { var _a; @@ -50511,10 +51249,6 @@ var ts; checkExpressionCached(expression); return getNodeLinks(expression).resolvedSymbol; } - function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) { - var expression = node.initializer; - return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve); - } function getTargetOfAccessExpression(node, dontRecursivelyResolve) { if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */)) { return undefined; @@ -50546,7 +51280,7 @@ var ts; case 297 /* SyntaxKind.ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* SymbolFlags.Value */ | 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); case 296 /* SyntaxKind.PropertyAssignment */: - return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); + return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); case 207 /* SyntaxKind.ElementAccessExpression */: case 206 /* SyntaxKind.PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); @@ -50951,7 +51685,40 @@ var ts; // An override clause will take effect for type-only imports and import types, and allows importing the types across formats, regardless of // normal mode restrictions if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext && !ts.getResolutionModeOverrideForClause(overrideClause)) { - error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); + if (ts.findAncestor(location, ts.isImportEqualsDeclaration)) { + // ImportEquals in a ESM file resolving to another ESM file + error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); + } + else { + // CJS file resolving to an ESM file + var diagnosticDetails = void 0; + var ext = ts.tryGetExtensionFromPath(currentSourceFile.fileName); + if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) { + var scope = currentSourceFile.packageJsonScope; + var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined; + if (scope && !scope.packageJsonContent.type) { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json")); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, ts.combinePaths(scope.packageDirectory, "package.json")); + } + } + else { + if (targetExt) { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, targetExt); + } + else { + diagnosticDetails = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module); + } + } + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(diagnosticDetails, ts.Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, moduleReference))); + } } } // merged symbol is module declaration symbol combined with all augmentations @@ -51460,8 +52227,9 @@ var ts; function getExportSymbolOfValueSymbolIfExported(symbol) { return getMergedSymbol(symbol && (symbol.flags & 1048576 /* SymbolFlags.ExportValue */) !== 0 && symbol.exportSymbol || symbol); } - function symbolIsValue(symbol) { - return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && !getTypeOnlyAliasDeclaration(symbol)); + function symbolIsValue(symbol, includeTypeOnlyMembers) { + return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || + symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -51501,7 +52269,7 @@ var ts; return type; } function createTypeofType() { - return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getStringLiteralType)); + return getUnionType(ts.arrayFrom(typeofNEFacts.keys(), getStringLiteralType)); } function createTypeParameter(symbol) { var type = createType(262144 /* TypeFlags.TypeParameter */); @@ -51910,13 +52678,25 @@ var ts; && isDeclarationVisible(declaration.parent)) { return addVisibleAlias(declaration, declaration); } - else if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isBindingElement(declaration) && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement - && ts.isVariableDeclaration(declaration.parent.parent) - && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) - && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) - && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) - && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { - return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + else if (ts.isBindingElement(declaration)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement + && ts.isVariableDeclaration(declaration.parent.parent) + && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent) + && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* ModifierFlags.Export */) + && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) + && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); + } + else if (symbol.flags & 2 /* SymbolFlags.BlockScopedVariable */) { + var variableStatement = ts.findAncestor(declaration, ts.isVariableStatement); + if (ts.hasSyntacticModifier(variableStatement, 1 /* ModifierFlags.Export */)) { + return true; + } + if (!isDeclarationVisible(variableStatement.parent)) { + return false; + } + return addVisibleAlias(declaration, variableStatement); + } } // Declaration is not visible return false; @@ -51958,6 +52738,9 @@ var ts; if (symbol && symbol.flags & 262144 /* SymbolFlags.TypeParameter */ && meaning & 788968 /* SymbolFlags.Type */) { return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; } + if (!symbol && ts.isThisIdentifier(firstIdentifier) && isSymbolAccessible(getSymbolOfNode(ts.getThisContainer(firstIdentifier, /*includeArrowFunctions*/ false)), firstIdentifier, meaning, /*computeAliases*/ false).accessibility === 0 /* SymbolAccessibility.Accessible */) { + return { accessibility: 0 /* SymbolAccessibility.Accessible */ }; + } // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* SymbolAccessibility.NotAccessible */, @@ -52046,7 +52829,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* TypeFormatFlags.None */; } - return flags & 814775659 /* TypeFormatFlags.NodeBuilderFlagsMask */; + return flags & 848330091 /* TypeFormatFlags.NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { return !!type.symbol && !!(type.symbol.flags & 32 /* SymbolFlags.Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* TypeFlags.Object */) && !!(ts.getObjectFlags(type) & 16777216 /* ObjectFlags.IsClassInstanceClone */))); @@ -52148,6 +52931,12 @@ var ts; return context.truncating = context.approximateLength > ((context.flags & 1 /* NodeBuilderFlags.NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { + var savedFlags = context.flags; + var typeNode = typeToTypeNodeWorker(type, context); + context.flags = savedFlags; + return typeNode; + } + function typeToTypeNodeWorker(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); } @@ -52287,6 +53076,9 @@ var ts; var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* SymbolFlags.Class */)) return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes); + if (ts.length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) { + return ts.factory.createArrayTypeNode(typeArgumentNodes[0]); + } return symbolToTypeNode(type.aliasSymbol, context, 788968 /* SymbolFlags.Type */, typeArgumentNodes); } var objectFlags = ts.getObjectFlags(type); @@ -52323,8 +53115,8 @@ var ts; if (type.symbol) { return symbolToTypeNode(type.symbol, context, 788968 /* SymbolFlags.Type */); } - var name = (type === markerSuperType || type === markerSubType) && varianceTypeParameter && varianceTypeParameter.symbol ? - (type === markerSubType ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; + var name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? + (type === markerSubTypeForCheck ? "sub-" : "super-") + ts.symbolName(varianceTypeParameter.symbol) : "?"; return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name), /*typeArguments*/ undefined); } if (type.flags & 1048576 /* TypeFlags.Union */ && type.origin) { @@ -52390,7 +53182,7 @@ var ts; var name = typeParameterToName(newParam, context); var newTypeVariable = ts.factory.createTypeReferenceNode(name); context.approximateLength += 37; // 15 each for two added conditionals, 7 for an added infer type - var newMapper = prependTypeMapping(type.root.checkType, newParam, type.combinedMapper || type.mapper); + var newMapper = prependTypeMapping(type.root.checkType, newParam, type.mapper); var saveInferTypeParameters_1 = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode_1 = typeToTypeNodeHelper(instantiateType(type.root.extendsType, newMapper), context); @@ -52431,6 +53223,10 @@ var ts; } return typeToTypeNodeHelper(type, context); } + function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) { + return isMappedTypeWithKeyofConstraintDeclaration(type) + && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */); + } function createMappedTypeNodeFromType(type) { ts.Debug.assert(!!(type.flags & 524288 /* TypeFlags.Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined; @@ -52440,7 +53236,7 @@ var ts; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` - if (!(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { var newParam = createTypeParameter(createSymbol(262144 /* SymbolFlags.TypeParameter */, "T")); var name = typeParameterToName(newParam, context); newTypeVariable = ts.factory.createTypeReferenceNode(name); @@ -52456,11 +53252,12 @@ var ts; var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; var result = ts.setEmitFlags(mappedTypeNode, 1 /* EmitFlags.SingleLine */); - if (isMappedTypeWithKeyofConstraintDeclaration(type) && !(getModifiersTypeFromMappedType(type).flags & 262144 /* TypeFlags.TypeParameter */) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { + if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type) && context.flags & 4 /* NodeBuilderFlags.GenerateNamesForShadowedTypeParams */) { // homomorphic mapped type with a non-homomorphic naive inlining // wrap it with a conditional like `SomeModifiersType extends infer U ? {..the mapped type...} : never` to ensure the resulting // type stays homomorphic - return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); + var originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type.declaration.typeParameter.constraint.type)) || unknownType, type.mapper); + return ts.factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), ts.factory.createInferTypeNode(ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, ts.factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* TypeFlags.Unknown */ ? undefined : typeToTypeNodeHelper(originalConstraint, context))), result, ts.factory.createKeywordTypeNode(143 /* SyntaxKind.NeverKeyword */)); } return result; } @@ -52477,7 +53274,7 @@ var ts; // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* SymbolFlags.Class */ && !getBaseTypeVariableOfClass(symbol) - && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 226 /* SyntaxKind.ClassExpression */ && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */) || + && !(symbol.valueDeclaration && ts.isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* NodeBuilderFlags.WriteClassExpressionAsTypeLiteral */ && (!ts.isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*computeAliases*/ false).accessibility !== 0 /* SymbolAccessibility.Accessible */)) || symbol.flags & (384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -52743,7 +53540,7 @@ var ts; var id = ids_1[_i]; qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id; } - return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf); + return ts.factory.updateImportTypeNode(root, root.argument, root.assertions, qualifier, typeArguments, root.isTypeOf); } else { // first shift type arguments @@ -52847,7 +53644,7 @@ var ts; anyType : getNonMissingTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* CheckFlags.Late */ && isLateBoundName(propertySymbol.escapedName)) { + if (context.tracker.trackSymbol && isLateBoundName(propertySymbol.escapedName)) { if (propertySymbol.declarations) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { @@ -52992,7 +53789,6 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context); var indexingParameter = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, @@ -53004,8 +53800,7 @@ var ts; context.encounteredError = true; } context.approximateLength += (name.length + 4); - return ts.factory.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); + return ts.factory.createIndexSignature(indexInfo.isReadonly ? [ts.factory.createToken(145 /* SyntaxKind.ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { var _a, _b, _c, _d; @@ -53024,7 +53819,7 @@ var ts; var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* CheckFlags.RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 171 /* SyntaxKind.Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); - var thisParameter = tryGetThisParameterDeclaration(signature, context); + var thisParameter = context.flags & 33554432 /* NodeBuilderFlags.OmitThisParameter */ ? undefined : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { parameters.unshift(thisParameter); } @@ -53057,15 +53852,15 @@ var ts; var node = kind === 174 /* SyntaxKind.CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 175 /* SyntaxKind.ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 168 /* SyntaxKind.MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 169 /* SyntaxKind.MethodDeclaration */ ? ts.factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 171 /* SyntaxKind.Constructor */ ? ts.factory.createConstructorDeclaration(modifiers, parameters, /*body*/ undefined) : + kind === 172 /* SyntaxKind.GetAccessor */ ? ts.factory.createGetAccessorDeclaration(modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 173 /* SyntaxKind.SetAccessor */ ? ts.factory.createSetAccessorDeclaration(modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 176 /* SyntaxKind.IndexSignature */ ? ts.factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 317 /* SyntaxKind.JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 179 /* SyntaxKind.FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : kind === 180 /* SyntaxKind.ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 256 /* SyntaxKind.FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : kind === 213 /* SyntaxKind.FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : kind === 214 /* SyntaxKind.ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); @@ -53082,7 +53877,6 @@ var ts; var thisTag = ts.getJSDocThisTag(signature.declaration); if (thisTag && thisTag.typeExpression) { return ts.factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "this", /* questionToken */ undefined, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); @@ -53114,7 +53908,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); - var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined; + var modifiers = !(context.flags & 8192 /* NodeBuilderFlags.OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && ts.canHaveModifiers(parameterDeclaration) ? ts.map(ts.getModifiers(parameterDeclaration), ts.factory.cloneNode) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* CheckFlags.RestParameter */; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* SyntaxKind.DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -53125,21 +53919,27 @@ var ts; ts.symbolName(parameterSymbol); var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* CheckFlags.OptionalParameter */; var questionToken = isOptional ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined; - var parameterNode = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, + var parameterNode = ts.factory.createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { - return elideInitializerAndSetEmitFlags(node); - function elideInitializerAndSetEmitFlags(node) { + return elideInitializerAndPropertyRenamingAndSetEmitFlags(node); + function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) { if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { trackComputedName(node.expression, context.enclosingDeclaration, context); } - var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); + var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags); if (ts.isBindingElement(visited)) { - visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, - /*initializer*/ undefined); + if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, + /* propertyName*/ undefined, visited.propertyName, + /*initializer*/ undefined); + } + else { + visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, + /*initializer*/ undefined); + } } if (!ts.nodeIsSynthesized(visited)) { visited = ts.factory.cloneNode(visited); @@ -53348,6 +54148,7 @@ var ts; return symbol.parent ? ts.factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var _a, _b, _c, _d; var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module var isTypeOf = meaning === 111551 /* SymbolFlags.Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { @@ -53365,6 +54166,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral("import")) ]))); + (_b = (_a = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _b === void 0 ? void 0 : _b.call(_a); } } if (!specifier) { @@ -53384,6 +54186,7 @@ var ts; assertion = ts.factory.createImportTypeAssertionContainer(ts.factory.createAssertClause(ts.factory.createNodeArray([ ts.factory.createAssertEntry(ts.factory.createStringLiteral("resolution-mode"), ts.factory.createStringLiteral(swappedMode === ts.ModuleKind.ESNext ? "import" : "require")) ]))); + (_d = (_c = context.tracker).reportImportTypeNodeResolutionModeOverride) === null || _d === void 0 ? void 0 : _d.call(_c); } } if (!assertion) { @@ -53785,9 +54588,7 @@ var ts; } if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature( - /*decorators*/ undefined, /*modifiers*/ undefined, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdotToken*/ undefined, "x", /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); @@ -53795,14 +54596,13 @@ var ts; if (ts.isJSDocFunctionType(node)) { if (ts.isJSDocConstructSignature(node)) { var newTypeNode_1; - return ts.factory.createConstructorTypeNode(node.modifiers, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + return ts.factory.createConstructorTypeNode( + /*modifiers*/ undefined, ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.factory.createParameterDeclaration( /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } else { return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); } @@ -53821,7 +54621,7 @@ var ts; !(ts.length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) { return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); } - return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.assertions, node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { var _a = trackExistingEntityName(node, context, includePrivateSymbol), introducesError = _a.introducesError, result = _a.node; @@ -53873,7 +54673,7 @@ var ts; } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 169 /* SyntaxKind.MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 168 /* SyntaxKind.MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -53934,8 +54734,7 @@ var ts; var name_3 = ns.name; var body = ns.body; if (ts.length(excessExports)) { - ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, + ns = ts.factory.updateModuleDeclaration(ns, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements, true), [ts.factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, /*alias*/ undefined, id); })), /*moduleSpecifier*/ undefined)], false)))); @@ -53961,7 +54760,6 @@ var ts; if (ts.length(exports) > 1) { var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; }); statements = __spreadArray(__spreadArray([], nonExports, true), [ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), /*moduleSpecifier*/ undefined)], false); @@ -53976,7 +54774,6 @@ var ts; // remove group members from statements and then merge group members and add back to statements statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), true), [ ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier) ], false); @@ -54016,7 +54813,7 @@ var ts; } else { // some items filtered, others not - update the export declaration - statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); + statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.assertClause); } } return statements; @@ -54081,12 +54878,11 @@ var ts; if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) { var oldContext = context; context = cloneNodeBuilderContext(context); - var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); + serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); if (context.reportedDiagnostic) { oldcontext.reportedDiagnostic = context.reportedDiagnostic; // hoist diagnostic result into outer context } context = oldContext; - return result; } } // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias @@ -54167,7 +54963,6 @@ var ts; && ((_d = type.symbol) === null || _d === void 0 ? void 0 : _d.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, alias, localName)])), 0 /* ModifierFlags.None */); context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* SymbolFlags.Value */); @@ -54200,7 +54995,6 @@ var ts; // ``` // To create an export named `g` that does _not_ shadow the local `g` addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name, localName)])), 0 /* ModifierFlags.None */); needsExportDeclaration = false; @@ -54249,16 +55043,15 @@ var ts; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); if (!resolvedModule) continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* ModifierFlags.None */); } } } if (needsPostExportDefault) { - addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); + addResult(ts.factory.createExportAssignment(/*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* ModifierFlags.None */); } else if (needsExportDeclaration) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* ModifierFlags.None */); } @@ -54326,7 +55119,7 @@ var ts; && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); - addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); + addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* SyntaxKind.MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; context.enclosingDeclaration = oldEnclosingDecl; } @@ -54342,7 +55135,6 @@ var ts; var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* SymbolFlags.Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), constructSignatures, true), callSignatures, true), members, true)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { @@ -54368,7 +55160,6 @@ var ts; var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* InternalSymbolName.ExportEquals */; }), function (s) { var _a, _b; @@ -54385,13 +55176,11 @@ var ts; return ts.factory.createExportSpecifier(/*isTypeOnly*/ false, name === targetName ? undefined : targetName, name); })))]); addResult(ts.factory.createModuleDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* NodeFlags.Namespace */), 0 /* ModifierFlags.None */); } } function serializeEnum(symbol, symbolName, modifierFlags) { - addResult(ts.factory.createEnumDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { + addResult(ts.factory.createEnumDeclaration(ts.factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 2048 /* ModifierFlags.Const */ : 0), getInternalSymbolName(symbol, symbolName), ts.map(ts.filter(getPropertiesOfType(getTypeOfSymbol(symbol)), function (p) { return !!(p.flags & 8 /* SymbolFlags.EnumMember */); }), function (p) { // TODO: Handle computed names // I hate that to get the initialized value we need to walk back to the declarations here; but there's no // other way to get the possible const value of an enum member that I'm aware of, as the value is cached @@ -54452,7 +55241,7 @@ var ts; // emit akin to the above would be needed. // Add a namespace // Create namespace as non-synthetic so it is usable as an enclosing declaration - var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace, enclosingDeclaration); fakespace.locals = ts.createSymbolTable(props); fakespace.symbol = props[0].parent; @@ -54471,11 +55260,10 @@ var ts; results = oldResults; // replace namespace with synthetic version var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, d.expression, ts.factory.createIdentifier("default" /* InternalSymbolName.Default */))])) : d; }); var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* ModifierFlags.Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced; - fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); + fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped)); addResult(fakespace, modifierFlags); // namespaces can never be default exported } } @@ -54531,7 +55319,7 @@ var ts; ? getBaseConstructorTypeOfClass(staticType) : anyType; var heritageClauses = __spreadArray(__spreadArray([], !ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(94 /* SyntaxKind.ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], true), !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(117 /* SyntaxKind.ImplementsKeyword */, implementsExpressions)], true); - var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); + var symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties @@ -54549,7 +55337,6 @@ var ts; // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? [ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -54566,12 +55353,11 @@ var ts; ts.isInJSFile(symbol.valueDeclaration) && !ts.some(getSignaturesOfType(staticType, 1 /* SignatureKind.Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? - [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : + [ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(8 /* ModifierFlags.Private */), [], /*body*/ undefined)] : serializeSignatures(1 /* SignatureKind.Construct */, staticType, staticBaseType, 171 /* SyntaxKind.Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures, true), staticMembers, true), constructors, true), publicProperties, true), privateProperties, true)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags); } function getSomeTargetNameFromDeclarations(declarations) { @@ -54623,7 +55409,6 @@ var ts; var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier( /*isTypeOnly*/ false, propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1), /*importClause*/ undefined), 0 /* ModifierFlags.None */); @@ -54647,12 +55432,10 @@ var ts; var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); // 'y' // import _x = require('y'); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* ModifierFlags.None */); // import x = _x.z addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); break; @@ -54669,7 +55452,6 @@ var ts; // an external `import localName = require("whatever")` var isLocalImport = !(target.flags & 512 /* SymbolFlags.ValueModule */) && !ts.isVariableDeclaration(node); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), isLocalImport ? symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false) @@ -54683,7 +55465,6 @@ var ts; break; case 267 /* SyntaxKind.ImportClause */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag @@ -54693,19 +55474,16 @@ var ts; break; case 268 /* SyntaxKind.NamespaceImport */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), /*assertClause*/ undefined), 0 /* ModifierFlags.None */); break; case 274 /* SyntaxKind.NamespaceExport */: addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* ModifierFlags.None */); break; case 270 /* SyntaxKind.ImportSpecifier */: addResult(ts.factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( /*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamedImports([ @@ -54744,7 +55522,6 @@ var ts; } function serializeExportSpecifier(localName, targetName, specifier) { addResult(ts.factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(/*isTypeOnly*/ false, localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* ModifierFlags.None */); } @@ -54785,7 +55562,6 @@ var ts; context.tracker.trackSymbol = function () { return false; }; if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* SymbolFlags.All */))); } else { @@ -54800,7 +55576,6 @@ var ts; // serialize as `import _Ref = t.arg.et; export { _Ref as name }` var varName = getUnusedName(name, symbol); addResult(ts.factory.createImportEqualsDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* SymbolFlags.All */, /*expectsIdentifier*/ false)), 0 /* ModifierFlags.None */); serializeExportSpecifier(name, varName); @@ -54831,7 +55606,6 @@ var ts; } if (isExportAssignmentCompatibleSymbolName) { results.push(ts.factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName))); return true; } @@ -54881,9 +55655,7 @@ var ts; if (p.flags & 98304 /* SymbolFlags.Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SymbolFlags.SetAccessor */) { - result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( - /*decorators*/ undefined, + result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], @@ -54891,8 +55663,7 @@ var ts; } if (p.flags & 32768 /* SymbolFlags.GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* ModifierFlags.Private */; - result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; @@ -54900,8 +55671,7 @@ var ts; // This is an else/if as accessors and properties can't merge in TS, but might in JS // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* SymbolFlags.Property */ | 3 /* SymbolFlags.Variable */ | 98304 /* SymbolFlags.Accessor */)) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); @@ -54910,8 +55680,7 @@ var ts; var type = getTypeOfSymbol(p); var signatures = getSignaturesOfType(type, 0 /* SignatureKind.Call */); if (flag & 8 /* ModifierFlags.Private */) { - return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, + return ts.setTextRange(createProperty(ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* ModifierFlags.Readonly */ : 0) | flag), name, p.flags & 16777216 /* SymbolFlags.Optional */ ? ts.factory.createToken(57 /* SyntaxKind.QuestionToken */) : undefined, /*type*/ undefined, /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } @@ -54969,8 +55738,7 @@ var ts; } } if (privateProtected) { - return [ts.setTextRange(ts.factory.createConstructorDeclaration( - /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), + return [ts.setTextRange(ts.factory.createConstructorDeclaration(ts.factory.createModifiersFromModifierFlags(privateProtected), /*parameters*/ [], /*body*/ undefined), signatures[0].declaration)]; } @@ -55669,7 +56437,7 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 32768 /* TypeFlags.Undefined */) ? getNonUndefinedType(type) : type; + return strictNullChecks && !(getTypeFacts(checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)) & 16777216 /* TypeFacts.IsUndefined */) ? getNonUndefinedType(type) : type; } return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* CheckMode.Normal */)], 2 /* UnionReduction.Subtype */)); } @@ -56070,7 +56838,7 @@ var ts; (resolvedSymbol || symbol).exports.forEach(function (s, name) { var _a; var exportedMember = members_4.get(name); - if (exportedMember && exportedMember !== s) { + if (exportedMember && exportedMember !== s && !(s.flags & 2097152 /* SymbolFlags.Alias */)) { if (s.flags & 111551 /* SymbolFlags.Value */ && exportedMember.flags & 111551 /* SymbolFlags.Value */) { // If the member has an additional value-like declaration, union the types from the two declarations, // but issue an error if they occurred in two different files. The purpose is to support a JS file with @@ -56104,6 +56872,17 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.indexInfos); + if (initialSize === members_4.size) { + if (type.aliasSymbol) { + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = type.aliasTypeArguments; + } + if (ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */) { + result.aliasSymbol = type.symbol; + var args = getTypeArguments(type); + result.aliasTypeArguments = ts.length(args) ? args : undefined; + } + } result.objectFlags |= (ts.getObjectFlags(type) & 4096 /* ObjectFlags.JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* SymbolFlags.Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { result.objectFlags |= 16777216 /* ObjectFlags.IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type @@ -56155,11 +56934,7 @@ var ts; if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAny(element, anyType); } - // When we're including the pattern in the type (an indication we're obtaining a contextual type), we - // use the non-inferrable any type. Inference will never directly infer this type, but it is possible - // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases, - // widening of the binding pattern type substitutes a regular any for the non-inferrable any. - return includePatternInType ? nonInferrableAnyType : anyType; + return anyType; } // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { @@ -57160,7 +57935,7 @@ var ts; error(declaration.typeExpression.type, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } else { - error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + error(ts.isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } } links.declaredType = type; @@ -58464,6 +59239,9 @@ var ts; else if (type.objectFlags & 32 /* ObjectFlags.Mapped */) { resolveMappedTypeMembers(type); } + else { + ts.Debug.fail("Unhandled object type " + ts.Debug.formatObjectFlags(type.objectFlags)); + } } else if (type.flags & 1048576 /* TypeFlags.Union */) { resolveUnionTypeMembers(type); @@ -58471,6 +59249,9 @@ var ts; else if (type.flags & 2097152 /* TypeFlags.Intersection */) { resolveIntersectionTypeMembers(type); } + else { + ts.Debug.fail("Unhandled type " + ts.Debug.formatTypeFlags(type.flags)); + } } return type; } @@ -58658,7 +59439,7 @@ var ts; } } } - else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + else if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { hasDisjointDomainType = true; } } @@ -58670,12 +59451,13 @@ var ts; // intersection operation to reduce the union constraints. for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { var t = types_6[_a]; - if (t.flags & 469892092 /* TypeFlags.DisjointDomains */) { + if (t.flags & 469892092 /* TypeFlags.DisjointDomains */ || isEmptyAnonymousObjectType(t)) { constraints = ts.append(constraints, t); } } } - return getIntersectionType(constraints); + // The source types were normalized; ensure the result is normalized too. + return getNormalizedType(getIntersectionType(constraints), /*writing*/ false); } return undefined; } @@ -58786,7 +59568,7 @@ var ts; } if (t.flags & 268435456 /* TypeFlags.StringMapping */) { var constraint = getBaseConstraint(t.type); - return constraint ? getStringMappingType(t.symbol, constraint) : stringType; + return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType; } if (t.flags & 8388608 /* TypeFlags.IndexedAccess */) { if (isMappedTypeGenericIndexedAccess(t)) { @@ -58872,7 +59654,7 @@ var ts; var objectType; return !!(type.flags & 8388608 /* TypeFlags.IndexedAccess */ && ts.getObjectFlags(objectType = type.objectType) & 32 /* ObjectFlags.Mapped */ && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && - !objectType.declaration.questionToken && !objectType.declaration.nameType); + !(getMappedTypeModifiers(objectType) & 8 /* MappedTypeModifiers.ExcludeOptional */) && !objectType.declaration.nameType); } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, @@ -59151,12 +59933,12 @@ var ts; * @param type a type to look up property from * @param name a name of property to look up in a given type */ - function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment) { + function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) { type = getReducedApparentType(type); if (type.flags & 524288 /* TypeFlags.Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { + if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) { return symbol; } if (skipObjectFunctionPropertyAugment) @@ -59262,12 +60044,15 @@ var ts; // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(declaration) { + var _a; var result; - for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { - var node = _a[_i]; + for (var _i = 0, _b = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _b.length; _i++) { + var node = _b[_i]; result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); } - return result; + return (result === null || result === void 0 ? void 0 : result.length) ? result + : ts.isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) === null || _a === void 0 ? void 0 : _a.typeParameters + : undefined; } function symbolsToArray(symbols) { var result = []; @@ -59818,8 +60603,7 @@ var ts; var _a; var inferences; if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { - for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { - var declaration = _b[_i]; + var _loop_15 = function (declaration) { if (declaration.parent.kind === 190 /* SyntaxKind.InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the @@ -59827,12 +60611,12 @@ var ts; // present, we form an intersection of the inferred constraint types. var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; if (grandParent.kind === 178 /* SyntaxKind.TypeReference */ && !omitTypeReferences) { - var typeReference = grandParent; - var typeParameters = getTypeParametersForTypeReference(typeReference); - if (typeParameters) { - var index = typeReference.typeArguments.indexOf(childTypeParameter); - if (index < typeParameters.length) { - var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + var typeReference_1 = grandParent; + var typeParameters_1 = getTypeParametersForTypeReference(typeReference_1); + if (typeParameters_1) { + var index = typeReference_1.typeArguments.indexOf(childTypeParameter); + if (index < typeParameters_1.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters_1[index]); if (declaredConstraint) { // Type parameter constraints can reference other type parameters so // constraints need to be instantiated. If instantiation produces the @@ -59840,7 +60624,9 @@ var ts; // type Foo = [T, U]; // type Bar = T extends Foo ? Foo : T; // the instantiated constraint for U is X, so we discard that inference. - var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var mapper = makeDeferredTypeMapper(typeParameters_1, typeParameters_1.map(function (_, index) { return function () { + return getEffectiveTypeArgumentAtIndex(typeReference_1, typeParameters_1, index); + }; })); var constraint = instantiateType(declaredConstraint, mapper); if (constraint !== typeParameter) { inferences = ts.append(inferences, constraint); @@ -59878,6 +60664,10 @@ var ts; inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); } } + }; + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + _loop_15(declaration); } } return inferences && getIntersectionType(inferences); @@ -59940,13 +60730,13 @@ var ts; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type - // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // of an object literal or a non-inferrable type. This is because there are operations in the type checker // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type = types_8[_i]; - if (!(type.flags & excludeKinds)) { + if (excludeKinds === undefined || !(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } } @@ -59958,7 +60748,7 @@ var ts; if (!type) { type = createObjectType(4 /* ObjectFlags.Reference */, target.symbol); target.instantiations.set(id, type); - type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0; type.target = target; type.resolvedTypeArguments = typeArguments; } @@ -60766,7 +61556,7 @@ var ts; var lastRequiredIndex = -1; var firstRestIndex = -1; var lastOptionalOrRestIndex = -1; - var _loop_15 = function (i) { + var _loop_16 = function (i) { var type = elementTypes[i]; var flags = target.elementFlags[i]; if (flags & 8 /* ElementFlags.Variadic */) { @@ -60796,7 +61586,7 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - var state_4 = _loop_15(i); + var state_4 = _loop_16(i); if (typeof state_4 === "object") return state_4.value; } @@ -60992,7 +61782,7 @@ var ts; var templates = ts.filter(types, isPatternLiteralType); if (templates.length) { var i = types.length; - var _loop_16 = function () { + var _loop_17 = function () { i--; var t = types[i]; if (t.flags & 128 /* TypeFlags.StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { @@ -61000,7 +61790,7 @@ var ts; } }; while (i > 0) { - _loop_16(); + _loop_17(); } } } @@ -61077,14 +61867,14 @@ var ts; var namedUnions = []; addNamedUnions(namedUnions, types); var reducedTypes = []; - var _loop_17 = function (t) { + var _loop_18 = function (t) { if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) { reducedTypes.push(t); } }; for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) { var t = typeSet_1[_i]; - _loop_17(t); + _loop_18(t); } if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) { return namedUnions[0]; @@ -61219,7 +62009,7 @@ var ts; } return includes; } - function removeRedundantPrimitiveTypes(types, includes) { + function removeRedundantSupertypes(types, includes) { var i = types.length; while (i > 0) { i--; @@ -61227,7 +62017,9 @@ var ts; var remove = t.flags & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || t.flags & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || t.flags & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */; + t.flags & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + t.flags & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + isEmptyAnonymousObjectType(t) && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */; if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -61349,7 +62141,7 @@ var ts; // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types, aliasSymbol, aliasTypeArguments, noSupertypeReduction) { var typeMembershipMap = new ts.Map(); var includes = addTypesToIntersection(typeMembershipMap, 0, types); var typeSet = ts.arrayFrom(typeMembershipMap.values()); @@ -61386,11 +62178,11 @@ var ts; if (includes & 4 /* TypeFlags.String */ && includes & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */ | 268435456 /* TypeFlags.StringMapping */) || includes & 8 /* TypeFlags.Number */ && includes & 256 /* TypeFlags.NumberLiteral */ || includes & 64 /* TypeFlags.BigInt */ && includes & 2048 /* TypeFlags.BigIntLiteral */ || - includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */) { - removeRedundantPrimitiveTypes(typeSet, includes); - } - if (includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 524288 /* TypeFlags.Object */) { - ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); + includes & 4096 /* TypeFlags.ESSymbol */ && includes & 8192 /* TypeFlags.UniqueESSymbol */ || + includes & 16384 /* TypeFlags.Void */ && includes & 32768 /* TypeFlags.Undefined */ || + includes & 16777216 /* TypeFlags.IncludesEmptyObject */ && includes & 470302716 /* TypeFlags.DefinitelyNonNullable */) { + if (!noSupertypeReduction) + removeRedundantSupertypes(typeSet, includes); } if (includes & 262144 /* TypeFlags.IncludesMissingType */) { typeSet[typeSet.indexOf(undefinedType)] = missingType; @@ -61429,8 +62221,9 @@ var ts; } var constituents = getCrossProductIntersections(typeSet); // We attach a denormalized origin type when at least one constituent of the cross-product union is an - // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions). - var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; + // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions) and + // the denormalized origin has fewer constituents than the union itself. + var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* TypeFlags.Intersection */); }) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* TypeFlags.Intersection */, typeSet) : undefined; result = getUnionType(constituents, 1 /* UnionReduction.Literal */, aliasSymbol, aliasTypeArguments, origin); } } @@ -61473,11 +62266,21 @@ var ts; } return intersections; } + function getConstituentCount(type) { + return !(type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) || type.aliasSymbol ? 1 : + type.flags & 1048576 /* TypeFlags.Union */ && type.origin ? getConstituentCount(type.origin) : + getConstituentCountOfTypes(type.types); + } + function getConstituentCountOfTypes(types) { + return ts.reduceLeft(types, function (n, t) { return n + getConstituentCount(t); }, 0); + } function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var aliasSymbol = getAliasSymbolForTypeNode(node); - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + var types = ts.map(node.types, getTypeFromTypeNode); + var noSupertypeReduction = types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType; + links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); } return links.resolvedType; } @@ -61605,19 +62408,22 @@ var ts; * to reduce the resulting type if possible (since only intersections with conflicting literal-typed properties are reducible). */ function isPossiblyReducibleByInstantiation(type) { - return ts.some(type.types, function (t) { - var uniqueFilled = getUniqueLiteralFilledInstantiation(t); - return getReducedType(uniqueFilled) !== uniqueFilled; - }); + var uniqueFilled = getUniqueLiteralFilledInstantiation(type); + return getReducedType(uniqueFilled) !== uniqueFilled; + } + function shouldDeferIndexType(type) { + return !!(type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || + isGenericTupleType(type) || + isGenericMappedType(type) && !hasDistributiveNameType(type) || + type.flags & 1048576 /* TypeFlags.Union */ && ts.some(type.types, isPossiblyReducibleByInstantiation) || + type.flags & 2097152 /* TypeFlags.Intersection */ && maybeTypeOfKind(type, 465829888 /* TypeFlags.Instantiable */) && ts.some(type.types, isEmptyAnonymousObjectType)); } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } type = getReducedType(type); - return type.flags & 1048576 /* TypeFlags.Union */ ? isPossiblyReducibleByInstantiation(type) - ? getIndexTypeForGenericType(type, stringsOnly) - : getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : - type.flags & 58982400 /* TypeFlags.InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + return shouldDeferIndexType(type) ? getIndexTypeForGenericType(type, stringsOnly) : + type.flags & 1048576 /* TypeFlags.Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : + type.flags & 2097152 /* TypeFlags.Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ ? getIndexTypeForMappedType(type, stringsOnly, noIndexSignatures) : type === wildcardType ? wildcardType : type.flags & 2 /* TypeFlags.Unknown */ ? neverType : @@ -61743,9 +62549,12 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type; + // 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; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -61756,6 +62565,15 @@ var ts; } return str; } + function applyTemplateStringMapping(symbol, texts, types) { + switch (intrinsicTypeKinds.get(symbol.escapedName)) { + case 0 /* IntrinsicTypeKind.Uppercase */: return [texts.map(function (t) { return t.toUpperCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 1 /* IntrinsicTypeKind.Lowercase */: return [texts.map(function (t) { return t.toLowerCase(); }), types.map(function (t) { return getStringMappingType(symbol, t); })]; + case 2 /* IntrinsicTypeKind.Capitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toUpperCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + case 3 /* IntrinsicTypeKind.Uncapitalize */: return [texts[0] === "" ? texts : __spreadArray([texts[0].charAt(0).toLowerCase() + texts[0].slice(1)], texts.slice(1), true), texts[0] === "" ? __spreadArray([getStringMappingType(symbol, types[0])], types.slice(1), true) : types]; + } + return [texts, types]; + } function getStringMappingTypeForGenericType(symbol, type) { var id = "".concat(getSymbolId(symbol), ",").concat(getTypeId(type)); var result = stringMappingTypes.get(id); @@ -61857,21 +62675,28 @@ var ts; getFlowTypeOfReference(accessExpression, propType) : propType; } - if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName) && +propName >= 0) { + if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName)) { + var index = +propName; if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 16 /* AccessFlags.NoTupleBoundsCheck */)) { var indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { + if (index < 0) { + error(indexNode, ts.Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); + return undefinedType; + } error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); } else { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } } - errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); - return mapType(objectType, function (t) { - var restType = getRestTypeOfTupleType(t) || undefinedType; - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; - }); + if (index >= 0) { + errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, numberType)); + return mapType(objectType, function (t) { + var restType = getRestTypeOfTupleType(t) || undefinedType; + return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([restType, undefinedType]) : restType; + }); + } } } if (!(indexType.flags & 98304 /* TypeFlags.Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* TypeFlags.StringLike */ | 296 /* TypeFlags.NumberLike */ | 12288 /* TypeFlags.ESSymbolLike */)) { @@ -61997,7 +62822,7 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -62135,7 +62960,7 @@ var ts; function substituteIndexedMappedType(objectType, index) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]); var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return instantiateType(getTemplateTypeFromMappedType(objectType.target || objectType), templateMapper); } function getIndexedAccessType(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) { if (accessFlags === void 0) { accessFlags = 0 /* AccessFlags.None */; } @@ -62283,7 +63108,7 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_18 = function () { + var _loop_19 = function () { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; @@ -62404,7 +63229,7 @@ var ts; // 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_5 = _loop_18(); + var state_5 = _loop_19(); if (typeof state_5 === "object") return state_5.value; if (state_5 === "break") @@ -62505,6 +63330,7 @@ var ts; } } function getTypeFromImportTypeNode(node) { + var _a; var links = getNodeLinks(node); if (!links.resolvedType) { if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments @@ -62524,6 +63350,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } + var isExportEquals = !!((_a = innerModuleSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* InternalSymbolName.ExportEquals */)); var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); @@ -62535,9 +63362,11 @@ var ts; // That, in turn, ultimately uses `getPropertyOfType` on the type of the symbol, which differs slightly from // the `exports` lookup process that only looks up namespace members which is used for most type references var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace)); - var next = node.isTypeOf - ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText) - : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var symbolFromVariable = node.isTypeOf || ts.isInJSFile(node) && isExportEquals + ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ true) + : undefined; + var symbolFromModule = node.isTypeOf ? undefined : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); + var next = symbolFromModule !== null && symbolFromModule !== void 0 ? symbolFromModule : symbolFromVariable; if (!next) { error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); return links.resolvedType = errorType; @@ -63034,7 +63863,7 @@ var ts; switch (mapper.kind) { case 0 /* TypeMapKind.Simple */: return type === mapper.source ? mapper.target : type; - case 1 /* TypeMapKind.Array */: + case 1 /* TypeMapKind.Array */: { var sources = mapper.sources; var targets = mapper.targets; for (var i = 0; i < sources.length; i++) { @@ -63043,25 +63872,39 @@ var ts; } } return type; - case 2 /* TypeMapKind.Function */: + } + case 2 /* TypeMapKind.Deferred */: { + var sources = mapper.sources; + var targets = mapper.targets; + for (var i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets[i](); + } + } + return type; + } + case 3 /* TypeMapKind.Function */: return mapper.func(type); - case 3 /* TypeMapKind.Composite */: - case 4 /* TypeMapKind.Merged */: + case 4 /* TypeMapKind.Composite */: + case 5 /* TypeMapKind.Merged */: var t1 = getMappedType(type, mapper.mapper1); - return t1 !== type && mapper.kind === 3 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); + return t1 !== type && mapper.kind === 4 /* TypeMapKind.Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); } } function makeUnaryTypeMapper(source, target) { - return { kind: 0 /* TypeMapKind.Simple */, source: source, target: target }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 0 /* TypeMapKind.Simple */, source: source, target: target }); } function makeArrayTypeMapper(sources, targets) { - return { kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 1 /* TypeMapKind.Array */, sources: sources, targets: targets }); } - function makeFunctionTypeMapper(func) { - return { kind: 2 /* TypeMapKind.Function */, func: func }; + function makeFunctionTypeMapper(func, debugInfo) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 3 /* TypeMapKind.Function */, func: func, debugInfo: ts.Debug.isDebugging ? debugInfo : undefined }); + } + function makeDeferredTypeMapper(sources, targets) { + return ts.Debug.attachDebugPrototypeIfDebug({ kind: 2 /* TypeMapKind.Deferred */, sources: sources, targets: targets }); } function makeCompositeTypeMapper(kind, mapper1, mapper2) { - return { kind: kind, mapper1: mapper1, mapper2: mapper2 }; + return ts.Debug.attachDebugPrototypeIfDebug({ kind: kind, mapper1: mapper1, mapper2: mapper2 }); } function createTypeEraser(sources) { return createTypeMapper(sources, /*targets*/ undefined); @@ -63071,19 +63914,20 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(context, index) { - return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; }); + var forwardInferences = context.inferences.slice(index); + return createTypeMapper(ts.map(forwardInferences, function (i) { return i.typeParameter; }), ts.map(forwardInferences, function () { return unknownType; })); } function combineTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(3 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Composite */, mapper1, mapper2) : mapper2; } function mergeTypeMappers(mapper1, mapper2) { - return mapper1 ? makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; + return mapper1 ? makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper1, mapper2) : mapper2; } function prependTypeMapping(source, target, mapper) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, makeUnaryTypeMapper(source, target), mapper); } function appendTypeMapping(mapper, source, target) { - return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(5 /* TypeMapKind.Merged */, mapper, makeUnaryTypeMapper(source, target)); } function getRestrictiveTypeParameter(tp) { return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), @@ -63349,6 +64193,7 @@ var ts; result.mapper = mapper; result.aliasSymbol = aliasSymbol || type.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + result.objectFlags |= result.aliasTypeArguments ? getPropagatingFlagsOfTypes(result.aliasTypeArguments) : 0; return result; } function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { @@ -63997,7 +64842,7 @@ var ts; }); } function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; if (isTupleLikeType(source)) { return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); @@ -64064,7 +64909,7 @@ var ts; }); } function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & 131068 /* TypeFlags.Primitive */) + if (target.flags & (131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); } @@ -64151,7 +64996,7 @@ var ts; var sourceSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = checkMode & 3 /* SignatureCheckMode.Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && - (getFalsyFlags(sourceType) & 98304 /* TypeFlags.Nullable */) === (getFalsyFlags(targetType) & 98304 /* TypeFlags.Nullable */); + (getTypeFacts(sourceType) & 50331648 /* TypeFacts.IsUndefinedOrNull */) === (getTypeFacts(targetType) & 50331648 /* TypeFacts.IsUndefinedOrNull */); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* SignatureCheckMode.StrictArity */) | (strictVariance ? 2 /* SignatureCheckMode.StrictCallback */ : 1 /* SignatureCheckMode.BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* SignatureCheckMode.Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); @@ -64263,6 +65108,20 @@ var ts; return !!(ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && (type.members && isEmptyResolvedType(type) || type.symbol && type.symbol.flags & 2048 /* SymbolFlags.TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0)); } + function isUnknownLikeUnionType(type) { + if (strictNullChecks && type.flags & 1048576 /* TypeFlags.Union */) { + if (!(type.objectFlags & 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */)) { + var types = type.types; + type.objectFlags |= 33554432 /* ObjectFlags.IsUnknownLikeUnionComputed */ | (types.length >= 3 && types[0].flags & 32768 /* TypeFlags.Undefined */ && + types[1].flags & 65536 /* TypeFlags.Null */ && ts.some(types, isEmptyAnonymousObjectType) ? 67108864 /* ObjectFlags.IsUnknownLikeUnion */ : 0); + } + return !!(type.objectFlags & 67108864 /* ObjectFlags.IsUnknownLikeUnion */); + } + return false; + } + function containsUndefinedType(type) { + return !!((type.flags & 1048576 /* TypeFlags.Union */ ? type.types[0] : type).flags & 32768 /* TypeFlags.Undefined */); + } function isStringIndexSignatureOnlyType(type) { return type.flags & 524288 /* TypeFlags.Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) || @@ -64342,7 +65201,7 @@ var ts; return true; if (s & 65536 /* TypeFlags.Null */ && (!strictNullChecks && !(t & 3145728 /* TypeFlags.UnionOrIntersection */) || t & 65536 /* TypeFlags.Null */)) return true; - if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */) + if (s & 524288 /* TypeFlags.Object */ && t & 67108864 /* TypeFlags.NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(ts.getObjectFlags(source) & 8192 /* ObjectFlags.FreshLiteral */))) return true; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* TypeFlags.Any */) @@ -64352,6 +65211,9 @@ var ts; // bit-flag enum types sometimes look like literal enum types with numeric literal values. if (s & (8 /* TypeFlags.Number */ | 256 /* TypeFlags.NumberLiteral */) && !(s & 1024 /* TypeFlags.EnumLiteral */) && (t & 32 /* TypeFlags.Enum */ || relation === assignableRelation && t & 256 /* TypeFlags.NumberLiteral */ && t & 1024 /* TypeFlags.EnumLiteral */)) return true; + // Anything is assignable to a union containing undefined, null, and {} + if (isUnknownLikeUnionType(target)) + return true; } return false; } @@ -64394,16 +65256,27 @@ var ts; function getNormalizedType(type, writing) { while (true) { var t = isFreshLiteralType(type) ? type.regularType : - ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getReducedType(type) : + ts.getObjectFlags(type) & 4 /* ObjectFlags.Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : + type.flags & 3145728 /* TypeFlags.UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* TypeFlags.Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* TypeFlags.Simplifiable */ ? getSimplifiedType(type, writing) : type; - t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) - break; + return t; type = t; } + } + function getNormalizedUnionOrIntersectionType(type, writing) { + var reduced = getReducedType(type); + if (reduced !== type) { + return reduced; + } + if (type.flags & 2097152 /* TypeFlags.Intersection */) { + var normalizedTypes = ts.sameMap(type.types, function (t) { return getNormalizedType(t, writing); }); + if (normalizedTypes !== type.types) { + return getIntersectionType(normalizedTypes); + } + } return type; } /** @@ -64635,7 +65508,7 @@ var ts; ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable"); generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); } - if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperType && target !== markerSubType) { + if (target.flags & 262144 /* TypeFlags.TypeParameter */ && target !== markerSuperTypeForCheck && target !== markerSubTypeForCheck) { var constraint = getBaseConstraintOfType(target); var needsOriginalSource = void 0; if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) { @@ -64850,6 +65723,7 @@ var ts; return 0 /* Ternary.False */; } function reportErrorResults(originalSource, originalTarget, source, target, headMessage) { + var _a, _b; var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; @@ -64890,6 +65764,14 @@ var ts; return; } reportRelationError(headMessage, source, target); + if (source.flags & 262144 /* TypeFlags.TypeParameter */ && ((_b = (_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) === null || _b === void 0 ? void 0 : _b[0]) && !getConstraintOfType(source)) { + var syntheticParam = cloneTypeParameter(source); + syntheticParam.constraint = instantiateType(target, makeUnaryTypeMapper(source, syntheticParam)); + if (hasNonCircularBaseConstraint(syntheticParam)) { + var targetConstraintString = typeToString(target, source.symbol.declarations[0]); + associateRelatedInfo(ts.createDiagnosticForNode(source.symbol.declarations[0], ts.Diagnostics.This_type_parameter_might_need_an_extends_0_constraint, targetConstraintString)); + } + } } function traceUnionsOrIntersectionsTooLarge(source, target) { if (!ts.tracing) { @@ -64942,7 +65824,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_19 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -65005,7 +65887,7 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_6 = _loop_19(prop); + var state_6 = _loop_20(prop); if (typeof state_6 === "object") return state_6.value; } @@ -65027,7 +65909,7 @@ var ts; return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* TypeFlags.Primitive */) && !(target.flags & 131068 /* TypeFlags.Primitive */)); } if (target.flags & 2097152 /* TypeFlags.Intersection */) { - return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* IntersectionState.Target */); + return typeRelatedToEachType(source, target, reportErrors, 2 /* IntersectionState.Target */); } // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the // constraints of all non-primitive types in the source into a new intersection. We do this because the @@ -65237,10 +66119,10 @@ var ts; // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component var saved = entry & 24 /* RelationComparisonResult.ReportsMask */; if (saved & 8 /* RelationComparisonResult.ReportsUnmeasurable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers)); + instantiateType(source, reportUnmeasurableMapper); } if (saved & 16 /* RelationComparisonResult.ReportsUnreliable */) { - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } } return entry & 1 /* RelationComparisonResult.Succeeded */ ? -1 /* Ternary.True */ : 0 /* Ternary.False */; @@ -65340,13 +66222,40 @@ var ts; return result; } 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 */)) { + // 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 + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + // This also handles type parameters, as a type parameter with a union constraint compared against a union + // 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 && 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) { + resetErrorInfo(saveErrorInfo); + } + 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; - var saveErrorInfo = captureErrorCalculationState(); var sourceFlags = source.flags; var targetFlags = target.flags; if (relation === identityRelation) { @@ -65392,29 +66301,6 @@ var ts; if (result = unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState)) { return result; } - if (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */) { - // 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 - // when the target is a union type. Another is when the intersection contains types belonging - // to one of the disjoint domains. For example, given type variables T and U, each with the - // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and - // we need to check this constraint against a union on the target side. Also, given a type - // variable V constrained to 'string | number', 'V & number' has a combined constraint of - // 'string & number | number & number' which reduces to just 'number'. - // This also handles type parameters, as a type parameter with a union constraint compared against a union - // 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 && 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 - if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - } // The ordered decomposition above doesn't handle all cases. Specifically, we also need to handle: // Source is instantiable (e.g. source has union or intersection constraint). // Source is an object, target is a union (e.g. { a, b: boolean } <=> { a, b: true } | { a, b: false }). @@ -65458,6 +66344,20 @@ var ts; } } } + if (relation === comparableRelation && sourceFlags & 262144 /* TypeFlags.TypeParameter */) { + // This is a carve-out in comparability to essentially forbid comparing a type parameter + // 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 */) { + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { + return result; + } + constraint = getConstraintOfTypeParameter(constraint); + } + } + return 0 /* Ternary.False */; + } } else if (targetFlags & 4194304 /* TypeFlags.Index */) { var targetType_1 = target.type; @@ -65521,7 +66421,6 @@ var ts; result &= isRelatedTo(source.indexType, target.indexType, 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } if (reportErrors) { @@ -65624,7 +66523,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } var c = target; @@ -65639,7 +66537,6 @@ var ts; if (result = skipTrue ? -1 /* Ternary.True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false)) { result &= skipFalse ? -1 /* Ternary.True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* RecursionFlags.Target */, /*reportErrors*/ false); if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65652,31 +66549,29 @@ var ts; } // Report unreliable variance for type variables referenced in template literal type placeholders. // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. - instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + instantiateType(source, reportUnreliableMapper); } if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* Ternary.True */; } } + else if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + if (!(source.flags & 268435456 /* TypeFlags.StringMapping */)) { + if (isMemberOfStringMapping(source, target)) { + return -1 /* Ternary.True */; + } + } + } if (sourceFlags & 8650752 /* TypeFlags.TypeVariable */) { // IndexedAccess comparisons are handled above in the `targetFlags & TypeFlage.IndexedAccess` branch if (!(sourceFlags & 8388608 /* TypeFlags.IndexedAccess */ && targetFlags & 8388608 /* TypeFlags.IndexedAccess */)) { - var constraint = getConstraintOfType(source); - if (!constraint || (sourceFlags & 262144 /* TypeFlags.TypeParameter */ && constraint.flags & 1 /* TypeFlags.Any */)) { - // A type variable with no constraint is not related to the non-primitive object type. - if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* TypeFlags.NonPrimitive */), 3 /* RecursionFlags.Both */)) { - resetErrorInfo(saveErrorInfo); - return result; - } - } + var constraint = getConstraintOfType(source) || unknownType; // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed - else if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* RecursionFlags.Source */, reportErrors && constraint !== unknownType && !(targetFlags & sourceFlags & 262144 /* TypeFlags.TypeParameter */), /*headMessage*/ undefined, intersectionState)) { return result; } if (isMappedTypeGenericIndexedAccess(source)) { @@ -65685,7 +66580,6 @@ var ts; var indexConstraint = getConstraintOfType(source.indexType); if (indexConstraint) { if (result = isRelatedTo(getIndexedAccessType(source.objectType, indexConstraint), target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65694,7 +66588,6 @@ var ts; } else if (sourceFlags & 4194304 /* TypeFlags.Index */) { if (result = isRelatedTo(keyofConstraintType, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65702,22 +66595,22 @@ var ts; if (!(targetFlags & 134217728 /* TypeFlags.TemplateLiteral */)) { var constraint = getBaseConstraintOfType(source); if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } } else if (sourceFlags & 268435456 /* TypeFlags.StringMapping */) { - if (targetFlags & 268435456 /* TypeFlags.StringMapping */ && source.symbol === target.symbol) { + if (targetFlags & 268435456 /* TypeFlags.StringMapping */) { + if (source.symbol !== target.symbol) { + return 0 /* Ternary.False */; + } if (result = isRelatedTo(source.type, target.type, 3 /* RecursionFlags.Both */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } else { var constraint = getBaseConstraintOfType(source); if (constraint && (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, reportErrors))) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65726,7 +66619,6 @@ var ts; // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { - resetErrorInfo(saveErrorInfo); return 3 /* Ternary.Maybe */; } if (targetFlags & 16777216 /* TypeFlags.Conditional */) { @@ -65749,7 +66641,6 @@ var ts; result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* RecursionFlags.Both */, reportErrors); } if (result) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65760,7 +66651,6 @@ var ts; var distributiveConstraint = hasNonCircularBaseConstraint(source) ? getConstraintOfDistributiveConditionalType(source) : undefined; if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65770,7 +66660,6 @@ var ts; var defaultConstraint = getDefaultConstraintOfConditionalType(source); if (defaultConstraint) { if (result = isRelatedTo(defaultConstraint, target, 1 /* RecursionFlags.Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65783,7 +66672,6 @@ var ts; if (isGenericMappedType(target)) { if (isGenericMappedType(source)) { if (result = mappedTypeRelatedTo(source, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); return result; } } @@ -65921,18 +66809,6 @@ var ts; } } } - function reportUnmeasurableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false); - } - return p; - } - function reportUnreliableMarkers(p) { - if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) { - outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true); - } - return p; - } // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice // that S and T are contra-variant whereas X and Y are co-variant. @@ -65942,7 +66818,7 @@ var ts; if (modifiersRelated) { var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); - var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); + var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMapper : reportUnreliableMapper); if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* RecursionFlags.Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { @@ -65996,11 +66872,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_20 = 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_21 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -66016,7 +66892,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_8 = _loop_21(i); + var state_8 = _loop_22(i); switch (state_8) { case "continue-outer": continue outer; } @@ -66030,7 +66906,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_7 = _loop_20(combination); + var state_7 = _loop_21(combination); if (typeof state_7 === "object") return state_7.value; } @@ -66478,7 +67354,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, makeFunctionTypeMapper(reportUnreliableMarkers)); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* SignatureCheckMode.StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, reportUnreliableMapper); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -66633,7 +67509,7 @@ var ts; return typeCouldHaveTopLevelSingletonTypes(constraint); } } - return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */); + return isUnitType(type) || !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */); } function getExactOptionalUnassignableProperties(source, target) { if (isTupleType(source) && isTupleType(target)) @@ -66737,7 +67613,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_22 = 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 */ : @@ -66773,12 +67649,12 @@ var ts; } variances.push(variance); }; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var tp = typeParameters_1[_i]; - _loop_22(tp); + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var tp = typeParameters_2[_i]; + _loop_23(tp); } links.variances = variances; - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); } return links.variances; } @@ -67116,35 +67992,33 @@ var ts; var commonBaseType; for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { var t = types_13[_i]; - var baseType = getBaseTypeOfLiteralType(t); - if (!commonBaseType) { - commonBaseType = baseType; - } - if (baseType === t || baseType !== commonBaseType) { - return false; + if (!(t.flags & 131072 /* TypeFlags.Never */)) { + var baseType = getBaseTypeOfLiteralType(t); + commonBaseType !== null && commonBaseType !== void 0 ? commonBaseType : (commonBaseType = baseType); + if (baseType === t || baseType !== commonBaseType) { + return false; + } } } return true; } - // When the candidate types are all literal types with the same base type, return a union - // of those literal types. Otherwise, return the leftmost type for which no type to the - // right is a supertype. - function getSupertypeOrUnion(types) { - if (types.length === 1) { - return types[0]; - } - return literalTypesWithSameBaseType(types) ? - getUnionType(types) : - ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + function getCombinedTypeFlags(types) { + return ts.reduceLeft(types, function (flags, t) { return flags | (t.flags & 1048576 /* TypeFlags.Union */ ? getCombinedTypeFlags(t.types) : t.flags); }, 0); } function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); + if (types.length === 1) { + return types[0]; } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* TypeFlags.Nullable */); }); - return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* TypeFlags.Nullable */) : - getUnionType(types, 2 /* UnionReduction.Subtype */); + // Remove nullable types from each of the candidates. + var primaryTypes = strictNullChecks ? ts.sameMap(types, function (t) { return filterType(t, function (u) { return !(u.flags & 98304 /* TypeFlags.Nullable */); }); }) : types; + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + var superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? + getUnionType(primaryTypes) : + ts.reduceLeft(primaryTypes, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + // Add any nullable types that occurred in the candidates back to the result. + return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & 98304 /* TypeFlags.Nullable */); } // Return the leftmost type for which no type to the right is a subtype. function getCommonSubtype(types) { @@ -67248,9 +68122,14 @@ var ts; type.flags & 256 /* TypeFlags.NumberLiteral */ ? numberType : type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? bigintType : type.flags & 512 /* TypeFlags.BooleanLiteral */ ? booleanType : - type.flags & 1048576 /* TypeFlags.Union */ ? mapType(type, getBaseTypeOfLiteralType) : + type.flags & 1048576 /* TypeFlags.Union */ ? getBaseTypeOfLiteralTypeUnion(type) : type; } + function getBaseTypeOfLiteralTypeUnion(type) { + var _a; + var key = "B".concat(getTypeId(type)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); + } function getWidenedLiteralType(type) { return type.flags & 1024 /* TypeFlags.EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : type.flags & 128 /* TypeFlags.StringLiteral */ && isFreshLiteralType(type) ? stringType : @@ -67331,29 +68210,8 @@ var ts; var value = _a.value; return value.base10Value === "0"; } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; - result |= getFalsyFlags(t); - } - return result; - } - // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null - // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns - // no flags for all other types (including non-falsy literal types). - function getFalsyFlags(type) { - return type.flags & 1048576 /* TypeFlags.Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? type.value === "" ? 128 /* TypeFlags.StringLiteral */ : 0 : - type.flags & 256 /* TypeFlags.NumberLiteral */ ? type.value === 0 ? 256 /* TypeFlags.NumberLiteral */ : 0 : - type.flags & 2048 /* TypeFlags.BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* TypeFlags.BigIntLiteral */ : 0 : - type.flags & 512 /* TypeFlags.BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* TypeFlags.BooleanLiteral */ : 0 : - type.flags & 117724 /* TypeFlags.PossiblyFalsy */; - } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 117632 /* TypeFlags.DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* TypeFlags.DefinitelyFalsy */); }) : - type; + return filterType(type, function (t) { return !!(getTypeFacts(t) & 4194304 /* TypeFacts.Truthy */); }); } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); @@ -67388,20 +68246,15 @@ var ts; return type.flags & 32768 /* TypeFlags.Undefined */ ? type : getUnionType([type, isProperty ? missingType : undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { - // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates - // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' - // that isn't eliminated by a NonNullable instantiation. - var reducedType = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* SymbolFlags.TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? - getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : - reducedType; + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : + getIntersectionType([type, emptyObjectType]); } function getNonNullableType(type) { - return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; + return strictNullChecks ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; @@ -67455,12 +68308,13 @@ var ts; * with no call or construct signatures. */ function isObjectTypeWithInferableIndex(type) { + var objectFlags = ts.getObjectFlags(type); return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* SymbolFlags.ObjectLiteral */ | 2048 /* SymbolFlags.TypeLiteral */ | 384 /* SymbolFlags.Enum */ | 512 /* SymbolFlags.ValueModule */)) !== 0 && !(type.symbol.flags & 32 /* SymbolFlags.Class */) - && !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & 4194304 /* ObjectFlags.ObjectRestType */) || !!(objectFlags & 1024 /* ObjectFlags.ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* CheckFlags.Readonly */); @@ -67793,27 +68647,29 @@ var ts; signature: signature, flags: flags, compareTypes: compareTypes, - mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }), - nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }), + mapper: reportUnmeasurableMapper, + nonFixingMapper: reportUnmeasurableMapper, }; + context.mapper = makeFixingMapperForContext(context); + context.nonFixingMapper = makeNonFixingMapperForContext(context); return context; } - function mapToInferredType(context, t, fix) { - var inferences = context.inferences; - for (var i = 0; i < inferences.length; i++) { - var inference = inferences[i]; - if (t === inference.typeParameter) { - if (fix && !inference.isFixed) { - // Before we commit to a particular inference (and thus lock out any further inferences), - // we infer from any intra-expression inference sites we have collected. - inferFromIntraExpressionSites(context); - clearCachedInferences(inferences); - inference.isFixed = true; - } - return getInferredType(context, i); + function makeFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (inference, i) { return function () { + if (!inference.isFixed) { + // Before we commit to a particular inference (and thus lock out any further inferences), + // we infer from any intra-expression inference sites we have collected. + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; } - } - return t; + return getInferredType(context, i); + }; })); + } + function makeNonFixingMapperForContext(context) { + return makeDeferredTypeMapper(ts.map(context.inferences, function (i) { return i.typeParameter; }), ts.map(context.inferences, function (_, i) { return function () { + return getInferredType(context, i); + }; })); } function clearCachedInferences(inferences) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { @@ -68082,13 +68938,40 @@ var ts; return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen); } - function isValidBigIntString(s) { + /** + * Tests whether the provided string can be parsed as a number. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting number matches the input when converted back to a string. + */ + function isValidNumberString(s, roundTripOnly) { + if (s === "") + return false; + var n = +s; + return isFinite(n) && (!roundTripOnly || "" + n === s); + } + /** + * @param text a valid bigint string excluding a trailing `n`, but including a possible prefix `-`. Use `isValidBigIntString(text, roundTripOnly)` before calling this function. + */ + function parseBigIntLiteralType(text) { + var negative = text.startsWith("-"); + var base10Value = ts.parsePseudoBigInt("".concat(negative ? text.slice(1) : text, "n")); + return getBigIntLiteralType({ negative: negative, base10Value: base10Value }); + } + /** + * Tests whether the provided string can be parsed as a bigint. + * @param s The string to test. + * @param roundTripOnly Indicates the resulting bigint matches the input when converted back to a string. + */ + function isValidBigIntString(s, roundTripOnly) { + if (s === "") + return false; var scanner = ts.createScanner(99 /* ScriptTarget.ESNext */, /*skipTrivia*/ false); var success = true; scanner.setOnError(function () { return success = false; }); scanner.setText(s + "n"); var result = scanner.scan(); - if (result === 40 /* SyntaxKind.MinusToken */) { + var negative = result === 40 /* SyntaxKind.MinusToken */; + if (negative) { result = scanner.scan(); } var flags = scanner.getTokenFlags(); @@ -68097,7 +68980,33 @@ var ts; // * a bigint can be scanned, and that when it is scanned, it is // * the full length of the input string (so the scanner is one character beyond the augmented input length) // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) - return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */); + return success && result === 9 /* SyntaxKind.BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* TokenFlags.ContainsSeparator */) + && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); + } + function isMemberOfStringMapping(source, target) { + if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + return true; + } + if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { + return isTypeAssignableTo(source, target); + } + if (target.flags & 268435456 /* TypeFlags.StringMapping */) { + // We need to see whether applying the same mappings of the target + // onto the source would produce an identical type *and* that + // it's compatible with the inner-most non-string-mapped type. + // + // The intuition here is that if same mappings don't affect the source at all, + // and the source is compatible with the unmapped target, then they must + // still reside in the same domain. + var mappingStack = []; + while (target.flags & 268435456 /* TypeFlags.StringMapping */) { + mappingStack.unshift(target.symbol); + target = target.type; + } + var mappedSource = ts.reduceLeft(mappingStack, function (memo, value) { return getStringMappingType(value, memo); }, source); + return mappedSource === source && isMemberOfStringMapping(source, target); + } + return false; } function isValidTypeForTemplateLiteralPlaceholder(source, target) { if (source === target || target.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */)) { @@ -68105,9 +69014,10 @@ var ts; } if (source.flags & 128 /* TypeFlags.StringLiteral */) { var value = source.value; - return !!(target.flags & 8 /* TypeFlags.Number */ && value !== "" && isFinite(+value) || - target.flags & 64 /* TypeFlags.BigInt */ && value !== "" && isValidBigIntString(value) || - target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName); + return !!(target.flags & 8 /* TypeFlags.Number */ && isValidNumberString(value, /*roundTripOnly*/ false) || + target.flags & 64 /* TypeFlags.BigInt */ && isValidBigIntString(value, /*roundTripOnly*/ false) || + target.flags & (512 /* TypeFlags.BooleanLiteral */ | 98304 /* TypeFlags.Nullable */) && value === target.intrinsicName || + target.flags & 268435456 /* TypeFlags.StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target)); } if (source.flags & 134217728 /* TypeFlags.TemplateLiteral */) { var texts = source.texts; @@ -68230,10 +69140,13 @@ var ts; propagationType = savePropagationType; return; } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - // Source and target are types originating in the same generic type alias declaration. - // Simply infer from source type arguments to target type arguments. - inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + if (source.aliasSymbol && source.aliasSymbol === target.aliasSymbol) { + if (source.aliasTypeArguments) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol)); + } + // And if there weren't any type arguments, there's no reason to run inference as the types must be the same. return; } if (source === target && source.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { @@ -68289,18 +69202,26 @@ var ts; target = getActualTypeVariable(target); } if (target.flags & 8650752 /* TypeFlags.TypeVariable */) { - // If target is a type parameter, make an inference, unless the source type contains - // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). - // Because the anyFunctionType is internal, it should not be exposed to the user by adding - // it as an inference candidate. Hopefully, a better candidate will come along that does - // not contain anyFunctionType when we come back to this argument for its second round - // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard - // when constructing types from type parameters that had no inference candidates). - if (source === nonInferrableAnyType || source === silentNeverType || (priority & 128 /* InferencePriority.ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + // Skip inference if the source is "blocked", which is used by the language service to + // prevent inference on nodes currently being edited. + if (isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); if (inference) { + // If target is a type parameter, make an inference, unless the source type contains + // a "non-inferrable" type. Types with this flag set are markers used to prevent inference. + // + // For example: + // - anyFunctionType is a wildcard type that's used to avoid contextually typing functions; + // it's internal, so should not be exposed to the user by adding it as a candidate. + // - autoType (and autoArrayType) is a special "any" used in control flow; like anyFunctionType, + // it's internal and should not be observable. + // - silentNeverType is returned by getInferredType when instantiating a generic function for + // inference (and a type variable has no mapping). + // + // This flag is infectious; if we produce Box (where never is silentNeverType), Box is + // also non-inferrable. if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) { return; } @@ -68357,15 +69278,11 @@ var ts; inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target)); } else if (source.flags & 4194304 /* TypeFlags.Index */ && target.flags & 4194304 /* TypeFlags.Index */) { - contravariant = !contravariant; - inferFromTypes(source.type, target.type); - contravariant = !contravariant; + inferFromContravariantTypes(source.type, target.type); } else if ((isLiteralType(source) || source.flags & 4 /* TypeFlags.String */) && target.flags & 4194304 /* TypeFlags.Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - contravariant = !contravariant; - inferWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); - contravariant = !contravariant; + inferFromContravariantTypesWithPriority(empty, target.type, 256 /* InferencePriority.LiteralKeyof */); } else if (source.flags & 8388608 /* TypeFlags.IndexedAccess */ && target.flags & 8388608 /* TypeFlags.IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -68378,10 +69295,7 @@ var ts; } else if (source.flags & 33554432 /* TypeFlags.Substitution */) { inferFromTypes(source.baseType, target); - var oldPriority = priority; - priority |= 4 /* InferencePriority.SubstituteSource */; - inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority - priority = oldPriority; + inferWithPriority(source.substitute, target, 4 /* InferencePriority.SubstituteSource */); // Make substitute inference at a lower priority } else if (target.flags & 16777216 /* TypeFlags.Conditional */) { invokeOnce(source, target, inferToConditionalType); @@ -68431,6 +69345,18 @@ var ts; inferFromTypes(source, target); priority = savePriority; } + function inferFromContravariantTypesWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromContravariantTypes(source, target); + priority = savePriority; + } + function inferToMultipleTypesWithPriority(source, targets, targetFlags, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferToMultipleTypes(source, targets, targetFlags); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -68495,10 +69421,13 @@ var ts; } } function inferFromContravariantTypes(source, target) { + contravariant = !contravariant; + inferFromTypes(source, target); + contravariant = !contravariant; + } + function inferFromContravariantTypesIfStrictFunctionTypes(source, target) { if (strictFunctionTypes || priority & 1024 /* InferencePriority.AlwaysStrict */) { - contravariant = !contravariant; - inferFromTypes(source, target); - contravariant = !contravariant; + inferFromContravariantTypes(source, target); } else { inferFromTypes(source, target); @@ -68517,8 +69446,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var type = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* TypeFlags.Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -68662,11 +69591,8 @@ var ts; inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else { - var savePriority = priority; - priority |= contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; - inferToMultipleTypes(source, targetTypes, target.flags); - priority = savePriority; + inferToMultipleTypesWithPriority(source, targetTypes, target.flags, contravariant ? 64 /* InferencePriority.ContravariantConditional */ : 0); } } function inferToTemplateLiteralType(source, target) { @@ -68679,8 +69605,57 @@ 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_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 + // allowed template literal placeholder types, infer from a literal type corresponding to the constraint. + if (source_1.flags & 128 /* TypeFlags.StringLiteral */ && target_3.flags & 8650752 /* TypeFlags.TypeVariable */) { + var inferenceContext = getInferenceInfoForType(target_3); + var constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : undefined; + if (constraint && !isTypeAny(constraint)) { + var constraintTypes = constraint.flags & 1048576 /* TypeFlags.Union */ ? constraint.types : [constraint]; + var allTypeFlags_1 = ts.reduceLeft(constraintTypes, function (flags, t) { return flags | t.flags; }, 0); + // If the constraint contains `string`, we don't need to look for a more preferred type + if (!(allTypeFlags_1 & 4 /* TypeFlags.String */)) { + var str_1 = source_1.value; + // If the type contains `number` or a number literal and the string isn't a valid number, exclude numbers + if (allTypeFlags_1 & 296 /* TypeFlags.NumberLike */ && !isValidNumberString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~296 /* TypeFlags.NumberLike */; + } + // If the type contains `bigint` or a bigint literal and the string isn't a valid bigint, exclude bigints + if (allTypeFlags_1 & 2112 /* TypeFlags.BigIntLike */ && !isValidBigIntString(str_1, /*roundTripOnly*/ true)) { + allTypeFlags_1 &= ~2112 /* TypeFlags.BigIntLike */; + } + // for each type in the constraint, find the highest priority matching type + var matchingType = ts.reduceLeft(constraintTypes, function (left, right) { + return !(right.flags & allTypeFlags_1) ? left : + left.flags & 4 /* TypeFlags.String */ ? left : right.flags & 4 /* TypeFlags.String */ ? source_1 : + left.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? left : right.flags & 134217728 /* TypeFlags.TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source_1, right) ? source_1 : + left.flags & 268435456 /* TypeFlags.StringMapping */ ? left : right.flags & 268435456 /* TypeFlags.StringMapping */ && str_1 === applyStringMapping(right.symbol, str_1) ? source_1 : + left.flags & 128 /* TypeFlags.StringLiteral */ ? left : right.flags & 128 /* TypeFlags.StringLiteral */ && right.value === str_1 ? right : + left.flags & 8 /* TypeFlags.Number */ ? left : right.flags & 8 /* TypeFlags.Number */ ? getNumberLiteralType(+str_1) : + left.flags & 32 /* TypeFlags.Enum */ ? left : right.flags & 32 /* TypeFlags.Enum */ ? getNumberLiteralType(+str_1) : + left.flags & 256 /* TypeFlags.NumberLiteral */ ? left : right.flags & 256 /* TypeFlags.NumberLiteral */ && right.value === +str_1 ? right : + left.flags & 64 /* TypeFlags.BigInt */ ? left : right.flags & 64 /* TypeFlags.BigInt */ ? parseBigIntLiteralType(str_1) : + left.flags & 2048 /* TypeFlags.BigIntLiteral */ ? left : right.flags & 2048 /* TypeFlags.BigIntLiteral */ && ts.pseudoBigIntToString(right.value) === str_1 ? right : + left.flags & 16 /* TypeFlags.Boolean */ ? left : right.flags & 16 /* TypeFlags.Boolean */ ? str_1 === "true" ? trueType : str_1 === "false" ? falseType : booleanType : + left.flags & 512 /* TypeFlags.BooleanLiteral */ ? left : right.flags & 512 /* TypeFlags.BooleanLiteral */ && right.intrinsicName === str_1 ? right : + left.flags & 32768 /* TypeFlags.Undefined */ ? left : right.flags & 32768 /* TypeFlags.Undefined */ && right.intrinsicName === str_1 ? right : + left.flags & 65536 /* TypeFlags.Null */ ? left : right.flags & 65536 /* TypeFlags.Null */ && right.intrinsicName === str_1 ? right : + left; + }, neverType); + if (!(matchingType.flags & 131072 /* TypeFlags.Never */)) { + inferFromTypes(matchingType, target_3); + return "continue"; + } + } + } + } + inferFromTypes(source_1, target_3); + }; for (var i = 0; i < types.length; i++) { - inferFromTypes(matches ? matches[i] : neverType, types[i]); + _loop_24(i); } } } @@ -68794,20 +69769,17 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } - function inferFromSignature(source, target, skipParameters) { - if (!skipParameters) { - var saveBivariant = bivariant; - var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; - // Once we descend into a bivariant signature we remain bivariant for all nested inferences - bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; - applyToParameterTypes(source, target, inferFromContravariantTypes); - bivariant = saveBivariant; - } + function inferFromSignature(source, target) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* SyntaxKind.Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 169 /* SyntaxKind.MethodDeclaration */ || kind === 168 /* SyntaxKind.MethodSignature */ || kind === 171 /* SyntaxKind.Constructor */; + applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes); + bivariant = saveBivariant; applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { @@ -69054,6 +70026,15 @@ var ts; var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); return key && key + "." + propName; } + break; + case 201 /* SyntaxKind.ObjectBindingPattern */: + case 202 /* SyntaxKind.ArrayBindingPattern */: + case 256 /* SyntaxKind.FunctionDeclaration */: + case 213 /* SyntaxKind.FunctionExpression */: + case 214 /* SyntaxKind.ArrowFunction */: + case 169 /* SyntaxKind.MethodDeclaration */: + // Handle pseudo-references originating in getNarrowedTypeOfSymbol. + return "".concat(getNodeId(node), "#").concat(getTypeId(declaredType)); } return undefined; } @@ -69198,7 +70179,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_23 = 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) { @@ -69222,9 +70203,9 @@ var ts; } } }; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - var state_9 = _loop_23(type); + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var type = types_15[_i]; + var state_9 = _loop_25(type); if (typeof state_9 === "object") return state_9.value; } @@ -69313,23 +70294,25 @@ var ts; // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 131072 /* TypeFlags.Never */) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType)) { - reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types - } - // Our crude heuristic produces an invalid result in some cases: see GH#26130. - // For now, when that happens, we give up and don't narrow at all. (This also - // means we'll never narrow for erroneous assignments where the assigned type - // is not assignable to the declared type.) - if (isTypeAssignableTo(assignedType, reducedType)) { - return reducedType; - } + var _a; + if (declaredType === assignedType) { + return declaredType; } - return declaredType; + if (assignedType.flags & 131072 /* TypeFlags.Never */) { + return assignedType; + } + var key = "A".concat(getTypeId(declaredType), ",").concat(getTypeId(assignedType)); + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); + } + function getAssignmentReducedTypeWorker(declaredType, assignedType) { + var filteredType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + // Ensure that we narrow to fresh types if the assignment is a fresh boolean literal type. + var reducedType = assignedType.flags & 512 /* TypeFlags.BooleanLiteral */ && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType; + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType; } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype @@ -69338,14 +70321,16 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type, ignoreObjects) { - if (ignoreObjects === void 0) { ignoreObjects = false; } + function getTypeFacts(type) { + if (type.flags & (2097152 /* TypeFlags.Intersection */ | 465829888 /* TypeFlags.Instantiable */)) { + type = getBaseConstraintOfType(type) || unknownType; + } var flags = type.flags; - if (flags & 4 /* TypeFlags.String */) { + if (flags & (4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */)) { return strictNullChecks ? 16317953 /* TypeFacts.StringStrictFacts */ : 16776705 /* TypeFacts.StringFacts */; } - if (flags & 128 /* TypeFlags.StringLiteral */) { - var isEmpty = type.value === ""; + if (flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */)) { + var isEmpty = flags & 128 /* TypeFlags.StringLiteral */ && type.value === ""; return strictNullChecks ? isEmpty ? 12123649 /* TypeFacts.EmptyStringStrictFacts */ : 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* TypeFacts.EmptyStringFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; @@ -69377,20 +70362,20 @@ var ts; (type === falseType || type === regularFalseType) ? 12580616 /* TypeFacts.FalseFacts */ : 16774920 /* TypeFacts.TrueFacts */; } if (flags & 524288 /* TypeFlags.Object */) { - if (ignoreObjects) { - return 16768959 /* TypeFacts.AndFactsMask */; // This is the identity element for computing type facts of intersection. - } return ts.getObjectFlags(type) & 16 /* ObjectFlags.Anonymous */ && isEmptyObjectType(type) ? - strictNullChecks ? 16318463 /* TypeFacts.EmptyObjectStrictFacts */ : 16777215 /* TypeFacts.EmptyObjectFacts */ : + strictNullChecks ? 83427327 /* TypeFacts.EmptyObjectStrictFacts */ : 83886079 /* TypeFacts.EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* TypeFacts.FunctionStrictFacts */ : 16728000 /* TypeFacts.FunctionFacts */ : strictNullChecks ? 7888800 /* TypeFacts.ObjectStrictFacts */ : 16736160 /* TypeFacts.ObjectFacts */; } - if (flags & (16384 /* TypeFlags.Void */ | 32768 /* TypeFlags.Undefined */)) { - return 9830144 /* TypeFacts.UndefinedFacts */; + if (flags & 16384 /* TypeFlags.Void */) { + return 9830144 /* TypeFacts.VoidFacts */; + } + if (flags & 32768 /* TypeFlags.Undefined */) { + return 26607360 /* TypeFacts.UndefinedFacts */; } if (flags & 65536 /* TypeFlags.Null */) { - return 9363232 /* TypeFacts.NullFacts */; + return 42917664 /* TypeFacts.NullFacts */; } if (flags & 12288 /* TypeFlags.ESSymbolLike */) { return strictNullChecks ? 7925520 /* TypeFacts.SymbolStrictFacts */ : 16772880 /* TypeFacts.SymbolFacts */; @@ -69401,37 +70386,56 @@ var ts; if (flags & 131072 /* TypeFlags.Never */) { return 0 /* TypeFacts.None */; } - if (flags & 465829888 /* TypeFlags.Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : - strictNullChecks ? 7929345 /* TypeFacts.NonEmptyStringStrictFacts */ : 16776705 /* TypeFacts.NonEmptyStringFacts */; - } if (flags & 1048576 /* TypeFlags.Union */) { - return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* TypeFacts.None */); + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t); }, 0 /* TypeFacts.None */); } if (flags & 2097152 /* TypeFlags.Intersection */) { - // When an intersection contains a primitive type we ignore object type constituents as they are - // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. - ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */)); - return getIntersectionTypeFacts(type, ignoreObjects); + return getIntersectionTypeFacts(type); } - return 16777215 /* TypeFacts.All */; + return 83886079 /* TypeFacts.UnknownFacts */; } - function getIntersectionTypeFacts(type, ignoreObjects) { + function getIntersectionTypeFacts(type) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + var ignoreObjects = maybeTypeOfKind(type, 131068 /* TypeFlags.Primitive */); // When computing the type facts of an intersection type, certain type facts are computed as `and` // and others are computed as `or`. var oredFacts = 0 /* TypeFacts.None */; - var andedFacts = 16777215 /* TypeFacts.All */; + var andedFacts = 134217727 /* TypeFacts.All */; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - var f = getTypeFacts(t, ignoreObjects); - oredFacts |= f; - andedFacts &= f; + if (!(ignoreObjects && t.flags & 524288 /* TypeFlags.Object */)) { + var f = getTypeFacts(t); + oredFacts |= f; + andedFacts &= f; + } } - return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 16768959 /* TypeFacts.AndFactsMask */; + return oredFacts & 8256 /* TypeFacts.OrFactsMask */ | andedFacts & 134209471 /* TypeFacts.AndFactsMask */; } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } + // This function is similar to getTypeWithFacts, except that in strictNullChecks mode it replaces type + // unknown with the union {} | null | undefined (and reduces that accordingly), and it intersects remaining + // instantiable types with {}, {} | null, or {} | undefined in order to remove null and/or undefined. + function getAdjustedTypeWithFacts(type, facts) { + var reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 /* TypeFlags.Unknown */ ? unknownUnionType : type, facts)); + if (strictNullChecks) { + switch (facts) { + case 524288 /* TypeFacts.NEUndefined */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ ? getIntersectionType([t, getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ && !maybeTypeOfKind(reduced, 65536 /* TypeFlags.Null */) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t; }); + case 1048576 /* TypeFacts.NENull */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 131072 /* TypeFacts.EQNull */ ? getIntersectionType([t, getTypeFacts(t) & 65536 /* TypeFacts.EQUndefined */ && !maybeTypeOfKind(reduced, 32768 /* TypeFlags.Undefined */) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t; }); + case 2097152 /* TypeFacts.NEUndefinedOrNull */: + case 4194304 /* TypeFacts.Truthy */: + return mapType(reduced, function (t) { return getTypeFacts(t) & 262144 /* TypeFacts.EQUndefinedOrNull */ ? getGlobalNonNullableTypeInstantiation(t) : t; }); + } + } + return reduced; + } + function recombineUnknownType(type) { + return type === unknownUnionType ? unknownType : type; + } function getTypeWithDefault(type, defaultExpression) { return defaultExpression ? getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : @@ -69586,19 +70590,17 @@ var ts; } return links.switchTypes; } - function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) { + // Get the type names from all cases in a switch on `typeof`. The default clause and/or duplicate type names are + // represented as undefined. Return undefined if one or more case clause expressions are not string literals. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + if (ts.some(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 289 /* SyntaxKind.CaseClause */ && !ts.isStringLiteralLike(clause.expression); })) { + return undefined; + } var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 289 /* SyntaxKind.CaseClause */) { - if (ts.isStringLiteralLike(clause.expression)) { - witnesses.push(clause.expression.text); - continue; - } - return ts.emptyArray; - } - if (retainDefault) - witnesses.push(/*explicitDefaultStatement*/ undefined); + var text = clause.kind === 289 /* SyntaxKind.CaseClause */ ? clause.expression.text : undefined; + witnesses.push(text && !ts.contains(witnesses, text) ? text : undefined); } return witnesses; } @@ -69680,8 +70682,8 @@ var ts; var types = origin && origin.flags & 1048576 /* TypeFlags.Union */ ? origin.types : type.types; var mappedTypes; var changed = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; var mapped = t.flags & 1048576 /* TypeFlags.Union */ ? mapType(t, mapper, noReductions) : mapper(t); changed || (changed = t !== mapped); if (mapped) { @@ -69767,8 +70769,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (!(t.flags & 131072 /* TypeFlags.Never */)) { if (!(ts.getObjectFlags(t) & 256 /* ObjectFlags.EvolvingArray */)) { return false; @@ -70229,7 +71231,7 @@ var ts; } // for (const _ in ref) acts as a nonnull on ref if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 243 /* SyntaxKind.ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { - return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)))); } // Assignment doesn't affect reference return undefined; @@ -70489,7 +71491,7 @@ var ts; if (isEvolvingArrayTypeList(types)) { return getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))); } - var result = getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + var result = recombineUnknownType(getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction)); if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* TypeFlags.Union */ && ts.arraysEqual(result.types, declaredType.types)) { return declaredType; } @@ -70591,11 +71593,10 @@ var ts; } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { - return type.flags & 2 /* TypeFlags.Unknown */ && assumeTrue ? nonNullUnknownType : - getTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); + return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 /* TypeFacts.Truthy */ : 8388608 /* TypeFacts.Falsy */); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -70717,7 +71718,7 @@ var ts; var targetType = ts.hasStaticModifier(ts.Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); } function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows: @@ -70735,7 +71736,7 @@ var ts; // Note that we include any and unknown in the exclusion test because their domain includes null and undefined. var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) || equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* TypeFlags.AnyOrUnknown */ | nullableFlags)); }); - return removeNullable ? getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; + return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */) : type; } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* TypeFlags.Any */) { @@ -70745,9 +71746,6 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (assumeTrue && (type.flags & 2 /* TypeFlags.Unknown */) && (operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 35 /* SyntaxKind.ExclamationEqualsToken */) && (valueType.flags & 65536 /* TypeFlags.Null */)) { - return getUnionType([nullType, undefinedType]); - } if ((type.flags & 2 /* TypeFlags.Unknown */) && assumeTrue && (operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */ || operator === 37 /* SyntaxKind.ExclamationEqualsEqualsToken */)) { if (valueType.flags & (131068 /* TypeFlags.Primitive */ | 67108864 /* TypeFlags.NonPrimitive */)) { return valueType; @@ -70767,7 +71765,7 @@ var ts; valueType.flags & 65536 /* TypeFlags.Null */ ? assumeTrue ? 131072 /* TypeFacts.EQNull */ : 1048576 /* TypeFacts.NENull */ : assumeTrue ? 65536 /* TypeFacts.EQUndefined */ : 524288 /* TypeFacts.NEUndefined */; - return type.flags & 2 /* TypeFlags.Unknown */ && facts & (1048576 /* TypeFacts.NENull */ | 2097152 /* TypeFacts.NEUndefinedOrNull */) ? nonNullUnknownType : getTypeWithFacts(type, facts); + return getAdjustedTypeWithFacts(type, facts); } if (assumeTrue) { var filterFn = operator === 34 /* SyntaxKind.EqualsEqualsToken */ ? @@ -70788,24 +71786,13 @@ var ts; var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } - if (type.flags & 1 /* TypeFlags.Any */ && literal.text === "function") { - return type; - } - if (assumeTrue && type.flags & 2 /* TypeFlags.Unknown */ && literal.text === "object") { - // The non-null unknown type is used to track whether a previous narrowing operation has removed the null type - // from the unknown type. For example, the expression `x && typeof x === 'object'` first narrows x to the non-null - // unknown type, and then narrows that to the non-primitive type. - return type === nonNullUnknownType ? nonPrimitiveType : getUnionType([nonPrimitiveType, nullType]); - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 128 /* TypeFacts.TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */; - var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text); - return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts); + return assumeTrue ? + narrowTypeByTypeName(type, literal.text) : + getTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeFacts.TypeofNEHostObject */); } function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); @@ -70852,97 +71839,52 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* TypeFlags.Never */ ? defaultType : getUnionType([caseType, defaultType]); } - function getImpliedTypeFromTypeofGuard(type, text) { - switch (text) { - case "function": - return type.flags & 1 /* TypeFlags.Any */ ? type : globalFunctionType; - case "object": - return type.flags & 2 /* TypeFlags.Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type; - default: - return typeofTypesByName.get(text); - } - } - // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are - // super-types of the implied guard will be retained in the final type: this is because type-facts only - // filter. Instead, we would like to replace those union constituents with the more precise type implied by - // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not - // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to - // filtering by type-facts. - function narrowUnionMemberByTypeof(candidate) { - return function (type) { - if (isTypeSubtypeOf(type, candidate)) { - return type; - } - if (isTypeSubtypeOf(candidate, type)) { - return candidate; - } - if (type.flags & 465829888 /* TypeFlags.Instantiable */) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(candidate, constraint)) { - return getIntersectionType([type, candidate]); - } - } - return type; - }; + function narrowTypeByTypeName(type, typeName) { + switch (typeName) { + case "string": return narrowTypeByTypeFacts(type, stringType, 1 /* TypeFacts.TypeofEQString */); + case "number": return narrowTypeByTypeFacts(type, numberType, 2 /* TypeFacts.TypeofEQNumber */); + case "bigint": return narrowTypeByTypeFacts(type, bigintType, 4 /* TypeFacts.TypeofEQBigInt */); + case "boolean": return narrowTypeByTypeFacts(type, booleanType, 8 /* TypeFacts.TypeofEQBoolean */); + case "symbol": return narrowTypeByTypeFacts(type, esSymbolType, 16 /* TypeFacts.TypeofEQSymbol */); + case "object": return type.flags & 1 /* TypeFlags.Any */ ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32 /* TypeFacts.TypeofEQObject */), narrowTypeByTypeFacts(type, nullType, 131072 /* TypeFacts.EQNull */)]); + case "function": return type.flags & 1 /* TypeFlags.Any */ ? type : narrowTypeByTypeFacts(type, globalFunctionType, 64 /* TypeFacts.TypeofEQFunction */); + case "undefined": return narrowTypeByTypeFacts(type, undefinedType, 65536 /* TypeFacts.EQUndefined */); + } + return narrowTypeByTypeFacts(type, nonPrimitiveType, 128 /* TypeFacts.TypeofEQHostObject */); + } + function narrowTypeByTypeFacts(type, impliedType, facts) { + return mapType(type, function (t) { + // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate + // the constituent based on its type facts. We use the strict subtype relation because it treats `object` + // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, + // but are classified as "function" according to `typeof`. + return isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? getTypeFacts(t) & facts ? t : neverType : + // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied + // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. + isTypeSubtypeOf(impliedType, t) ? impliedType : + // Neither the constituent nor the implied type is a subtype of the other, however their domains may still + // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate + // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. + getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : + neverType; + }); } function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { - var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true); - if (!switchWitnesses.length) { + var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!witnesses) { return type; } - // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause - var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); - var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); - var clauseWitnesses; - var switchFacts; - if (defaultCaseLocation > -1) { - // We no longer need the undefined denoting an explicit default case. Remove the undefined and - // fix-up clauseStart and clauseEnd. This means that we don't have to worry about undefined in the - // witness array. - var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); - // The adjusted clause start and end after removing the `default` statement. - var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; - var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; - clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); - switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); - } - else { - clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); - switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); - } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause. + var defaultIndex = ts.findIndex(switchStatement.caseBlock.clauses, function (clause) { return clause.kind === 290 /* SyntaxKind.DefaultClause */; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultIndex >= clauseStart && defaultIndex < clauseEnd); if (hasDefaultClause) { - return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }); + // In the default clause we filter constituents down to those that are not-equal to all handled cases. + var notEqualFacts_1 = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); + return filterType(type, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }); } - /* - The implied type is the raw type suggested by a - value being caught in this clause. - - When the clause contains a default case we ignore - the implied type and try to narrow using any facts - we can learn: see `switchFacts`. - - Example: - switch (typeof x) { - case 'number': - case 'string': break; - default: break; - case 'number': - case 'boolean': break - } - - In the first clause (case `number` and `string`) the - implied type is number | string. - - In the default clause we de not compute an implied type. - - In the third clause (case `number` and `boolean`) - the naive implied type is number | boolean, however - we use the type facts to narrow the implied type to - boolean. We know that number cannot be selected - because it is caught in the first clause. - */ - var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts); - return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts); + // In the non-default cause we create a union of the type narrowed by each of the listed cases. + var clauseWitnesses = witnesses.slice(clauseStart, clauseEnd); + return getUnionType(ts.map(clauseWitnesses, function (text) { return text ? narrowTypeByTypeName(type, text) : neverType; })); } function isMatchingConstructorReference(expr) { return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || @@ -70993,7 +71935,7 @@ var ts; var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { - return getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } return type; } @@ -71027,29 +71969,48 @@ var ts; if (!nonConstructorTypeInUnion) return type; } - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ true); + } + function getNarrowedType(type, candidate, assumeTrue, checkDerived) { + var _a; + var key = type.flags & 1048576 /* TypeFlags.Union */ ? "N".concat(getTypeId(type), ",").concat(getTypeId(candidate), ",").concat((assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)) : undefined; + return (_a = getCachedType(key)) !== null && _a !== void 0 ? _a : setCachedType(key, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { + function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) { + var isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf; if (!assumeTrue) { return filterType(type, function (t) { return !isRelated(t, candidate); }); } - // If the current type is a union type, remove all constituents that couldn't be instances of - // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 1048576 /* TypeFlags.Union */) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 131072 /* TypeFlags.Never */)) { - return assignableType; - } + if (type.flags & 3 /* TypeFlags.AnyOrUnknown */) { + return candidate; } - // If the candidate type is a subtype of the target type, narrow to the candidate type. - // Otherwise, if the target type is assignable to the candidate type, keep the target type. - // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate - // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the - // two types. - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); + // We first attempt to filter the current type, narrowing constituents as appropriate and removing + // constituents that are unrelated to the candidate. + var keyPropertyName = type.flags & 1048576 /* TypeFlags.Union */ ? getKeyPropertyName(type) : undefined; + var narrowedType = mapType(candidate, function (c) { + // If a discriminant property is available, use that to reduce the type. + var discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName); + var matching = discriminant && getConstituentTypeForKeyType(type, discriminant); + // For each constituent t in the current type, if t and and c are directly related, pick the most + // specific of the two. When t and c are related in both directions, we prefer c for type predicates + // because that is the asserted type, but t for `instanceof` because generics aren't reflected in + // prototype object types. + var directlyRelated = mapType(matching || type, checkDerived ? + function (t) { return isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType; } : + function (t) { return isTypeSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : neverType; }); + // If no constituents are directly related, create intersections for any generic constituents that + // are related by constraint. + return directlyRelated.flags & 131072 /* TypeFlags.Never */ ? + mapType(type, function (t) { return maybeTypeOfKind(t, 465829888 /* TypeFlags.Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType; }) : + directlyRelated; + }); + // If filtering produced a non-empty type, return that. Otherwise, pick the most specific of the two + // based on assignability, or as a last resort produce an intersection. + return !(narrowedType.flags & 131072 /* TypeFlags.Never */) ? narrowedType : + isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -71077,15 +72038,15 @@ var ts; var predicateArgument = getTypePredicateArgument(predicate, callExpression); if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + return getNarrowedType(type, predicate.type, assumeTrue, /*checkDerived*/ false); } if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && !(getTypeFacts(predicate.type) & 65536 /* TypeFacts.EQUndefined */)) { - type = getTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); + type = getAdjustedTypeWithFacts(type, 2097152 /* TypeFacts.NEUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(predicateArgument, type); if (access) { - return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); + return narrowTypeByDiscriminant(type, access, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, /*checkDerived*/ false); }); } } } @@ -71138,7 +72099,7 @@ var ts; } function narrowTypeByOptionality(type, expr, assumePresent) { if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); + return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 /* TypeFacts.NEUndefinedOrNull */ : 262144 /* TypeFacts.EQUndefinedOrNull */); } var access = getDiscriminantPropertyAccess(expr, type); if (access) { @@ -71224,8 +72185,8 @@ var ts; var annotationIncludesUndefined = strictNullChecks && declaration.kind === 164 /* SyntaxKind.Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 32768 /* TypeFlags.Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* TypeFlags.Undefined */); + getTypeFacts(declaredType) & 16777216 /* TypeFacts.IsUndefined */ && + !(getTypeFacts(checkExpression(declaration.initializer)) & 16777216 /* TypeFacts.IsUndefined */); popTypeResolution(); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* TypeFacts.NEUndefined */) : declaredType; } @@ -71246,7 +72207,9 @@ var ts; !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { - return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); + return type.flags & 2097152 /* TypeFlags.Intersection */ ? + ts.some(type.types, isGenericTypeWithUnionConstraint) : + !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* TypeFlags.Nullable */ | 1048576 /* TypeFlags.Union */)); } function isGenericTypeWithoutNullableConstraint(type) { return !!(type.flags & 465829888 /* TypeFlags.Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* TypeFlags.Nullable */)); @@ -71260,7 +72223,7 @@ var ts; !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 64 /* CheckMode.RestBindingElement */ ? getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) - : getContextualType(node)); + : getContextualType(node, /*contextFlags*/ undefined)); return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { @@ -71274,7 +72237,7 @@ var ts; var substituteConstraints = !(checkMode && checkMode & 2 /* CheckMode.Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); - return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* TypeFlags.Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (n) { @@ -71422,9 +72385,7 @@ var ts; getNodeLinks(container).flags |= 8192 /* NodeCheckFlags.CaptureArguments */; return getTypeOfSymbol(symbol); } - // We should only mark aliases as referenced if there isn't a local value declaration - // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that - if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + if (shouldMarkIdentifierAliasReferenced(node)) { markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); @@ -71551,13 +72512,32 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function shouldMarkIdentifierAliasReferenced(node) { + var _a; + var parent = node.parent; + if (parent) { + // A property access expression LHS? checkPropertyAccessExpression will handle that. + if (ts.isPropertyAccessExpression(parent) && parent.expression === node) { + return false; + } + // Next two check for an identifier inside a type only export. + if (ts.isExportSpecifier(parent) && parent.isTypeOnly) { + return false; + } + var greatGrandparent = (_a = parent.parent) === null || _a === void 0 ? void 0 : _a.parent; + if (greatGrandparent && ts.isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) { + return false; + } + } + return true; + } function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } @@ -71685,7 +72665,7 @@ var ts; } function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) { if (ts.isPropertyDeclaration(container) && ts.hasStaticModifier(container) && - container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.length(container.parent.decorators)) { + container.initializer && ts.textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && ts.hasDecorators(container.parent)) { error(thisExpression, ts.Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); } } @@ -72107,7 +73087,7 @@ var ts; // We have an object literal method. Check if the containing object literal has a contextual type // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in // any directly enclosing object literals. - var contextualType = getApparentTypeOfContextualType(containingLiteral); + var contextualType = getApparentTypeOfContextualType(containingLiteral, /*contextFlags*/ undefined); var literal = containingLiteral; var type = contextualType; while (type) { @@ -72119,7 +73099,7 @@ var ts; break; } literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); + type = getApparentTypeOfContextualType(literal, /*contextFlags*/ undefined); } // There was no contextual ThisType for the containing object literal, so the contextual type // for 'this' is the non-null form of the contextual type for the containing object literal or @@ -72176,7 +73156,7 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } - function getContextualTypeForVariableLikeDeclaration(declaration) { + function getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -72185,18 +73165,18 @@ var ts; case 164 /* SyntaxKind.Parameter */: return getContextuallyTypedParameterType(declaration); case 203 /* SyntaxKind.BindingElement */: - return getContextualTypeForBindingElement(declaration); + return getContextualTypeForBindingElement(declaration, contextFlags); case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isStatic(declaration)) { - return getContextualTypeForStaticPropertyDeclaration(declaration); + return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); } // By default, do nothing and return undefined - only the above cases have context implied by a parent } } - function getContextualTypeForBindingElement(declaration) { + function getContextualTypeForBindingElement(declaration, contextFlags) { var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - var parentType = getContextualTypeForVariableLikeDeclaration(parent) || + var parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== 203 /* SyntaxKind.BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 64 /* CheckMode.RestBindingElement */ : 0 /* CheckMode.Normal */); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; @@ -72212,8 +73192,8 @@ var ts; return getTypeOfPropertyOfType(parentType, text); } } - function getContextualTypeForStaticPropertyDeclaration(declaration) { - var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent); + function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) { + var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags); if (!parentType) return undefined; return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName); @@ -72229,29 +73209,32 @@ var ts; function getContextualTypeForInitializerExpression(node, contextFlags) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var result = getContextualTypeForVariableLikeDeclaration(declaration); + var result = getContextualTypeForVariableLikeDeclaration(declaration, contextFlags); if (result) { return result; } - if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable + if (!(contextFlags & 8 /* ContextFlags.SkipBindingPatterns */) && ts.isBindingPattern(declaration.name) && declaration.name.elements.length > 0) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } } return undefined; } - function getContextualTypeForReturnExpression(node) { + function getContextualTypeForReturnExpression(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { var functionFlags = ts.getFunctionFlags(func); if (functionFlags & 1 /* FunctionFlags.Generator */) { // Generator or AsyncGenerator function - var use = functionFlags & 2 /* FunctionFlags.Async */ ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; - var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined); - if (!iterationTypes) { + var isAsyncGenerator_1 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_1); }); + } + var iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + if (!iterationReturnType) { return undefined; } - contextualReturnType = iterationTypes.returnType; + contextualReturnType = iterationReturnType; // falls through to unwrap Promise for AsyncGenerators } if (functionFlags & 2 /* FunctionFlags.Async */) { // Async function or AsyncGenerator function @@ -72272,15 +73255,19 @@ var ts; } return undefined; } - function getContextualTypeForYieldOperand(node) { + function getContextualTypeForYieldOperand(node, contextFlags) { var func = ts.getContainingFunction(node); if (func) { var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); + var contextualReturnType = getContextualReturnType(func, contextFlags); if (contextualReturnType) { + var isAsyncGenerator_2 = (functionFlags & 2 /* FunctionFlags.Async */) !== 0; + if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* TypeFlags.Union */) { + contextualReturnType = filterType(contextualReturnType, function (type) { return !!getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, type, isAsyncGenerator_2); }); + } return node.asteriskToken ? contextualReturnType - : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, (functionFlags & 2 /* FunctionFlags.Async */) !== 0); + : getIterationTypeOfGeneratorFunctionReturnType(0 /* IterationTypeKind.Yield */, contextualReturnType, isAsyncGenerator_2); } } return undefined; @@ -72300,14 +73287,14 @@ var ts; } function getContextualIterationType(kind, functionDecl) { var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* FunctionFlags.Async */); - var contextualReturnType = getContextualReturnType(functionDecl); + var contextualReturnType = getContextualReturnType(functionDecl, /*contextFlags*/ undefined); if (contextualReturnType) { return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || undefined; } return undefined; } - function getContextualReturnType(functionDecl) { + function getContextualReturnType(functionDecl, contextFlags) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed var returnType = getReturnTypeFromAnnotation(functionDecl); @@ -72322,7 +73309,7 @@ var ts; } var iife = ts.getImmediatelyInvokedFunctionExpression(functionDecl); if (iife) { - return getContextualType(iife); + return getContextualType(iife, contextFlags); } return undefined; } @@ -72396,6 +73383,14 @@ var ts; var lhsType = getTypeOfExpression(e.expression); return ts.isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText); } + if (ts.isElementAccessExpression(e)) { + var propType = checkExpressionCached(e.argumentExpression); + if (!isTypeUsableAsPropertyName(propType)) { + return undefined; + } + var lhsType = getTypeOfExpression(e.expression); + return getPropertyOfType(lhsType, getPropertyNameFromType(propType)); + } return undefined; function tryGetPrivateIdentifierPropertyOfType(type, id) { var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id); @@ -72417,7 +73412,7 @@ var ts; if (decl && (ts.isPropertyDeclaration(decl) || ts.isPropertySignature(decl))) { var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); return (overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper)) || - (decl.initializer && getTypeOfExpression(binaryExpression.left)); + (ts.isPropertyDeclaration(decl) ? decl.initializer && getTypeOfExpression(binaryExpression.left) : undefined); } if (kind === 0 /* AssignmentDeclarationKind.None */) { return getTypeOfExpression(binaryExpression.left); @@ -72550,7 +73545,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; - var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element, contextFlags); if (propertyAssignmentType) { return propertyAssignmentType; } @@ -72585,8 +73580,8 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined; } - function getContextualTypeForChildJsxExpression(node, child) { - var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + function getContextualTypeForChildJsxExpression(node, child, contextFlags) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); // JSX expression is in children of JSX Element, we will look for an "children" attribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { @@ -72604,27 +73599,27 @@ var ts; } }, /*noReductions*/ true)); } - function getContextualTypeForJsxExpression(node) { + function getContextualTypeForJsxExpression(node, contextFlags) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) - ? getContextualType(node) + ? getContextualType(node, contextFlags) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent, node) + ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) : undefined; } - function getContextualTypeForJsxAttribute(attribute) { + function getContextualTypeForJsxAttribute(attribute, contextFlags) { // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName if (ts.isJsxAttribute(attribute)) { - var attributesType = getApparentTypeOfContextualType(attribute.parent); + var attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return getContextualType(attribute.parent); + return getContextualType(attribute.parent, contextFlags); } } // Return true if the given expression is possibly a discriminant value. We limit the kinds of @@ -72677,22 +73672,20 @@ var ts; 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 && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { // 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. - if (contextFlags && contextFlags & 1 /* ContextFlags.Signature */) { - return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); - } + return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); + } + if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.returnMapper) { // For other purposes (e.g. determining whether to produce literal types) we only // incorporate inferences made from the return type in a function call. We remove // the 'boolean' type from the contextual type such that contextually typed boolean // literals actually end up widening to 'boolean' (see #48363). - if (inferenceContext.returnMapper) { - var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); - return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? - filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : - type; - } + var type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); + return type.flags & 1048576 /* TypeFlags.Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? + filterType(type, function (t) { return t !== regularFalseType && t !== regularTrueType; }) : + type; } } return contextualType; @@ -72747,9 +73740,9 @@ var ts; return getContextualTypeForInitializerExpression(node, contextFlags); case 214 /* SyntaxKind.ArrowFunction */: case 247 /* SyntaxKind.ReturnStatement */: - return getContextualTypeForReturnExpression(node); + return getContextualTypeForReturnExpression(node, contextFlags); case 224 /* SyntaxKind.YieldExpression */: - return getContextualTypeForYieldOperand(parent); + return getContextualTypeForYieldOperand(parent, contextFlags); case 218 /* SyntaxKind.AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); case 208 /* SyntaxKind.CallExpression */: @@ -72787,17 +73780,17 @@ var ts; case 271 /* SyntaxKind.ExportAssignment */: return tryGetTypeFromEffectiveTypeNode(parent); case 288 /* SyntaxKind.JsxExpression */: - return getContextualTypeForJsxExpression(parent); + return getContextualTypeForJsxExpression(parent, contextFlags); case 285 /* SyntaxKind.JsxAttribute */: case 287 /* SyntaxKind.JsxSpreadAttribute */: - return getContextualTypeForJsxAttribute(parent); + return getContextualTypeForJsxAttribute(parent, contextFlags); case 280 /* SyntaxKind.JsxOpeningElement */: case 279 /* SyntaxKind.JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; function tryFindWhenConstTypeReference(node) { - return getContextualType(node); + return getContextualType(node, contextFlags); } } function getInferenceContext(node) { @@ -73057,8 +74050,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var current = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var current = types_18[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -73099,7 +74092,7 @@ var ts; var elementCount = elements.length; var elementTypes = []; var elementFlags = []; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var inDestructuringPattern = ts.isAssignmentTarget(node); var inConstContext = isConstContext(node); var hasOmittedExpression = false; @@ -73270,7 +74263,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var contextualType = getApparentTypeOfContextualType(node); + var contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ undefined); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 201 /* SyntaxKind.ObjectBindingPattern */ || contextualType.pattern.kind === 205 /* SyntaxKind.ObjectLiteralExpression */); var inConstContext = isConstContext(node); @@ -73609,7 +74602,7 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes, /*contextFlags*/ undefined); var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* SymbolFlags.Property */, jsxChildrenPropertyName); @@ -74220,19 +75213,19 @@ var ts; return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { - return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */); + return !!(getTypeFacts(type) & 50331648 /* TypeFacts.IsUndefinedOrNull */); } function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function reportObjectPossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportObjectPossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); } - function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { - error(node, flags & 32768 /* TypeFlags.Undefined */ ? flags & 65536 /* TypeFlags.Null */ ? + function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { + error(node, facts & 16777216 /* TypeFacts.IsUndefined */ ? facts & 33554432 /* TypeFacts.IsNull */ ? ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); @@ -74242,9 +75235,9 @@ var ts; error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* TypeFlags.Nullable */; - if (kind) { - reportError(node, kind); + var facts = getTypeFacts(type); + if (facts & 50331648 /* TypeFacts.IsUndefinedOrNull */) { + reportError(node, facts); var t = getNonNullableType(type); return t.flags & (98304 /* TypeFlags.Nullable */ | 131072 /* TypeFlags.Never */) ? errorType : t; } @@ -74413,9 +75406,8 @@ var ts; markAliasReferenced(parentSymbol, node); } return isErrorType(apparentType) ? errorType : apparentType; - ; } - prop = getPropertyOfType(apparentType, right.escapedText); + prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ false, /*includeTypeOnlyMembers*/ node.kind === 161 /* SyntaxKind.QualifiedName */); } // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. // `Foo` is also not referenced in `enum FooCopy { Bar = Foo.Bar }`, because the enum member value gets inlined @@ -74540,7 +75532,7 @@ var ts; assumeUninitialized = true; } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* TypeFlags.Undefined */) && getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */) { + if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) { error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; @@ -74723,9 +75715,9 @@ var ts; function getSuggestedSymbolForNonexistentProperty(name, containingType) { var props = getPropertiesOfType(containingType); if (typeof name !== "string") { - var parent_2 = name.parent; - if (ts.isPropertyAccessExpression(parent_2)) { - props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + var parent_3 = name.parent; + if (ts.isPropertyAccessExpression(parent_3)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_3, containingType, prop); }); } name = ts.idText(name); } @@ -75227,29 +76219,43 @@ var ts; // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. if (node.kind !== 165 /* SyntaxKind.Decorator */) { - var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); + var skipBindingPatterns = ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }); + var contextualType = getContextualType(node, skipBindingPatterns ? 8 /* ContextFlags.SkipBindingPatterns */ : 0 /* ContextFlags.None */); if (contextualType) { var inferenceTargetType = getReturnTypeOfSignature(signature); if (couldContainTypeVariables(inferenceTargetType)) { - // We clone the inference context to avoid disturbing a resolution in progress for an - // outer call expression. Effectively we just want a snapshot of whatever has been - // inferred for any outer call expression so far. var outerContext = getInferenceContext(node); - var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); - var instantiatedType = instantiateType(contextualType, outerMapper); - // If the contextual type is a generic function type with a single call signature, we - // instantiate the type with its own type parameters and type arguments. This ensures that - // the type parameters are not erased to type any during type inference such that they can - // be inferred as actual types from the contextual type. For example: - // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; - // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); - // Above, the type of the 'value' parameter is inferred to be 'A'. - var contextualSignature = getSingleCallSignature(instantiatedType); - var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : - instantiatedType; - // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + var isFromBindingPattern = !skipBindingPatterns && getContextualType(node, 8 /* ContextFlags.SkipBindingPatterns */) !== contextualType; + // A return type inference from a binding pattern can be used in instantiating the contextual + // type of an argument later in inference, but cannot stand on its own as the final return type. + // It is incorporated into `context.returnMapper` which is used in `instantiateContextualType`, + // but doesn't need to go into `context.inferences`. This allows a an array binding pattern to + // produce a tuple for `T` in + // declare function f(cb: () => T): T; + // const [e1, e2, e3] = f(() => [1, "hi", true]); + // but does not produce any inference for `T` in + // declare function f(): T; + // const [e1, e2, e3] = f(); + if (!isFromBindingPattern) { + // We clone the inference context to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* InferenceFlags.NoDefault */)); + var instantiatedType = instantiateType(contextualType, outerMapper); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* InferencePriority.ReturnType */); + } // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -75576,7 +76582,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_24 = 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 === 225 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -75593,7 +76599,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_24(i); + _loop_26(i); } return effectiveArgs_1; } @@ -75800,7 +76806,7 @@ var ts; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray; var typeArguments; - if (!isDecorator) { + if (!isDecorator && !ts.isSuperCall(node)) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 106 /* SyntaxKind.SuperKeyword */) { @@ -75879,6 +76885,15 @@ var ts; if (result) { return result; } + result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + // Preemptively cache the result; getResolvedSignature will do this after we return, but + // we need to ensure that the result is present for the error checks below so that if + // this signature is encountered again, we handle the circularity (rather than producing a + // different result which may produce no errors and assert). Callers of getResolvedSignature + // don't hit this issue because they only observe this result after it's had a chance to + // be cached, but the error reporting code below executes before getResolvedSignature sets + // resolvedSignature. + getNodeLinks(node).resolvedSignature = result; // No signatures were applicable. Now report errors based on the last applicable signature with // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, @@ -75913,7 +76928,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_25 = 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) { @@ -75931,7 +76946,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_25(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"); @@ -75970,7 +76985,7 @@ var ts; } } } - return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode); + return result; function addImplementationSuccessElaboration(failed, diagnostic) { var _a, _b; var oldCandidatesForArgumentError = candidatesForArgumentError; @@ -76050,7 +77065,7 @@ var ts; argCheckMode = checkMode & 32 /* CheckMode.IsForStringLiteralArgumentCompletions */; if (inferenceContext) { var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -76089,7 +77104,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_26 = 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; }); @@ -76097,7 +77112,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_26(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -76265,7 +77280,7 @@ var ts; // returns a function type, we choose to defer processing. This narrowly permits function composition // operators to flow inferences through return types, but otherwise processes calls right away. We // use the resolvingSignature singleton to indicate that we deferred processing. This result will be - // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and + // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and // from which we never make inferences). if (checkMode & 8 /* CheckMode.SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) { skippedGenericFunction(node, checkMode); @@ -76442,8 +77457,8 @@ var ts; if (apparentType.flags & 1048576 /* TypeFlags.Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var constituent = types_20[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var constituent = types_19[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -76609,7 +77624,7 @@ var ts; // file would probably be preferable. var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* SymbolFlags.Type */); var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* SymbolFlags.Type */, node); - var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); + var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */)); var parameterSymbol = createSymbol(1 /* SymbolFlags.FunctionScopedVariable */, "props"); parameterSymbol.type = result; return createSignature(declaration, @@ -76818,8 +77833,8 @@ var ts; var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode); if (signature === resolvingSignature) { // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that - // returns a function type. We defer checking and return nonInferrableType. - return nonInferrableType; + // returns a function type. We defer checking and return silentNeverType. + return silentNeverType; } checkDeprecatedSignature(signature, node); if (node.expression.kind === 106 /* SyntaxKind.SuperKeyword */) { @@ -77427,17 +78442,6 @@ var ts; } } } - var restType = getEffectiveRestType(context); - if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { - // The contextual signature has a generic rest parameter. We first instantiate the contextual - // signature (without fixing type parameters) and assign types to contextually typed parameters. - var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper); - assignContextualParameterTypes(signature, instantiatedContext); - // We then infer from a tuple type representing the parameters that correspond to the contextual - // rest parameter. - var restPos = getParameterCount(context) - 1; - inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType); - } } function assignContextualParameterTypes(signature, context) { if (context.typeParameters) { @@ -77630,7 +78634,7 @@ var ts; var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : - instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); + instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func, /*contextFlags*/ undefined); if (isGenerator) { yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* IterationTypeKind.Yield */, isAsync); returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* IterationTypeKind.Return */, isAsync); @@ -77701,7 +78705,7 @@ var ts; nextType = iterationTypes && iterationTypes.nextType; } else { - nextType = getContextualType(yieldExpression); + nextType = getContextualType(yieldExpression, /*contextFlags*/ undefined); } if (nextType) ts.pushIfUnique(nextTypes, nextType); @@ -77716,45 +78720,12 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - /** - * Collect the TypeFacts learned from a typeof switch with - * total clauses `witnesses`, and the active clause ranging - * from `start` to `end`. Parameter `hasDefault` denotes - * whether the active clause contains a default clause. - */ - function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + // Return the combined not-equal type facts for all cases except those between the start and end indices. + function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) { var facts = 0 /* TypeFacts.None */; - // When in the default we only collect inequality facts - // because default is 'in theory' a set of infinite - // equalities. - if (hasDefault) { - // Value is not equal to any types after the active clause. - for (var i = end; i < witnesses.length; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - // Remove inequalities for types that appear in the - // active clause because they appear before other - // types collected so far. - for (var i = start; i < end; i++) { - facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); - } - // Add inequalities for types before the active clause unconditionally. - for (var i = 0; i < start; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeFacts.TypeofNEHostObject */; - } - } - // When in an active clause without default the set of - // equalities is finite. - else { - // Add equalities for all types in the active clause. - for (var i = start; i < end; i++) { - facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeFacts.TypeofEQHostObject */; - } - // Remove equalities for types that appear before the - // active clause. - for (var i = 0; i < start; i++) { - facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); - } + for (var i = 0; i < witnesses.length; i++) { + var witness = i < start || i >= end ? witnesses[i] : undefined; + facts |= witness !== undefined ? typeofNEFacts.get(witness) || 32768 /* TypeFacts.TypeofNEHostObject */ : 0; } return facts; } @@ -77764,16 +78735,19 @@ var ts; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 216 /* SyntaxKind.TypeOfExpression */) { - var operandType = getTypeOfExpression(node.expression.expression); - var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); - // notEqualFacts states that the type of the switched value is not equal to every type in the switch. - var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_6 = getBaseConstraintOfType(operandType) || operandType; - // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_6.flags & 3 /* TypeFlags.AnyOrUnknown */) { - return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_1) === 556800 /* TypeFacts.AllTypeofNE */; + var witnesses = getSwitchClauseTypeOfWitnesses(node); + if (!witnesses) { + return false; } - return !!(filterType(type_6, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* TypeFlags.Never */); + var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(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 */) { + // We special case the top types to be exhaustive when all cases are handled. + return (556800 /* TypeFacts.AllTypeofNE */ & notEqualFacts_2) === 556800 /* TypeFacts.AllTypeofNE */; + } + // 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); if (!isLiteralType(type)) { @@ -77940,11 +78914,16 @@ var ts; if (isContextSensitive(node)) { if (contextualSignature) { var inferenceContext = getInferenceContext(node); + var instantiatedContextualSignature = void 0; if (checkMode && checkMode & 2 /* CheckMode.Inferential */) { inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); + var restType = getEffectiveRestType(contextualSignature); + if (restType && restType.flags & 262144 /* TypeFlags.TypeParameter */) { + instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper); + } } - var instantiatedContextualSignature = inferenceContext ? - instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature; + instantiatedContextualSignature || (instantiatedContextualSignature = inferenceContext ? + instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature); assignContextualParameterTypes(signature, instantiatedContextualSignature); } else { @@ -78134,7 +79113,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks && !(type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 131072 /* TypeFlags.Never */)) && - !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* SymbolFlags.Optional */ : getTypeFacts(type) & 16777216 /* TypeFacts.IsUndefined */)) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); } } @@ -78243,7 +79222,7 @@ var ts; error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } if (node.operator === 39 /* SyntaxKind.PlusToken */) { - if (maybeTypeOfKind(operandType, 2112 /* TypeFlags.BigIntLike */)) { + if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* TypeFlags.BigIntLike */)) { error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType))); } return numberType; @@ -78302,8 +79281,8 @@ var ts; } if (type.flags & 3145728 /* TypeFlags.UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { - var t = types_21[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var t = types_20[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -78530,7 +79509,7 @@ var ts; // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* TypeFlags.Undefined */)) { + !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & 16777216 /* TypeFacts.IsUndefined */)) { sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -78543,6 +79522,10 @@ var ts; if (target.kind === 221 /* SyntaxKind.BinaryExpression */ && target.operatorToken.kind === 63 /* SyntaxKind.EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; + // A default value is specified, so remove undefined from the final type. + if (strictNullChecks) { + sourceType = getTypeWithFacts(sourceType, 524288 /* TypeFacts.NEUndefined */); + } } if (target.kind === 205 /* SyntaxKind.ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); @@ -78683,7 +79666,11 @@ var ts; var operator = operatorToken.kind; if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */ || operator === 56 /* SyntaxKind.BarBarToken */ || operator === 60 /* SyntaxKind.QuestionQuestionToken */) { if (operator === 55 /* SyntaxKind.AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); + var parent = node.parent; + while (parent.kind === 212 /* SyntaxKind.ParenthesizedExpression */ + || ts.isBinaryExpression(parent) && (parent.operatorToken.kind === 55 /* SyntaxKind.AmpersandAmpersandToken */ || parent.operatorToken.kind === 56 /* SyntaxKind.BarBarToken */)) { + parent = parent.parent; + } checkTestingKnownTruthyCallableOrAwaitableType(node.left, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } checkTruthinessOfType(leftType, node.left); @@ -78907,6 +79894,10 @@ var ts; case 35 /* SyntaxKind.ExclamationEqualsToken */: case 36 /* SyntaxKind.EqualsEqualsEqualsToken */: case 37 /* SyntaxKind.ExclamationEqualsEqualsToken */: + if (ts.isLiteralExpressionOfObject(left) || ts.isLiteralExpressionOfObject(right)) { + var eqType = operator === 34 /* SyntaxKind.EqualsEqualsToken */ || operator === 36 /* SyntaxKind.EqualsEqualsEqualsToken */; + error(errorNode, ts.Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); + } reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); }); return booleanType; case 102 /* SyntaxKind.InstanceOfKeyword */: @@ -78926,7 +79917,7 @@ var ts; case 56 /* SyntaxKind.BarBarToken */: case 75 /* SyntaxKind.BarBarEqualsToken */: { var resultType_3 = getTypeFacts(leftType) & 8388608 /* TypeFacts.Falsy */ ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* UnionReduction.Subtype */) : + getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* UnionReduction.Subtype */) : leftType; if (operator === 75 /* SyntaxKind.BarBarEqualsToken */) { checkAssignmentOperator(rightType); @@ -79178,7 +80169,7 @@ var ts; type = anyType; addLazyDiagnostic(function () { if (noImplicitAny && !ts.expressionResultIsUnused(node)) { - var contextualType = getContextualType(node); + var contextualType = getContextualType(node, /*contextFlags*/ undefined); if (!contextualType || isTypeAny(contextualType)) { error(node, ts.Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); } @@ -79219,7 +80210,7 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + return isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(node, /*contextFlags*/ undefined) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; } function isTemplateLiteralContextualType(type) { return !!(type.flags & (128 /* TypeFlags.StringLiteral */ | 134217728 /* TypeFlags.TemplateLiteral */) || @@ -79247,7 +80238,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* TypeFlags.Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node, /*contextFlags*/ undefined)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -79362,7 +80353,7 @@ var ts; var type = checkExpression(node, checkMode, forceTuple); return isConstContext(node) || ts.isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : - getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node)); + getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node, /*contextFlags*/ undefined) : contextualType, node, /*contextFlags*/ undefined)); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. @@ -79472,8 +80463,8 @@ var ts; var result = []; var oldTypeParameters; var newTypeParameters; - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var tp = typeParameters_2[_i]; + for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { + var tp = typeParameters_3[_i]; var name = tp.symbol.escapedName; if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) { var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name); @@ -79795,12 +80786,14 @@ var ts; error(node, ts.Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); } else if (modifiers === 32768 /* ModifierFlags.In */ || modifiers === 65536 /* ModifierFlags.Out */) { - var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubType : markerSuperType); - var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperType : markerSubType); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); + var source = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck); + var target = createMarkerType(symbol, typeParameter, modifiers === 65536 /* ModifierFlags.Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck); var saveVarianceTypeParameter = typeParameter; varianceTypeParameter = typeParameter; checkTypeAssignableTo(source, target, node, ts.Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation); varianceTypeParameter = saveVarianceTypeParameter; + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } } @@ -79821,7 +80814,7 @@ var ts; error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + if ((node.questionToken || isJSDocOptionalParameter(node)) && ts.isBindingPattern(node.name) && func.body) { error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { @@ -80150,7 +81143,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_27 = 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)); @@ -80165,7 +81158,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_27(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -80198,6 +81191,9 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); + if (ts.isMethodDeclaration(node) && node.asteriskToken && ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_a_generator); + } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // method signatures already report "implementation not allowed in ambient context" elsewhere @@ -80325,6 +81321,9 @@ var ts; return !!ts.forEachChild(node, nodeImmediatelyReferencesSuperOrThis); } function checkAccessorDeclaration(node) { + if (ts.isIdentifier(node.name) && ts.idText(node.name) === "constructor") { + error(node.name, ts.Diagnostics.Class_constructor_may_not_be_an_accessor); + } addLazyDiagnostic(checkAccessorDeclarationDiagnostics); checkSourceElement(node.body); setNodeLinksForPrivateIdentifierScope(node); @@ -80382,6 +81381,12 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) { + if (index < typeParameters.length) { + return getTypeFromTypeNode(node.typeArguments[index]); + } + return getEffectiveTypeArguments(node, typeParameters)[index]; + } function getEffectiveTypeArguments(node, typeParameters) { return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } @@ -80623,8 +81628,11 @@ var ts; if (node.assertions) { var override = ts.getResolutionModeOverrideForClause(node.assertions.assertClause, grammarErrorOnNode); if (override) { + if (!ts.isNightly()) { + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + grammarErrorOnNode(node.assertions.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } } } @@ -81009,7 +82017,7 @@ var ts; * @param type The type of the promise. * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. */ - function getPromisedTypeOfPromise(type, errorNode) { + function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) { // // { // type // then( // thenFunction @@ -81044,7 +82052,29 @@ var ts; } return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); + var thisTypeForError; + var candidates; + for (var _i = 0, thenSignatures_1 = thenSignatures; _i < thenSignatures_1.length; _i++) { + var thenSignature = thenSignatures_1[_i]; + var thisType = getThisTypeOfSignature(thenSignature); + if (thisType && thisType !== voidType && !isTypeRelatedTo(type, thisType, subtypeRelation)) { + thisTypeForError = thisType; + } + else { + candidates = ts.append(candidates, thenSignature); + } + } + if (!candidates) { + ts.Debug.assertIsDefined(thisTypeForError); + if (thisTypeForErrorOut) { + thisTypeForErrorOut.value = thisTypeForError; + } + if (errorNode) { + error(errorNode, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError)); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(candidates, getTypeOfFirstParameterOfSignature)), 2097152 /* TypeFacts.NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -81098,6 +82128,34 @@ var ts; isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : type; } + function isAwaitedTypeNeeded(type) { + // If this is already an `Awaited`, we shouldn't wrap it. This helps to avoid `Awaited>` in higher-order. + if (isTypeAny(type) || isAwaitedTypeInstantiation(type)) { + return false; + } + // We only need `Awaited` if `T` contains possibly non-primitive types. + if (isGenericObjectType(type)) { + var baseConstraint = getBaseConstraintOfType(type); + // 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) : + maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { + return true; + } + } + return false; + } + function tryCreateAwaitedType(type) { + // Nothing to do if `Awaited` doesn't exist + var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); + if (awaitedSymbol) { + // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where + // an `Awaited` would suffice. + return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); + } + return undefined; + } function createAwaitedTypeIfNeeded(type) { // We wrap type `T` in `Awaited` based on the following conditions: // - `T` is not already an `Awaited`, and @@ -81106,26 +82164,10 @@ var ts; // - `T` has no base constraint, or // - The base constraint of `T` is `any`, `unknown`, `object`, or `{}`, or // - The base constraint of `T` is an object type with a callable `then` method. - if (isTypeAny(type)) { - return type; - } - // If this is already an `Awaited`, just return it. This helps to avoid `Awaited>` in higher-order. - if (isAwaitedTypeInstantiation(type)) { - return type; - } - // Only instantiate `Awaited` if `T` contains possibly non-primitive types. - if (isGenericObjectType(type)) { - var baseConstraint = getBaseConstraintOfType(type); - // Only instantiate `Awaited` if `T` 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)) { - // Nothing to do if `Awaited` doesn't exist - var awaitedSymbol = getGlobalAwaitedSymbol(/*reportErrors*/ true); - if (awaitedSymbol) { - // Unwrap unions that may contain `Awaited`, otherwise its possible to manufacture an `Awaited | U>` where - // an `Awaited` would suffice. - return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); - } + if (isAwaitedTypeNeeded(type)) { + var awaitedType = tryCreateAwaitedType(type); + if (awaitedType) { + return awaitedType; } } ts.Debug.assert(getPromisedTypeOfPromise(type) === undefined, "type provided should not be a non-generic 'promise'-like."); @@ -81165,10 +82207,24 @@ var ts; } // For a union, get a union of the awaited types of each constituent. if (type.flags & 1048576 /* TypeFlags.Union */) { + if (awaitedTypeStack.lastIndexOf(type.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } var mapper = errorNode ? function (constituentType) { return getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeNoAlias; - return typeAsAwaitable.awaitedTypeOfType = mapType(type, mapper); + awaitedTypeStack.push(type.id); + var mapped = mapType(type, mapper); + awaitedTypeStack.pop(); + return typeAsAwaitable.awaitedTypeOfType = mapped; } - var promisedType = getPromisedTypeOfPromise(type); + // If `type` is generic and should be wrapped in `Awaited`, return it. + if (isAwaitedTypeNeeded(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + var thisTypeForErrorOut = { value: undefined }; + var promisedType = getPromisedTypeOfPromise(type, /*errorNode*/ undefined, thisTypeForErrorOut); if (promisedType) { if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose @@ -81237,7 +82293,12 @@ var ts; if (isThenableType(type)) { if (errorNode) { ts.Debug.assertIsDefined(diagnosticMessage); - error(errorNode, diagnosticMessage, arg0); + var chain = void 0; + if (thisTypeForErrorOut.value) { + chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value)); + } + chain = ts.chainDiagnosticMessages(chain, diagnosticMessage, arg0); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, chain)); } return undefined; } @@ -81433,8 +82494,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { - var typeNode = types_22[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */ || typeNode.kind === 197 /* SyntaxKind.NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } @@ -81474,18 +82535,18 @@ var ts; } /** Check the decorators of a node */ function checkDecorators(node) { - if (!node.decorators) { - return; - } // skip this check for nodes that cannot have decorators. These should have already had an error reported by // checkGrammarDecorators. - if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node) || !node.modifiers || !ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { return; } if (!compilerOptions.experimentalDecorators) { error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning); } - var firstDecorator = node.decorators[0]; + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (!firstDecorator) { + return; + } checkExternalEmitHelpers(firstDecorator, 8 /* ExternalEmitHelpers.Decorate */); if (node.kind === 164 /* SyntaxKind.Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* ExternalEmitHelpers.Param */); @@ -81529,7 +82590,12 @@ var ts; break; } } - ts.forEach(node.decorators, checkDecorator); + for (var _f = 0, _g = node.modifiers; _f < _g.length; _f++) { + var modifier = _g[_f]; + if (ts.isDecorator(modifier)) { + checkDecorator(modifier); + } + } } function checkFunctionDeclaration(node) { addLazyDiagnostic(checkFunctionDeclarationDiagnostics); @@ -81560,6 +82626,11 @@ var ts; function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } + function checkJSDocLinkLikeTag(node) { + if (node.name) { + resolveJSDocMemberName(node.name, /*ignoreErrors*/ true); + } + } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); } @@ -81799,8 +82870,8 @@ var ts; return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); - for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { - var typeParameter = typeParameters_3[_i]; + for (var _i = 0, typeParameters_4 = typeParameters; _i < typeParameters_4.length; _i++) { + var typeParameter = typeParameters_4[_i]; if (!isTypeParameterUnused(typeParameter)) continue; var name = ts.idText(typeParameter.name); @@ -81960,6 +83031,22 @@ var ts; } }); } + function checkPotentialUncheckedRenamedBindingElementsInTypes() { + var _a; + for (var _i = 0, potentialUnusedRenamedBindingElementsInTypes_1 = potentialUnusedRenamedBindingElementsInTypes; _i < potentialUnusedRenamedBindingElementsInTypes_1.length; _i++) { + var node = potentialUnusedRenamedBindingElementsInTypes_1[_i]; + if (!((_a = getSymbolOfNode(node)) === null || _a === void 0 ? void 0 : _a.isReferenced)) { + var wrappingDeclaration = ts.walkUpBindingElementsAndPatterns(node); + ts.Debug.assert(ts.isParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here"); + var diagnostic = ts.createDiagnosticForNode(node.name, ts.Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, ts.declarationNameToString(node.name), ts.declarationNameToString(node.propertyName)); + if (!wrappingDeclaration.type) { + // entire parameter does not have type annotation, suggest adding an annotation + ts.addRelatedInfo(diagnostic, ts.createFileDiagnostic(ts.getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, ts.Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, ts.declarationNameToString(node.propertyName))); + } + diagnostics.add(diagnostic); + } + } + } function bindingNameText(name) { switch (name.kind) { case 79 /* SyntaxKind.Identifier */: @@ -82256,11 +83343,22 @@ var ts; // well known symbols. if (node.name.kind === 162 /* SyntaxKind.ComputedPropertyName */) { checkComputedPropertyName(node.name); - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkExpressionCached(node.initializer); } } if (ts.isBindingElement(node)) { + if (node.propertyName && + ts.isIdentifier(node.name) && + ts.isParameterDeclaration(node) && + ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + // type F = ({a: string}) => void; + // ^^^^^^ + // variable renaming in function type notation is confusing, + // so we forbid it even if noUnusedLocals is not enabled + potentialUnusedRenamedBindingElementsInTypes.push(node); + return; + } if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ScriptTarget.ES2018 */) { checkExternalEmitHelpers(node, 4 /* ExternalEmitHelpers.Rest */); } @@ -82293,14 +83391,14 @@ var ts; ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (ts.isParameter(node) && node.initializer && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; - var needCheckWidenedType = node.name.elements.length === 0; + var needCheckInitializer = ts.hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 243 /* SyntaxKind.ForInStatement */; + var needCheckWidenedType = !ts.some(node.name.elements, ts.not(ts.isOmittedExpression)); if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error var widenedType = getWidenedTypeForVariableLikeDeclaration(node); @@ -82327,7 +83425,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node)) { + if (symbol.flags & 2097152 /* SymbolFlags.Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node.kind === 203 /* SyntaxKind.BindingElement */ ? node.parent.parent : node)) { checkAliasSymbol(node); return; } @@ -82335,7 +83433,7 @@ var ts; if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - var initializer = ts.getEffectiveInitializer(node); + var initializer = ts.hasOnlyExpressionInitializer(node) && ts.getEffectiveInitializer(node); if (initializer) { var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && @@ -82360,7 +83458,7 @@ var ts; !(symbol.flags & 67108864 /* SymbolFlags.Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); } - if (node.initializer) { + if (ts.hasOnlyExpressionInitializer(node) && node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { @@ -82453,7 +83551,7 @@ var ts; return; var type = checkTruthinessExpression(location); var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) && isTypeAssertion(location.expression); - if (getFalsyFlags(type) || isPropertyExpressionCast) + if (!(getTypeFacts(type) & 4194304 /* TypeFacts.Truthy */) || isPropertyExpressionCast) return; // While it technically should be invalid for any known-truthy value // to be tested, we de-scope to functions and Promises unreferenced in @@ -82919,17 +84017,28 @@ var ts; * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. */ function getIterationTypesOfIterable(type, use, errorNode) { + var _a, _b; if (isTypeAny(type)) { return anyIterationTypes; } if (!(type.flags & 1048576 /* TypeFlags.Union */)) { - var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode); + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); if (iterationTypes_1 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } return undefined; } + else if ((_a = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _a === void 0 ? void 0 : _a.length) { + for (var _i = 0, _c = errorOutputContainer.errors; _i < _c.length; _i++) { + var diag = _c[_i]; + diagnostics.add(diag); + } + } return iterationTypes_1; } var cacheKey = use & 2 /* IterationUse.AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; @@ -82937,19 +84046,27 @@ var ts; if (cachedTypes) return cachedTypes === noIterationTypes ? undefined : cachedTypes; var allIterationTypes; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituent = _a[_i]; - var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode); + for (var _d = 0, _e = type.types; _d < _e.length; _d++) { + var constituent = _e[_d]; + var errorOutputContainer = errorNode ? { errors: undefined } : undefined; + var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer); if (iterationTypes_2 === noIterationTypes) { if (errorNode) { - reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + var rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* IterationUse.AllowsAsyncIterablesFlag */)); + if (errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) { + ts.addRelatedInfo.apply(void 0, __spreadArray([rootDiag], errorOutputContainer.errors, false)); + } } setCachedIterationTypes(type, cacheKey, noIterationTypes); return undefined; } - else { - allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); + else if ((_b = errorOutputContainer === null || errorOutputContainer === void 0 ? void 0 : errorOutputContainer.errors) === null || _b === void 0 ? void 0 : _b.length) { + for (var _f = 0, _g = errorOutputContainer.errors; _f < _g.length; _f++) { + var diag = _g[_f]; + diagnostics.add(diag); + } } + allIterationTypes = ts.append(allIterationTypes, iterationTypes_2); } var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes; setCachedIterationTypes(type, cacheKey, iterationTypes); @@ -82977,47 +84094,62 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableWorker(type, use, errorNode) { + function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) { if (isTypeAny(type)) { return anyIterationTypes; } + // If we are reporting errors and encounter a cached `noIterationTypes`, we should ignore the cached value and continue as if nothing was cached. + // In addition, we should not cache any new results for this call. + var noCache = false; if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver); if (iterationTypes) { - return use & 8 /* IterationUse.ForOfFlag */ ? - getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : - iterationTypes; + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; + } + else { + return use & 8 /* IterationUse.ForOfFlag */ ? + getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : + iterationTypes; + } } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver); if (iterationTypes) { - if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - // for a sync iterable in an async context, only use the cached types if they are valid. - if (iterationTypes !== noIterationTypes) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode)); - } + if (iterationTypes === noIterationTypes && errorNode) { + // ignore the cached value + noCache = true; } else { - return iterationTypes; + if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { + // for a sync iterable in an async context, only use the cached types if they are valid. + if (iterationTypes !== noIterationTypes) { + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); + } + } + else { + return iterationTypes; + } } } } if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { return iterationTypes; } } if (use & 1 /* IterationUse.AllowsSyncIterablesFlag */) { - var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode); + var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache); if (iterationTypes !== noIterationTypes) { if (use & 2 /* IterationUse.AllowsAsyncIterablesFlag */) { - return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes - ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) - : noIterationTypes); + iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode); + return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes); } else { return iterationTypes; @@ -83038,7 +84170,7 @@ var ts; } function getIterationTypesOfGlobalIterableType(globalType, resolver) { var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || - getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; } /** @@ -83092,26 +84224,26 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableSlow(type, resolver, errorNode) { + function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var _a; var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* SymbolFlags.Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); + return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); } var signatures = methodType ? getSignaturesOfType(methodType, 0 /* SignatureKind.Call */) : undefined; if (!ts.some(signatures)) { - return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); + return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); } var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature)); - var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes; - return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); + var iterationTypes = (_a = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache)) !== null && _a !== void 0 ? _a : noIterationTypes; + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { 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; - errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. @@ -83119,13 +84251,29 @@ var ts; * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, `undefined` is returned. */ - function getIterationTypesOfIterator(type, resolver, errorNode) { + function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { + return getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, /*noCache*/ false); + } + /** + * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. + * + * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` + * record is returned. Otherwise, `undefined` is returned. + * + * NOTE: You probably don't want to call this directly and should be calling + * `getIterationTypesOfIterator` instead. + */ + function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) { if (isTypeAny(type)) { return anyIterationTypes; } var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || - getIterationTypesOfIteratorFast(type, resolver) || - getIterationTypesOfIteratorSlow(type, resolver, errorNode); + getIterationTypesOfIteratorFast(type, resolver); + if (iterationTypes === noIterationTypes && errorNode) { + iterationTypes = undefined; + noCache = true; + } + iterationTypes !== null && iterationTypes !== void 0 ? iterationTypes : (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache)); return iterationTypes === noIterationTypes ? undefined : iterationTypes; } /** @@ -83163,7 +84311,7 @@ var ts; // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any` // and `undefined` in our libs by default, a custom lib *could* use different definitions. var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || - getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined); + getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType; return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } @@ -83233,8 +84381,8 @@ var ts; * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, we return `undefined`. */ - function getIterationTypesOfMethod(type, resolver, methodName, errorNode) { - var _a, _b, _c, _d; + function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) { + var _a, _b, _c, _d, _e, _f; var method = getPropertyOfType(type, methodName); // Ignore 'return' or 'throw' if they are missing. if (!method && methodName !== "next") { @@ -83254,9 +84402,15 @@ var ts; var diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic; - error(errorNode, diagnostic, methodName); + if (errorOutputContainer) { + (_a = errorOutputContainer.errors) !== null && _a !== void 0 ? _a : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, diagnostic, methodName)); + } + else { + error(errorNode, diagnostic, methodName); + } } - return methodName === "next" ? anyIterationTypes : undefined; + return methodName === "next" ? noIterationTypes : undefined; } // If the method signature comes exclusively from the global iterator or generator type, // create iteration types from its type arguments like `getIterationTypesOfIteratorFast` @@ -83268,8 +84422,8 @@ var ts; if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) { var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false); var globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false); - var isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) === null || _a === void 0 ? void 0 : _a.members) === null || _b === void 0 ? void 0 : _b.get(methodName)) === methodType.symbol; - var isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) === null || _c === void 0 ? void 0 : _c.members) === null || _d === void 0 ? void 0 : _d.get(methodName)) === methodType.symbol; + var isGeneratorMethod = ((_c = (_b = globalGeneratorType.symbol) === null || _b === void 0 ? void 0 : _b.members) === null || _c === void 0 ? void 0 : _c.get(methodName)) === methodType.symbol; + var isIteratorMethod = !isGeneratorMethod && ((_e = (_d = globalIteratorType.symbol) === null || _d === void 0 ? void 0 : _d.members) === null || _e === void 0 ? void 0 : _e.get(methodName)) === methodType.symbol; if (isGeneratorMethod || isIteratorMethod) { var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType; var mapper = methodType.mapper; @@ -83309,7 +84463,13 @@ var ts; var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType); if (iterationTypes === noIterationTypes) { if (errorNode) { - error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + if (errorOutputContainer) { + (_f = errorOutputContainer.errors) !== null && _f !== void 0 ? _f : (errorOutputContainer.errors = []); + errorOutputContainer.errors.push(ts.createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName)); + } + else { + error(errorNode, resolver.mustHaveAValueDiagnostic, methodName); + } } yieldType = anyType; returnTypes = ts.append(returnTypes, anyType); @@ -83330,13 +84490,13 @@ var ts; * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterator` instead. */ - function getIterationTypesOfIteratorSlow(type, resolver, errorNode) { + function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) { var iterationTypes = combineIterationTypes([ - getIterationTypesOfMethod(type, resolver, "next", errorNode), - getIterationTypesOfMethod(type, resolver, "return", errorNode), - getIterationTypesOfMethod(type, resolver, "throw", errorNode), + getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), + getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer), ]); - return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); + return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); } /** * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like, @@ -83357,7 +84517,7 @@ var ts; var use = isAsyncGenerator ? 2 /* IterationUse.AsyncGeneratorReturnType */ : 1 /* IterationUse.GeneratorReturnType */; var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) || - getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined); + getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined); } function checkBreakOrContinueStatement(node) { // Grammar checking @@ -83368,9 +84528,14 @@ var ts; function unwrapReturnType(returnType, functionFlags) { var isGenerator = !!(functionFlags & 1 /* FunctionFlags.Generator */); var isAsync = !!(functionFlags & 2 /* FunctionFlags.Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync) || errorType : - isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : - returnType; + if (isGenerator) { + var returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1 /* IterationTypeKind.Return */, returnType, isAsync); + if (!returnIterationType) { + return errorType; + } + return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType; + } + return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func)); @@ -83590,9 +84755,10 @@ var ts; } var indexInfos = getApplicableIndexInfos(type, propNameType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; - var localPropDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || - name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ || getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_28 = function (info) { + var propDeclaration = declaration && declaration.kind === 221 /* SyntaxKind.BinaryExpression */ || + name && name.kind === 162 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; + var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; + 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 @@ -83600,12 +84766,16 @@ var ts; var errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !ts.some(getBaseTypes(type), function (base) { return !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType); }) ? interfaceDeclaration : undefined); if (errorNode && !isTypeAssignableTo(propType, info.type)) { - error(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + var diagnostic = createError(errorNode, ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + if (propDeclaration && errorNode !== propDeclaration) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(propDeclaration, ts.Diagnostics._0_is_declared_here, symbolToString(prop))); + } + diagnostics.add(diagnostic); } }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_28(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -83613,7 +84783,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 258 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_29 = 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; @@ -83628,7 +84798,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_29(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -83817,8 +84987,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { - if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { - grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + var firstDecorator = ts.find(node.modifiers, ts.isDecorator); + if (firstDecorator && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(firstDecorator, ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -83947,7 +85118,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_30 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -83964,7 +85135,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_30(member); + _loop_32(member); } } /** @@ -84052,7 +85223,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_31 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -84071,7 +85242,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_31(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -84139,18 +85310,17 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. - var _a, _b; + var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { - continue; + return "continue"; } var baseSymbol = getPropertyOfObjectType(type, base.escapedName); if (!baseSymbol) { - continue; + return "continue"; } var derived = getTargetSymbol(baseSymbol); var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); @@ -84168,14 +85338,14 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { - var otherBaseType = _d[_c]; + for (var _e = 0, _f = getBaseTypes(type); _e < _f.length; _e++) { + var otherBaseType = _f[_e]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1); if (derivedElsewhere && derivedElsewhere !== base) { - continue basePropertyCheck; + return "continue-basePropertyCheck"; } } if (derivedClassDecl.kind === 226 /* SyntaxKind.ClassExpression */) { @@ -84190,20 +85360,19 @@ var ts; // derived overrides base. var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); if (baseDeclarationFlags & 8 /* ModifierFlags.Private */ || derivedDeclarationFlags & 8 /* ModifierFlags.Private */) { - // either base or derived property is private - not override, skip it - continue; + return "continue"; } var errorMessage = void 0; var basePropertyFlags = base.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; var derivedPropertyFlags = derived.flags & 98308 /* SymbolFlags.PropertyOrAccessor */; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor - if (baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 258 /* SyntaxKind.InterfaceDeclaration */ + if ((ts.getCheckFlags(base) & 6 /* CheckFlags.Synthetic */ + ? (_a = base.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); }) + : (_b = base.declarations) === null || _b === void 0 ? void 0 : _b.every(function (d) { return isPropertyAbstractOrInterface(d, baseDeclarationFlags); })) + || ts.getCheckFlags(base) & 262144 /* CheckFlags.Mapped */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { - // when the base property is abstract or from an interface, base/derived flags don't need to match - // same when the derived property is from an assignment - continue; + return "continue"; } var overriddenInstanceProperty = basePropertyFlags !== 4 /* SymbolFlags.Property */ && derivedPropertyFlags === 4 /* SymbolFlags.Property */; var overriddenInstanceAccessor = basePropertyFlags === 4 /* SymbolFlags.Property */ && derivedPropertyFlags !== 4 /* SymbolFlags.Property */; @@ -84214,12 +85383,12 @@ var ts; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { - var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); + var uninitialized = (_c = derived.declarations) === null || _c === void 0 ? void 0 : _c.find(function (d) { return d.kind === 167 /* SyntaxKind.PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* SymbolFlags.Transient */) && !(baseDeclarationFlags & 128 /* ModifierFlags.Abstract */) && !(derivedDeclarationFlags & 128 /* ModifierFlags.Abstract */) - && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { + && !((_d = derived.declarations) === null || _d === void 0 ? void 0 : _d.some(function (d) { return !!(d.flags & 16777216 /* NodeFlags.Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -84232,13 +85401,11 @@ var ts; } } } - // correct case - continue; + return "continue"; } else if (isPrototypeProperty(base)) { if (isPrototypeProperty(derived) || derived.flags & 4 /* SymbolFlags.Property */) { - // method is overridden with method or property -- correct case - continue; + return "continue"; } else { ts.Debug.assert(!!(derived.flags & 98304 /* SymbolFlags.Accessor */)); @@ -84253,9 +85420,20 @@ var ts; } error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } + }; + basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var state_10 = _loop_34(baseProperty); + switch (state_10) { + case "continue-basePropertyCheck": continue basePropertyCheck; + } } } - function getNonInterhitedProperties(type, baseTypes, properties) { + function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { + return baseDeclarationFlags & 128 /* ModifierFlags.Abstract */ && (!ts.isPropertyDeclaration(declaration) || !declaration.initializer) + || ts.isInterfaceDeclaration(declaration.parent); + } + function getNonInheritedProperties(type, baseTypes, properties) { if (!ts.length(baseTypes)) { return properties; } @@ -84324,7 +85502,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName) || ts.isComputedPropertyName(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* TypeFlags.Undefined */)) { + if (!(type.flags & 3 /* TypeFlags.AnyOrUnknown */ || containsUndefinedType(type))) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -84349,7 +85527,7 @@ var ts; ts.setParent(reference, staticBlock); reference.flowNode = staticBlock.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - if (!(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */)) { + if (!containsUndefinedType(flowType)) { return true; } } @@ -84364,7 +85542,7 @@ var ts; ts.setParent(reference, constructor); reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 32768 /* TypeFlags.Undefined */); + return !containsUndefinedType(flowType); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -84880,6 +86058,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a, _b, _c, _d, _e; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -84890,6 +86069,31 @@ var ts; // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). symbol = getMergedSymbol(symbol.exportSymbol || symbol); + // A type-only import/export will already have a grammar error in a JS file, so no need to issue more errors within + if (ts.isInJSFile(node) && !(target.flags & 111551 /* SymbolFlags.Value */) && !ts.isTypeOnlyImportOrExportDeclaration(node)) { + var errorNode = ts.isImportOrExportSpecifier(node) ? node.propertyName || node.name : + ts.isNamedDeclaration(node) ? node.name : + node; + ts.Debug.assert(node.kind !== 274 /* SyntaxKind.NamespaceExport */); + if (node.kind === 275 /* SyntaxKind.ExportSpecifier */) { + var diag = error(errorNode, ts.Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); + var alreadyExportedSymbol = (_b = (_a = ts.getSourceFileOfNode(node).symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.get((node.propertyName || node.name).escapedText); + if (alreadyExportedSymbol === target) { + var exportingDeclaration = (_c = alreadyExportedSymbol.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isJSDocNode); + if (exportingDeclaration) { + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(exportingDeclaration, ts.Diagnostics._0_is_automatically_exported_here, ts.unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName))); + } + } + } + else { + ts.Debug.assert(node.kind !== 254 /* SyntaxKind.VariableDeclaration */); + var importDeclaration = ts.findAncestor(node, ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration)); + var moduleSpecifier = (_e = (importDeclaration && ((_d = ts.tryGetModuleSpecifierFromDeclaration(importDeclaration)) === null || _d === void 0 ? void 0 : _d.text))) !== null && _e !== void 0 ? _e : "..."; + var importedIdentifier = ts.unescapeLeadingUnderscores(ts.isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); + error(errorNode, ts.Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, "import(\"".concat(moduleSpecifier, "\").").concat(importedIdentifier)); + } + return; + } 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); @@ -84995,10 +86199,10 @@ var ts; var override = ts.getResolutionModeOverrideForClause(declaration.assertClause, validForTypeAssertions ? grammarErrorOnNode : undefined); if (validForTypeAssertions && override) { if (!ts.isNightly()) { - grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); + grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next); } if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { - return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext); + return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext); } return; // Other grammar checks do not apply to type-only imports with resolution mode assertions } @@ -85205,7 +86409,9 @@ var ts; error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { - markExportAsReferenced(node); + if (!node.isTypeOnly && !node.parent.parent.isTypeOnly) { + markExportAsReferenced(node); + } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); @@ -85347,12 +86553,16 @@ var ts; } } function checkSourceElementWorker(node) { - if (ts.isInJSFile(node)) { - ts.forEach(node.jsDoc, function (_a) { - var tags = _a.tags; - return ts.forEach(tags, checkSourceElement); + ts.forEach(node.jsDoc, function (_a) { + var comment = _a.comment, tags = _a.tags; + checkJSDocCommentWorker(comment); + ts.forEach(tags, function (tag) { + checkJSDocCommentWorker(tag.comment); + if (ts.isInJSFile(node)) { + checkSourceElement(tag); + } }); - } + }); var kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessively @@ -85438,6 +86648,10 @@ var ts; return checkJSDocTemplateTag(node); case 343 /* SyntaxKind.JSDocTypeTag */: return checkJSDocTypeTag(node); + case 324 /* SyntaxKind.JSDocLink */: + case 325 /* SyntaxKind.JSDocLinkCode */: + case 326 /* SyntaxKind.JSDocLinkPlain */: + return checkJSDocLinkLikeTag(node); case 340 /* SyntaxKind.JSDocParameterTag */: return checkJSDocParameterTag(node); case 347 /* SyntaxKind.JSDocPropertyTag */: @@ -85532,6 +86746,15 @@ var ts; return checkMissingDeclaration(node); } } + function checkJSDocCommentWorker(node) { + if (ts.isArray(node)) { + ts.forEach(node, function (tag) { + if (ts.isJSDocLinkLike(tag)) { + checkSourceElement(tag); + } + }); + } + } function checkJSDocTypeIsInJsFile(node) { if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); @@ -85699,6 +86922,7 @@ var ts; ts.clear(potentialNewTargetCollisions); ts.clear(potentialWeakMapSetCollisions); ts.clear(potentialReflectCollisions); + ts.clear(potentialUnusedRenamedBindingElementsInTypes); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -85714,6 +86938,9 @@ var ts; } }); } + if (!node.isDeclarationFile) { + checkPotentialUncheckedRenamedBindingElementsInTypes(); + } }); if (compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ && !node.isDeclarationFile && @@ -86087,7 +87314,7 @@ var ts; if (!result && isJSDoc_1) { var container = ts.findAncestor(name, ts.or(ts.isClassLike, ts.isInterfaceDeclaration)); if (container) { - return resolveJSDocMemberName(name, getSymbolOfNode(container)); + return resolveJSDocMemberName(name, /*ignoreErrors*/ false, getSymbolOfNode(container)); } } return result; @@ -86133,11 +87360,11 @@ var ts; * * For unqualified names, a container K may be provided as a second argument. */ - function resolveJSDocMemberName(name, container) { + function resolveJSDocMemberName(name, ignoreErrors, container) { if (ts.isEntityName(name)) { // resolve static values first var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */ | 111551 /* SymbolFlags.Value */; - var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, ignoreErrors, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); if (!symbol && ts.isIdentifier(name) && container) { symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning)); } @@ -86145,7 +87372,7 @@ var ts; return symbol; } } - var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left); + var left = ts.isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container); var right = ts.isIdentifier(name) ? name.escapedText : name.right.escapedText; if (left) { var proto = left.flags & 111551 /* SymbolFlags.Value */ && getPropertyOfType(getTypeOfSymbol(left), "prototype"); @@ -87136,13 +88363,20 @@ var ts; if (!fileToDirective) { return undefined; } + // computed property name should use node as value // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; - if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + var meaning; + if (node.parent.kind === 162 /* SyntaxKind.ComputedPropertyName */) { meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; } + else { + meaning = 788968 /* SymbolFlags.Type */ | 1920 /* SymbolFlags.Namespace */; + if ((node.kind === 79 /* SyntaxKind.Identifier */ && isInTypeQuery(node)) || (node.kind === 206 /* SyntaxKind.PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */; + } + } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -87426,7 +88660,10 @@ var ts; return checkGrammarDecorators(node) || checkGrammarModifiers(node); } function checkGrammarDecorators(node) { - if (!node.decorators) { + if (ts.canHaveIllegalDecorators(node) && ts.some(node.illegalDecorators)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + if (!ts.canHaveDecorators(node) || !ts.hasDecorators(node)) { return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { @@ -87439,7 +88676,7 @@ var ts; } else if (node.kind === 172 /* SyntaxKind.GetAccessor */ || node.kind === 173 /* SyntaxKind.SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + if (ts.hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } } @@ -87454,6 +88691,8 @@ var ts; var flags = 0 /* ModifierFlags.None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; if (modifier.kind !== 145 /* SyntaxKind.ReadonlyKeyword */) { if (node.kind === 166 /* SyntaxKind.PropertySignature */ || node.kind === 168 /* SyntaxKind.MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); @@ -87739,6 +88978,13 @@ var ts; case 164 /* SyntaxKind.Parameter */: case 163 /* SyntaxKind.TypeParameter */: return false; + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 264 /* SyntaxKind.NamespaceExportDeclaration */: + case 179 /* SyntaxKind.FunctionType */: + case 276 /* SyntaxKind.MissingDeclaration */: + return true; default: if (node.parent.kind === 262 /* SyntaxKind.ModuleBlock */ || node.parent.kind === 305 /* SyntaxKind.SourceFile */) { return false; @@ -87749,20 +88995,26 @@ var ts; case 257 /* SyntaxKind.ClassDeclaration */: case 180 /* SyntaxKind.ConstructorType */: return nodeHasAnyModifiersExcept(node, 126 /* SyntaxKind.AbstractKeyword */); + case 226 /* SyntaxKind.ClassExpression */: case 258 /* SyntaxKind.InterfaceDeclaration */: case 237 /* SyntaxKind.VariableStatement */: case 259 /* SyntaxKind.TypeAliasDeclaration */: - case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: return true; case 260 /* SyntaxKind.EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 85 /* SyntaxKind.ConstKeyword */); default: - ts.Debug.fail(); + ts.Debug.assertNever(node); } } } function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (ts.isDecorator(modifier)) + continue; + return modifier.kind !== allowedModifier; + } + return false; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { @@ -88054,14 +89306,20 @@ var ts; grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration - if (prop.modifiers) { + if (ts.canHaveModifiers(prop) && prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */) { + if (ts.isModifier(mod) && (mod.kind !== 131 /* SyntaxKind.AsyncKeyword */ || prop.kind !== 169 /* SyntaxKind.MethodDeclaration */)) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } + else if (ts.canHaveIllegalModifiers(prop) && prop.modifiers) { + for (var _d = 0, _e = prop.modifiers; _d < _e.length; _d++) { + var mod = _e[_d]; + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and @@ -88073,10 +89331,9 @@ var ts; var currentKind = void 0; switch (prop.kind) { case 297 /* SyntaxKind.ShorthandPropertyAssignment */: - checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); - // falls through case 296 /* SyntaxKind.PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* SyntaxKind.NumericLiteral */) { checkGrammarNumericLiteral(name); @@ -88515,9 +89772,6 @@ var ts; else { return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (!isConstOrReadonly || isInvalidInitializer) { - return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } } } function checkGrammarVariableDeclaration(node) { @@ -88684,7 +89938,7 @@ var ts; } } function checkGrammarConstructorTypeAnnotation(node) { - var type = ts.getEffectiveReturnTypeNode(node); + var type = node.type || ts.getEffectiveReturnTypeNode(node); if (type) { return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); } @@ -88708,6 +89962,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Interfaces cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } @@ -88716,6 +89972,8 @@ var ts; if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } + // Type literals cannot contain property declarations + ts.Debug.assertNode(node, ts.isPropertySignature); if (node.initializer) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } @@ -89090,7 +90348,6 @@ var ts; if (nodes === undefined || visitor === undefined) { return nodes; } - var updated; // Ensure start and count have valid values var length = nodes.length; if (start === undefined || start < 0) { @@ -89103,12 +90360,49 @@ var ts; var pos = -1; var end = -1; if (start > 0 || count < length) { - // If we are not visiting all of the original nodes, we must always create a new array. // Since this is a fragment of a node array, we do not copy over the previous location // and will only copy over `hasTrailingComma` if we are including the last element. - updated = []; hasTrailingComma = nodes.hasTrailingComma && start + count === length; } + else { + pos = nodes.pos; + end = nodes.end; + hasTrailingComma = nodes.hasTrailingComma; + } + var updated = visitArrayWorker(nodes, visitor, test, start, count); + if (updated !== nodes) { + // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. + var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); + ts.setTextRangePosEnd(updatedArray, pos, end); + return updatedArray; + } + return nodes; + } + ts.visitNodes = visitNodes; + /* @internal */ + function visitArray(nodes, visitor, test, start, count) { + if (nodes === undefined) { + return nodes; + } + // Ensure start and count have valid values + var length = nodes.length; + if (start === undefined || start < 0) { + start = 0; + } + if (count === undefined || count > length - start) { + count = length - start; + } + return visitArrayWorker(nodes, visitor, test, start, count); + } + ts.visitArray = visitArray; + /* @internal */ + function visitArrayWorker(nodes, visitor, test, start, count) { + var updated; + var length = nodes.length; + if (start > 0 || count < length) { + // If we are not visiting all of the original nodes, we must always create a new array. + updated = []; + } // Visit each original node. for (var i = 0; i < count; i++) { var node = nodes[i + start]; @@ -89117,9 +90411,6 @@ var ts; if (updated === undefined) { // Ensure we have a copy of `nodes`, up to the current index. updated = nodes.slice(0, i); - hasTrailingComma = nodes.hasTrailingComma; - pos = nodes.pos; - end = nodes.end; } if (visited) { if (ts.isArray(visited)) { @@ -89136,15 +90427,8 @@ var ts; } } } - if (updated) { - // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory. - var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma); - ts.setTextRangePosEnd(updatedArray, pos, end); - return updatedArray; - } - return nodes; + return updated !== null && updated !== void 0 ? updated : nodes; } - ts.visitNodes = visitNodes; /** * Starts a new lexical environment and visits a statement list, ending the lexical environment * and merging hoisted declarations upon completion. @@ -89216,7 +90500,7 @@ var ts; /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) : factory.getGeneratedNameForNode(parameter)), ]))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, /*initializer*/ undefined); } function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { @@ -89224,7 +90508,7 @@ var ts; context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([ factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(ts.setEmitFlags(factory.cloneNode(name), 48 /* EmitFlags.NoSourceMap */), ts.setEmitFlags(initializer, 48 /* EmitFlags.NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* EmitFlags.NoComments */)), parameter), 1536 /* EmitFlags.NoComments */)) ]), parameter), 1 /* EmitFlags.SingleLine */ | 32 /* EmitFlags.NoTrailingSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */ | 1536 /* EmitFlags.NoComments */))); - return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, /*initializer*/ undefined); } function visitFunctionBody(node, visitor, context, nodeVisitor) { @@ -89290,7 +90574,7 @@ var ts; return factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); case 164 /* SyntaxKind.Parameter */: ts.Debug.type(node); - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + return factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 165 /* SyntaxKind.Decorator */: ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -89300,7 +90584,7 @@ var ts; return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 167 /* SyntaxKind.PropertyDeclaration */: ts.Debug.type(node); - return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), + return factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 168 /* SyntaxKind.MethodSignature */: @@ -89308,21 +90592,21 @@ var ts; return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 169 /* SyntaxKind.MethodDeclaration */: ts.Debug.type(node); - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 171 /* SyntaxKind.Constructor */: ts.Debug.type(node); - return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 172 /* SyntaxKind.GetAccessor */: ts.Debug.type(node); - return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 173 /* SyntaxKind.SetAccessor */: ts.Debug.type(node); - return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: ts.Debug.type(node); context.startLexicalEnvironment(); context.suspendLexicalEnvironment(); - return factory.updateClassStaticBlockDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 174 /* SyntaxKind.CallSignature */: ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -89331,7 +90615,7 @@ var ts; return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 176 /* SyntaxKind.IndexSignature */: ts.Debug.type(node); - return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types case 177 /* SyntaxKind.TypePredicate */: ts.Debug.type(node); @@ -89377,13 +90661,13 @@ var ts; return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); case 200 /* SyntaxKind.ImportType */: ts.Debug.type(node); - return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.assertions, visitor, ts.isNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); case 295 /* SyntaxKind.ImportTypeAssertionContainer */: ts.Debug.type(node); return factory.updateImportTypeAssertionContainer(node, nodeVisitor(node.assertClause, visitor, ts.isNode), node.multiLine); case 197 /* SyntaxKind.NamedTupleMember */: ts.Debug.type(node); - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + return factory.updateNamedTupleMember(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 191 /* SyntaxKind.ParenthesizedType */: ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); @@ -89448,7 +90732,7 @@ var ts; return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 210 /* SyntaxKind.TaggedTemplateExpression */: ts.Debug.type(node); - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); case 211 /* SyntaxKind.TypeAssertionExpression */: ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); @@ -89496,7 +90780,7 @@ var ts; return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 226 /* SyntaxKind.ClassExpression */: ts.Debug.type(node); - return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 228 /* SyntaxKind.ExpressionWithTypeArguments */: ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); @@ -89577,22 +90861,22 @@ var ts; return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 256 /* SyntaxKind.FunctionDeclaration */: ts.Debug.type(node); - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 257 /* SyntaxKind.ClassDeclaration */: ts.Debug.type(node); - return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + return factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifierLike), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 258 /* SyntaxKind.InterfaceDeclaration */: ts.Debug.type(node); - return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + return factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 259 /* SyntaxKind.TypeAliasDeclaration */: ts.Debug.type(node); - return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 260 /* SyntaxKind.EnumDeclaration */: ts.Debug.type(node); - return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + return factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 261 /* SyntaxKind.ModuleDeclaration */: ts.Debug.type(node); - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + return factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); case 262 /* SyntaxKind.ModuleBlock */: ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); @@ -89604,10 +90888,10 @@ var ts; return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); case 265 /* SyntaxKind.ImportEqualsDeclaration */: ts.Debug.type(node); - return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); + return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); case 266 /* SyntaxKind.ImportDeclaration */: ts.Debug.type(node); - return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 293 /* SyntaxKind.AssertClause */: ts.Debug.type(node); return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); @@ -89631,10 +90915,10 @@ var ts; return factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); case 271 /* SyntaxKind.ExportAssignment */: ts.Debug.type(node); - return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); + return factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); case 272 /* SyntaxKind.ExportDeclaration */: ts.Debug.type(node); - return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); + return factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression), nodeVisitor(node.assertClause, visitor, ts.isAssertClause)); case 273 /* SyntaxKind.NamedExports */: ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); @@ -90727,6 +92011,126 @@ var ts; return !ts.isStatic(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); } ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; + /** + * Gets an array of arrays of decorators for the parameters of a function-like node. + * The offset into the result array should correspond to the offset of the parameter. + * + * @param node The function-like node. + */ + function getDecoratorsOfParameters(node) { + var decorators; + if (node) { + var parameters = node.parameters; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; + if (decorators || ts.hasDecorators(parameter)) { + if (!decorators) { + decorators = new Array(numParameters); + } + decorators[i] = ts.getDecorators(parameter); + } + } + } + return decorators; + } + /** + * Gets an AllDecorators object containing the decorators for the class and the decorators for the + * parameters of the constructor of the class. + * + * @param node The class node. + */ + function getAllDecoratorsOfClass(node) { + var decorators = ts.getDecorators(node); + var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters + }; + } + ts.getAllDecoratorsOfClass = getAllDecoratorsOfClass; + /** + * Gets an AllDecorators object containing the decorators for the member and its parameters. + * + * @param parent The class node that contains the member. + * @param member The class member. + */ + function getAllDecoratorsOfClassElement(member, parent) { + switch (member.kind) { + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: + return getAllDecoratorsOfAccessors(member, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + return getAllDecoratorsOfMethod(member); + case 167 /* SyntaxKind.PropertyDeclaration */: + return getAllDecoratorsOfProperty(member); + default: + return undefined; + } + } + ts.getAllDecoratorsOfClassElement = getAllDecoratorsOfClassElement; + /** + * Gets an AllDecorators object containing the decorators for the accessor and its parameters. + * + * @param parent The class node that contains the accessor. + * @param accessor The class accessor member. + */ + function getAllDecoratorsOfAccessors(accessor, parent) { + if (!accessor.body) { + return undefined; + } + var _a = ts.getAllAccessorDeclarations(parent.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; + var firstAccessorWithDecorators = ts.hasDecorators(firstAccessor) ? firstAccessor : + secondAccessor && ts.hasDecorators(secondAccessor) ? secondAccessor : + undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { + return undefined; + } + var decorators = ts.getDecorators(firstAccessorWithDecorators); + var parameters = getDecoratorsOfParameters(setAccessor); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { + decorators: decorators, + parameters: parameters, + getDecorators: getAccessor && ts.getDecorators(getAccessor), + setDecorators: setAccessor && ts.getDecorators(setAccessor) + }; + } + /** + * Gets an AllDecorators object containing the decorators for the method and its parameters. + * + * @param method The class method member. + */ + function getAllDecoratorsOfMethod(method) { + if (!method.body) { + return undefined; + } + var decorators = ts.getDecorators(method); + var parameters = getDecoratorsOfParameters(method); + if (!ts.some(decorators) && !ts.some(parameters)) { + return undefined; + } + return { decorators: decorators, parameters: parameters }; + } + /** + * Gets an AllDecorators object containing the decorators for the property. + * + * @param property The class property member. + */ + function getAllDecoratorsOfProperty(property) { + var decorators = ts.getDecorators(property); + if (!ts.some(decorators)) { + return undefined; + } + return { decorators: decorators }; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -91000,8 +92404,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */ - && !(element.transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* TransformFlags.ContainsRestOrSpread */ | 32768 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (32768 /* TransformFlags.ContainsRestOrSpread */ | 65536 /* TransformFlags.ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -91067,7 +92471,7 @@ var ts; if (flattenContext.level >= 1 /* FlattenLevel.ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -91289,8 +92693,6 @@ var ts; var USE_NEW_TYPE_METADATA_FORMAT = false; var TypeScriptSubstitutionFlags; (function (TypeScriptSubstitutionFlags) { - /** Enables substitutions for decorated classes. */ - TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; /** Enables substitutions for namespace exports. */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; /* Enables substitutions for unqualified enum members */ @@ -91316,9 +92718,9 @@ var ts; var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); - var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var typeSerializer = compilerOptions.emitDecoratorMetadata ? ts.createRuntimeTypeSerializer(context) : undefined; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -91333,7 +92735,6 @@ var ts; var currentNamespace; var currentNamespaceContainerName; var currentLexicalScope; - var currentNameScope; var currentScopeFirstDeclarationsOfName; var currentClassHasParameterProperties; /** @@ -91341,11 +92742,6 @@ var ts; * They are persisted between each SourceFile transformation and should not be reset. */ var enabledSubstitutions; - /** - * A map that keeps track of aliases created for classes with decorators to avoid issues - * with the double-binding behavior of classes. - */ - var classAliases; /** * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. @@ -91389,7 +92785,6 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentLexicalScope; - var savedCurrentNameScope = currentNameScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties; // Handle state changes before visiting a node. @@ -91400,7 +92795,6 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } currentLexicalScope = savedCurrentScope; - currentNameScope = savedCurrentNameScope; currentClassHasParameterProperties = savedCurrentClassHasParameterProperties; return visited; } @@ -91416,7 +92810,6 @@ var ts; case 262 /* SyntaxKind.ModuleBlock */: case 235 /* SyntaxKind.Block */: currentLexicalScope = node; - currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; case 257 /* SyntaxKind.ClassDeclaration */: @@ -91434,10 +92827,6 @@ var ts; // programs may also have an undefined name. ts.Debug.assert(node.kind === 257 /* SyntaxKind.ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */)); } - if (ts.isClassDeclaration(node)) { - // XXX: should probably also cover interfaces and type aliases that can have type variables? - currentNameScope = node; - } break; } } @@ -91539,40 +92928,73 @@ var ts; return node; } /** - * Specialized visitor that visits the immediate children of a class with TypeScript syntax. + * Gets a specialized visitor that visits the immediate children of a class with TypeScript syntax. * - * @param node The node to visit. + * @param parent The class containing the elements to visit. */ - function classElementVisitor(node) { - return saveStateAndInvoke(node, classElementVisitorWorker); + function getClassElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return classElementVisitorWorker(n, parent); }); }; } /** * Specialized visitor that visits the immediate children of a class with TypeScript syntax. * * @param node The node to visit. */ - function classElementVisitorWorker(node) { + function classElementVisitorWorker(node, parent) { switch (node.kind) { case 171 /* SyntaxKind.Constructor */: return visitConstructor(node); case 167 /* SyntaxKind.PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. - return visitPropertyDeclaration(node); - case 176 /* SyntaxKind.IndexSignature */: + return visitPropertyDeclaration(node, parent); case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: - // Fallback to the default visit behavior. - return visitorWorker(node); + return ts.visitEachChild(node, visitor, context); case 234 /* SyntaxKind.SemicolonClassElement */: return node; + case 176 /* SyntaxKind.IndexSignature */: + // Index signatures are elided + return; + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function getObjectLiteralElementVisitor(parent) { + return function (node) { return saveStateAndInvoke(node, function (n) { return objectLiteralElementVisitorWorker(n, parent); }); }; + } + function objectLiteralElementVisitorWorker(node, parent) { + switch (node.kind) { + case 296 /* SyntaxKind.PropertyAssignment */: + case 297 /* SyntaxKind.ShorthandPropertyAssignment */: + case 298 /* SyntaxKind.SpreadAssignment */: + return visitor(node); + case 172 /* SyntaxKind.GetAccessor */: + // Get Accessors can have TypeScript modifiers, decorators, and type annotations. + return visitGetAccessor(node, parent); + case 173 /* SyntaxKind.SetAccessor */: + // Set Accessors can have TypeScript modifiers and type annotations. + return visitSetAccessor(node, parent); + case 169 /* SyntaxKind.MethodDeclaration */: + // TypeScript method declarations may have decorators, modifiers + // or type annotations. + return visitMethodDeclaration(node, parent); default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { + if (ts.isDecorator(node)) + return undefined; if (ts.modifierToFlag(node.kind) & 116958 /* ModifierFlags.TypeScriptModifier */) { return undefined; } @@ -91640,22 +93062,14 @@ var ts; // TypeScript type nodes are elided. // falls through case 176 /* SyntaxKind.IndexSignature */: - // TypeScript index signatures are elided. - // falls through - case 165 /* SyntaxKind.Decorator */: - // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. + // TypeScript index signatures are elided. return undefined; case 259 /* SyntaxKind.TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return factory.createNotEmittedStatement(node); - case 167 /* SyntaxKind.PropertyDeclaration */: - // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects - return visitPropertyDeclaration(node); case 264 /* SyntaxKind.NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 171 /* SyntaxKind.Constructor */: - return visitConstructor(node); case 258 /* SyntaxKind.InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. @@ -91689,16 +93103,15 @@ var ts; case 228 /* SyntaxKind.ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); + case 205 /* SyntaxKind.ObjectLiteralExpression */: + return visitObjectLiteralExpression(node); + case 171 /* SyntaxKind.Constructor */: + case 167 /* SyntaxKind.PropertyDeclaration */: case 169 /* SyntaxKind.MethodDeclaration */: - // TypeScript method declarations may have decorators, modifiers - // or type annotations. - return visitMethodDeclaration(node); case 172 /* SyntaxKind.GetAccessor */: - // Get Accessors can have TypeScript modifiers, decorators, and type annotations. - return visitGetAccessor(node); case 173 /* SyntaxKind.SetAccessor */: - // Set Accessors can have TypeScript modifiers and type annotations. - return visitSetAccessor(node); + case 170 /* SyntaxKind.ClassStaticBlockDeclaration */: + return ts.Debug.fail("Class and object literal elements must be visited with their respective visitors"); case 256 /* SyntaxKind.FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); @@ -91764,6 +93177,9 @@ var ts; !ts.isJsonSourceFile(node); return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } + function visitObjectLiteralExpression(node) { + return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, getObjectLiteralElementVisitor(node), ts.isObjectLiteralElement)); + } function getClassFacts(node, staticProperties) { var facts = 0 /* ClassFacts.None */; if (ts.some(staticProperties)) @@ -91786,17 +93202,18 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 4096 /* TransformFlags.ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 8192 /* TransformFlags.ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { - return ts.some(node.decorators) + return ts.hasDecorators(node) || ts.some(node.typeParameters) || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) || ts.some(node.members, hasTypeScriptClassSyntax); } function visitClassDeclaration(node) { if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */))) { - return ts.visitEachChild(node, visitor, context); + return factory.updateClassDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); var facts = getClassFacts(node, staticProperties); @@ -91804,14 +93221,25 @@ var ts; context.startLexicalEnvironment(); } var name = node.name || (facts & 5 /* ClassFacts.NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined); - var classStatement = facts & 2 /* ClassFacts.HasConstructorDecorators */ - ? createClassDeclarationHeadWithDecorators(node, name) - : createClassDeclarationHeadWithoutDecorators(node, name, facts); + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : ts.elideNodes(factory, node.modifiers); // preserve positions, if available + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var classStatement = factory.updateClassDeclaration(node, ts.concatenate(decorators, modifiers), name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); + // To better align with the old emitter, we should not emit a trailing source map + // entry if the class has static properties. + var emitFlags = ts.getEmitFlags(node); + if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { + emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; + } + ts.setEmitFlags(classStatement, emitFlags); var statements = [classStatement]; - // Write any decorators of the node. - addClassElementDecorationStatements(statements, node, /*isStatic*/ false); - addClassElementDecorationStatements(statements, node, /*isStatic*/ true); - addConstructorDecorationStatement(statements, node); if (facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) { // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the // 'es2015' transformer can properly nest static initializers and decorators. The result @@ -91871,164 +93299,13 @@ var ts; } return ts.singleOrMany(statements); } - /** - * Transforms a non-decorated class declaration and appends the resulting statements. - * - * @param node A ClassDeclaration node. - * @param name The name of the class. - * @param facts Precomputed facts about the class. - */ - function createClassDeclarationHeadWithoutDecorators(node, name, facts) { - // ${modifiers} class ${name} ${heritageClauses} { - // ${members} - // } - // we do not emit modifiers on the declaration if we are emitting an IIFE - var modifiers = !(facts & 128 /* ClassFacts.UseImmediatelyInvokedFunctionExpression */) - ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) - : undefined; - var classDeclaration = factory.createClassDeclaration( - /*decorators*/ undefined, modifiers, name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - // To better align with the old emitter, we should not emit a trailing source map - // entry if the class has static properties. - var emitFlags = ts.getEmitFlags(node); - if (facts & 1 /* ClassFacts.HasStaticInitializedProperties */) { - emitFlags |= 32 /* EmitFlags.NoTrailingSourceMap */; - } - ts.setTextRange(classDeclaration, node); - ts.setOriginalNode(classDeclaration, node); - ts.setEmitFlags(classDeclaration, emitFlags); - return classDeclaration; - } - /** - * Transforms a decorated class declaration and appends the resulting statements. If - * the class requires an alias to avoid issues with double-binding, the alias is returned. - */ - function createClassDeclarationHeadWithDecorators(node, name) { - // When we emit an ES6 class that has a class decorator, we must tailor the - // emit to certain specific cases. - // - // In the simplest case, we emit the class declaration as a let declaration, and - // evaluate decorators after the close of the class body: - // - // [Example 1] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // class C { | } - // } | C = __decorate([dec], C); - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | } - // } | C = __decorate([dec], C); - // | export { C }; - // --------------------------------------------------------------------- - // - // If a class declaration contains a reference to itself *inside* of the class body, - // this introduces two bindings to the class: One outside of the class body, and one - // inside of the class body. If we apply decorators as in [Example 1] above, there - // is the possibility that the decorator `dec` will return a new value for the - // constructor, which would result in the binding inside of the class no longer - // pointing to the same reference as the binding outside of the class. - // - // As a result, we must instead rewrite all references to the class *inside* of the - // class body to instead point to a local temporary alias for the class: - // - // [Example 2] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = C_1 = class C { - // class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | var C_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export { C }; - // | var C_1; - // --------------------------------------------------------------------- - // - // If a class declaration is the default export of a module, we instead emit - // the export after the decorated declaration: - // - // [Example 3] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let default_1 = class { - // export default class { | } - // } | default_1 = __decorate([dec], default_1); - // | export default default_1; - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | } - // } | C = __decorate([dec], C); - // | export default C; - // --------------------------------------------------------------------- - // - // If the class declaration is the default export and a reference to itself - // inside of the class body, we must emit both an alias for the class *and* - // move the export after the declaration: - // - // [Example 4] - // --------------------------------------------------------------------- - // TypeScript | Javascript - // --------------------------------------------------------------------- - // @dec | let C = class C { - // export default class C { | static x() { return C_1.y; } - // static x() { return C.y; } | } - // static y = 1; | C.y = 1; - // } | C = C_1 = __decorate([dec], C); - // | export default C; - // | var C_1; - // --------------------------------------------------------------------- - // - var location = ts.moveRangePastDecorators(node); - var classAlias = getClassAliasIfNeeded(node); - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - // ... = class ${name} ${heritageClauses} { - // ${members} - // } - var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node); - var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, location); - // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference - // or decoratedClassAlias if the class contain self-reference. - var statement = factory.createVariableStatement( - /*modifiers*/ undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(declName, - /*exclamationToken*/ undefined, - /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) - ], 1 /* NodeFlags.Let */)); - ts.setOriginalNode(statement, node); - ts.setTextRange(statement, location); - ts.setCommentRange(statement, node); - return statement; - } function visitClassExpression(node) { - if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { - return ts.visitEachChild(node, visitor, context); - } - var classExpression = factory.createClassExpression( - /*decorators*/ undefined, - /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node)); - ts.setOriginalNode(classExpression, node); - ts.setTextRange(classExpression, node); - return classExpression; + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators); + return factory.updateClassExpression(node, decorators, node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), isClassLikeDeclarationWithTypeScriptSyntax(node) ? + transformClassMembers(node) : + ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); } /** * Transforms the members of a class. @@ -92045,7 +93322,6 @@ var ts; var parameter = parametersWithPropertyAssignments_1[_i]; if (ts.isIdentifier(parameter.name)) { members.push(ts.setOriginalNode(factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameter.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, @@ -92053,159 +93329,9 @@ var ts; } } } - ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + ts.addRange(members, ts.visitNodes(node.members, getClassElementVisitor(node), ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - /** - * Gets either the static or instance members of a class that are decorated, or have - * parameters that are decorated. - * - * @param node The class containing the member. - * @param isStatic A value indicating whether to retrieve static or instance members of - * the class. - */ - function getDecoratedClassElements(node, isStatic) { - return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); }); - } - /** - * Determines whether a class member is a static member of a class that is decorated, or - * has parameters that are decorated. - * - * @param member The class member. - */ - function isStaticDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ true, parent); - } - /** - * Determines whether a class member is an instance member of a class that is decorated, - * or has parameters that are decorated. - * - * @param member The class member. - */ - function isInstanceDecoratedClassElement(member, parent) { - return isDecoratedClassElement(member, /*isStaticElement*/ false, parent); - } - /** - * Determines whether a class member is either a static or an instance member of a class - * that is decorated, or has parameters that are decorated. - * - * @param member The class member. - */ - function isDecoratedClassElement(member, isStaticElement, parent) { - return ts.nodeOrChildIsDecorated(member, parent) - && isStaticElement === ts.isStatic(member); - } - /** - * Gets an array of arrays of decorators for the parameters of a function-like node. - * The offset into the result array should correspond to the offset of the parameter. - * - * @param node The function-like node. - */ - function getDecoratorsOfParameters(node) { - var decorators; - if (node) { - var parameters = node.parameters; - var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); - var firstParameterOffset = firstParameterIsThis ? 1 : 0; - var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i + firstParameterOffset]; - if (decorators || parameter.decorators) { - if (!decorators) { - decorators = new Array(numParameters); - } - decorators[i] = parameter.decorators; - } - } - } - return decorators; - } - /** - * Gets an AllDecorators object containing the decorators for the class and the decorators for the - * parameters of the constructor of the class. - * - * @param node The class node. - */ - function getAllDecoratorsOfConstructor(node) { - var decorators = node.decorators; - var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node)); - if (!decorators && !parameters) { - return undefined; - } - return { - decorators: decorators, - parameters: parameters - }; - } - /** - * Gets an AllDecorators object containing the decorators for the member and its parameters. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function getAllDecoratorsOfClassElement(node, member) { - switch (member.kind) { - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - return getAllDecoratorsOfAccessors(node, member); - case 169 /* SyntaxKind.MethodDeclaration */: - return getAllDecoratorsOfMethod(member); - case 167 /* SyntaxKind.PropertyDeclaration */: - return getAllDecoratorsOfProperty(member); - default: - return undefined; - } - } - /** - * Gets an AllDecorators object containing the decorators for the accessor and its parameters. - * - * @param node The class node that contains the accessor. - * @param accessor The class accessor member. - */ - function getAllDecoratorsOfAccessors(node, accessor) { - if (!accessor.body) { - return undefined; - } - var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; - if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { - return undefined; - } - var decorators = firstAccessorWithDecorators.decorators; - var parameters = getDecoratorsOfParameters(setAccessor); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the method and its parameters. - * - * @param method The class method member. - */ - function getAllDecoratorsOfMethod(method) { - if (!method.body) { - return undefined; - } - var decorators = method.decorators; - var parameters = getDecoratorsOfParameters(method); - if (!decorators && !parameters) { - return undefined; - } - return { decorators: decorators, parameters: parameters }; - } - /** - * Gets an AllDecorators object containing the decorators for the property. - * - * @param property The class property member. - */ - function getAllDecoratorsOfProperty(property) { - var decorators = property.decorators; - if (!decorators) { - return undefined; - } - return { decorators: decorators }; - } /** * Transforms all of the decorators for a declaration into an array of expressions. * @@ -92213,212 +93339,89 @@ var ts; * @param allDecorators An object containing all of the decorators for the declaration. */ function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { + var _a, _b, _c, _d; if (!allDecorators) { return undefined; } - var decoratorExpressions = []; - ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); - ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, container, decoratorExpressions); - return decoratorExpressions; - } - /** - * Generates statements used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate statements for static or - * instance members. - */ - function addClassElementDecorationStatements(statements, node, isStatic) { - ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement)); - } - /** - * Generates expressions used to apply decorators to either the static or instance members - * of a class. - * - * @param node The class node. - * @param isStatic A value indicating whether to generate expressions for static or - * instance members. - */ - function generateClassElementDecorationExpressions(node, isStatic) { - var members = getDecoratedClassElements(node, isStatic); - var expressions; - for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { - var member = members_8[_i]; - var expression = generateClassElementDecorationExpression(node, member); - if (expression) { - if (!expressions) { - expressions = [expression]; - } - else { - expressions.push(expression); - } - } - } - return expressions; - } - /** - * Generates an expression used to evaluate class element decorators at runtime. - * - * @param node The class node that contains the member. - * @param member The class member. - */ - function generateClassElementDecorationExpression(node, member) { - var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - // Emit the call to __decorate. Given the following: - // - // class C { - // @dec method(@dec2 x) {} - // @dec get accessor() {} - // @dec prop; - // } - // - // The emit for a method is: - // - // __decorate([ - // dec, - // __param(0, dec2), - // __metadata("design:type", Function), - // __metadata("design:paramtypes", [Object]), - // __metadata("design:returntype", void 0) - // ], C.prototype, "method", null); - // - // The emit for an accessor is: - // - // __decorate([ - // dec - // ], C.prototype, "accessor", null); - // - // The emit for a property is: - // - // __decorate([ - // dec - // ], C.prototype, "prop"); - // - var prefix = getClassMemberPrefix(node, member); - var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); - var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ - ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ - // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it - // should not invoke `Object.getOwnPropertyDescriptor`. - ? factory.createVoidZero() - // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. - // We have this extra argument here so that we can inject an explicit property descriptor at a later date. - : factory.createNull() - : undefined; - var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); - ts.setTextRange(helper, ts.moveRangePastDecorators(member)); - ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - return helper; - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function addConstructorDecorationStatement(statements, node) { - var expression = generateConstructorDecorationExpression(node); - if (expression) { - statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); - } - } - /** - * Generates a __decorate helper call for a class constructor. - * - * @param node The class node. - */ - function generateConstructorDecorationExpression(node) { - var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); - if (!decoratorExpressions) { - return undefined; - } - var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; - // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name - // without any block-scoped variable collision handling - var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? - factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); - var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); - ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); - ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node)); - return expression; - } - /** - * Transforms a decorator into an expression. - * - * @param decorator The decorator node. - */ - function transformDecorator(decorator) { - return ts.visitNode(decorator.expression, visitor, ts.isExpression); + var decorators = ts.visitArray(allDecorators.decorators, visitor, ts.isDecorator); + var parameterDecorators = ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter); + var metadataDecorators = ts.some(decorators) || ts.some(parameterDecorators) ? getTypeMetadata(node, container) : undefined; + var result = factory.createNodeArray(ts.concatenate(ts.concatenate(decorators, parameterDecorators), metadataDecorators)); + var pos = (_b = (_a = ts.firstOrUndefined(allDecorators.decorators)) === null || _a === void 0 ? void 0 : _a.pos) !== null && _b !== void 0 ? _b : -1; + var end = (_d = (_c = ts.lastOrUndefined(allDecorators.decorators)) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : -1; + ts.setTextRangePosEnd(result, pos, end); + return result; } /** - * Transforms the decorators of a parameter. + * Transforms the decorators of a parameter into decorators of the class/method. * - * @param decorators The decorators for the parameter at the provided offset. + * @param parameterDecorators The decorators for the parameter at the provided offset. * @param parameterOffset The offset of the parameter. */ - function transformDecoratorsOfParameter(decorators, parameterOffset) { - var expressions; - if (decorators) { - expressions = []; - for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { - var decorator = decorators_1[_i]; - var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); - ts.setTextRange(helper, decorator.expression); + function transformDecoratorsOfParameter(parameterDecorators, parameterOffset) { + if (parameterDecorators) { + var decorators = []; + for (var _i = 0, parameterDecorators_1 = parameterDecorators; _i < parameterDecorators_1.length; _i++) { + var parameterDecorator = parameterDecorators_1[_i]; + var expression = ts.visitNode(parameterDecorator.expression, visitor, ts.isExpression); + var helper = emitHelpers().createParamHelper(expression, parameterOffset); + ts.setTextRange(helper, parameterDecorator.expression); ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); - expressions.push(helper); + var decorator = factory.createDecorator(helper); + ts.setSourceMapRange(decorator, parameterDecorator.expression); + ts.setCommentRange(decorator, parameterDecorator.expression); + ts.setEmitFlags(decorator, 1536 /* EmitFlags.NoComments */); + decorators.push(decorator); } + return decorators; } - return expressions; } /** - * Adds optional type metadata for a declaration. + * Gets optional type metadata for a declaration. * * @param node The declaration node. - * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node, container, decoratorExpressions) { - if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, container, decoratorExpressions); - } - else { - addOldTypeMetadata(node, container, decoratorExpressions); - } + function getTypeMetadata(node, container) { + return USE_NEW_TYPE_METADATA_FORMAT ? + getNewTypeMetadata(node, container) : + getOldTypeMetadata(node, container); } - function addOldTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getOldTypeMetadata(node, container) { + if (typeSerializer) { + var decorators = void 0; if (shouldAddTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node))); + var typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(typeMetadata)); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container))); + var paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container)); + decorators = ts.append(decorators, factory.createDecorator(paramTypesMetadata)); } if (shouldAddReturnTypeMetadata(node)) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node))); + var returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node)); + decorators = ts.append(decorators, factory.createDecorator(returnTypeMetadata)); } + return decorators; } } - function addNewTypeMetadata(node, container, decoratorExpressions) { - if (compilerOptions.emitDecoratorMetadata) { + function getNewTypeMetadata(node, container) { + if (typeSerializer) { var properties = void 0; if (shouldAddTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeTypeOfNode(node)))); + var typeProperty = factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, typeProperty); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); + var paramTypeProperty = factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node, container))); + properties = ts.append(properties, paramTypeProperty); } if (shouldAddReturnTypeMetadata(node)) { - (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); + var returnTypeProperty = factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* SyntaxKind.EqualsGreaterThanToken */), typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope: currentLexicalScope, currentNameScope: container }, node))); + properties = ts.append(properties, returnTypeProperty); } if (properties) { - decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true))); + var typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)); + return [factory.createDecorator(typeInfoMetadata)]; } } } @@ -92465,412 +93468,71 @@ var ts; } return false; } - function getAccessorTypeNode(node) { - var accessors = resolver.getAllAccessorDeclarations(node); - return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) - || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); - } /** - * Serializes the type of a node for use with decorator type metadata. + * Gets an expression that represents a property name (for decorated properties or enums). + * For a computed property, a name is generated for the node. * - * @param node The node that should have its type serialized. + * @param member The member whose name should be converted into an expression. */ - function serializeTypeOfNode(node) { - switch (node.kind) { - case 167 /* SyntaxKind.PropertyDeclaration */: - case 164 /* SyntaxKind.Parameter */: - return serializeTypeNode(node.type); - case 173 /* SyntaxKind.SetAccessor */: - case 172 /* SyntaxKind.GetAccessor */: - return serializeTypeNode(getAccessorTypeNode(node)); - case 257 /* SyntaxKind.ClassDeclaration */: - case 226 /* SyntaxKind.ClassExpression */: - case 169 /* SyntaxKind.MethodDeclaration */: - return factory.createIdentifier("Function"); - default: - return factory.createVoidZero(); + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isPrivateIdentifier(name)) { + return factory.createIdentifier(""); + } + else if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression) + ? factory.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return factory.createStringLiteral(ts.idText(name)); + } + else { + return factory.cloneNode(name); } } /** - * Serializes the types of the parameters of a node for use with decorator type metadata. + * Visits the property name of a class element, for use when emitting property + * initializers. For a computed property on a node with decorators, a temporary + * value is stored for later use. * - * @param node The node that should have its parameter types serialized. + * @param member The member whose name should be visited. */ - function serializeParameterTypesOfNode(node, container) { - var valueDeclaration = ts.isClassLike(node) - ? ts.getFirstConstructorWithBody(node) - : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) - ? node - : undefined; - var expressions = []; - if (valueDeclaration) { - var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); - var numParameters = parameters.length; - for (var i = 0; i < numParameters; i++) { - var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { - continue; - } - if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); - } - else { - expressions.push(serializeTypeOfNode(parameter)); - } - } - } - return factory.createArrayLiteralExpression(expressions); - } - function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { - var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; - if (setAccessor) { - return setAccessor.parameters; + function visitPropertyNameOfClassElement(member) { + var name = member.name; + // Computed property names need to be transformed into a hoisted variable when they are used more than once. + // The names are used more than once when: + // - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments). + // - the property has a decorator. + if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.hasDecorators(member))) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + if (!ts.isSimpleInlineableExpression(innerExpression)) { + var generatedName = factory.getGeneratedNameForNode(name); + hoistVariableDeclaration(generatedName); + return factory.updateComputedPropertyName(name, factory.createAssignment(generatedName, expression)); } } - return node.parameters; + return ts.visitNode(name, visitor, ts.isPropertyName); } /** - * Serializes the return type of a node for use with decorator type metadata. + * Transforms a HeritageClause with TypeScript syntax. * - * @param node The node that should have its return type serialized. + * This function will only be called when one of the following conditions are met: + * - The node is a non-`extends` heritage clause that should be elided. + * - The node is an `extends` heritage clause that should be visited, but only allow a single type. + * + * @param node The HeritageClause to transform. */ - function serializeReturnTypeOfNode(node) { - if (ts.isFunctionLike(node) && node.type) { - return serializeTypeNode(node.type); - } - else if (ts.isAsyncFunction(node)) { - return factory.createIdentifier("Promise"); + function visitHeritageClause(node) { + if (node.token === 117 /* SyntaxKind.ImplementsKeyword */) { + // implements clauses are elided + return undefined; } - return factory.createVoidZero(); + return ts.visitEachChild(node, visitor, context); } /** - * Serializes a type node for use with decorator type metadata. - * - * Types are serialized in the following fashion: - * - Void types point to "undefined" (e.g. "void 0") - * - Function and Constructor types point to the global "Function" constructor. - * - Interface types with a call or construct signature types point to the global - * "Function" constructor. - * - Array and Tuple types point to the global "Array" constructor. - * - Type predicates and booleans point to the global "Boolean" constructor. - * - String literal types and strings point to the global "String" constructor. - * - Enum and number types point to the global "Number" constructor. - * - Symbol types point to the global "Symbol" constructor. - * - Type references to classes (or class-like variables) point to the constructor for the class. - * - Anything else points to the global "Object" constructor. - * - * @param node The type node to serialize. - */ - function serializeTypeNode(node) { - if (node === undefined) { - return factory.createIdentifier("Object"); - } - switch (node.kind) { - case 114 /* SyntaxKind.VoidKeyword */: - case 153 /* SyntaxKind.UndefinedKeyword */: - case 143 /* SyntaxKind.NeverKeyword */: - return factory.createVoidZero(); - case 191 /* SyntaxKind.ParenthesizedType */: - return serializeTypeNode(node.type); - case 179 /* SyntaxKind.FunctionType */: - case 180 /* SyntaxKind.ConstructorType */: - return factory.createIdentifier("Function"); - case 183 /* SyntaxKind.ArrayType */: - case 184 /* SyntaxKind.TupleType */: - return factory.createIdentifier("Array"); - case 177 /* SyntaxKind.TypePredicate */: - case 133 /* SyntaxKind.BooleanKeyword */: - return factory.createIdentifier("Boolean"); - case 198 /* SyntaxKind.TemplateLiteralType */: - case 150 /* SyntaxKind.StringKeyword */: - return factory.createIdentifier("String"); - case 148 /* SyntaxKind.ObjectKeyword */: - return factory.createIdentifier("Object"); - case 196 /* SyntaxKind.LiteralType */: - switch (node.literal.kind) { - case 10 /* SyntaxKind.StringLiteral */: - case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: - return factory.createIdentifier("String"); - case 219 /* SyntaxKind.PrefixUnaryExpression */: - case 8 /* SyntaxKind.NumericLiteral */: - return factory.createIdentifier("Number"); - case 9 /* SyntaxKind.BigIntLiteral */: - return getGlobalBigIntNameWithFallback(); - case 110 /* SyntaxKind.TrueKeyword */: - case 95 /* SyntaxKind.FalseKeyword */: - return factory.createIdentifier("Boolean"); - case 104 /* SyntaxKind.NullKeyword */: - return factory.createVoidZero(); - default: - return ts.Debug.failBadSyntaxKind(node.literal); - } - case 147 /* SyntaxKind.NumberKeyword */: - return factory.createIdentifier("Number"); - case 158 /* SyntaxKind.BigIntKeyword */: - return getGlobalBigIntNameWithFallback(); - case 151 /* SyntaxKind.SymbolKeyword */: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case 178 /* SyntaxKind.TypeReference */: - return serializeTypeReferenceNode(node); - case 188 /* SyntaxKind.IntersectionType */: - case 187 /* SyntaxKind.UnionType */: - return serializeTypeList(node.types); - case 189 /* SyntaxKind.ConditionalType */: - return serializeTypeList([node.trueType, node.falseType]); - case 193 /* SyntaxKind.TypeOperator */: - if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { - return serializeTypeNode(node.type); - } - break; - case 181 /* SyntaxKind.TypeQuery */: - case 194 /* SyntaxKind.IndexedAccessType */: - case 195 /* SyntaxKind.MappedType */: - case 182 /* SyntaxKind.TypeLiteral */: - case 130 /* SyntaxKind.AnyKeyword */: - case 155 /* SyntaxKind.UnknownKeyword */: - case 192 /* SyntaxKind.ThisType */: - case 200 /* SyntaxKind.ImportType */: - break; - // handle JSDoc types from an invalid parse - case 312 /* SyntaxKind.JSDocAllType */: - case 313 /* SyntaxKind.JSDocUnknownType */: - case 317 /* SyntaxKind.JSDocFunctionType */: - case 318 /* SyntaxKind.JSDocVariadicType */: - case 319 /* SyntaxKind.JSDocNamepathType */: - break; - case 314 /* SyntaxKind.JSDocNullableType */: - case 315 /* SyntaxKind.JSDocNonNullableType */: - case 316 /* SyntaxKind.JSDocOptionalType */: - return serializeTypeNode(node.type); - default: - return ts.Debug.failBadSyntaxKind(node); - } - return factory.createIdentifier("Object"); - } - function serializeTypeList(types) { - // Note when updating logic here also update getEntityNameForDecoratorMetadata - // so that aliases can be marked as referenced - var serializedUnion; - for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { - var typeNode = types_23[_i]; - while (typeNode.kind === 191 /* SyntaxKind.ParenthesizedType */) { - typeNode = typeNode.type; // Skip parens if need be - } - if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { - continue; // Always elide `never` from the union/intersection if possible - } - if (!strictNullChecks && (typeNode.kind === 196 /* SyntaxKind.LiteralType */ && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */ || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { - continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks - } - var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { - // One of the individual is global object, return immediately - return serializedIndividual; - } - // If there exists union that is not void 0 expression, check if the the common type is identifier. - // anything more complex and we will just default to Object - else if (serializedUnion) { - // Different types - if (!ts.isIdentifier(serializedUnion) || - !ts.isIdentifier(serializedIndividual) || - serializedUnion.escapedText !== serializedIndividual.escapedText) { - return factory.createIdentifier("Object"); - } - } - else { - // Initialize the union type - serializedUnion = serializedIndividual; - } - } - // If we were able to find common type, use it - return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never - } - /** - * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with - * decorator type metadata. - * - * @param node The type reference node. - */ - function serializeTypeReferenceNode(node) { - var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); - switch (kind) { - case ts.TypeReferenceSerializationKind.Unknown: - // From conditional type type reference that cannot be resolved is Similar to any or unknown - if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { - return factory.createIdentifier("Object"); - } - var serialized = serializeEntityNameAsExpressionFallback(node.typeName); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), - /*questionToken*/ undefined, temp, - /*colonToken*/ undefined, factory.createIdentifier("Object")); - case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName); - case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: - return factory.createVoidZero(); - case ts.TypeReferenceSerializationKind.BigIntLikeType: - return getGlobalBigIntNameWithFallback(); - case ts.TypeReferenceSerializationKind.BooleanType: - return factory.createIdentifier("Boolean"); - case ts.TypeReferenceSerializationKind.NumberLikeType: - return factory.createIdentifier("Number"); - case ts.TypeReferenceSerializationKind.StringLikeType: - return factory.createIdentifier("String"); - case ts.TypeReferenceSerializationKind.ArrayLikeType: - return factory.createIdentifier("Array"); - case ts.TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < 2 /* ScriptTarget.ES2015 */ - ? getGlobalSymbolNameWithFallback() - : factory.createIdentifier("Symbol"); - case ts.TypeReferenceSerializationKind.TypeWithCallSignature: - return factory.createIdentifier("Function"); - case ts.TypeReferenceSerializationKind.Promise: - return factory.createIdentifier("Promise"); - case ts.TypeReferenceSerializationKind.ObjectType: - return factory.createIdentifier("Object"); - default: - return ts.Debug.assertNever(kind); - } - } - function createCheckedValue(left, right) { - return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right); - } - /** - * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpressionFallback(node) { - if (node.kind === 79 /* SyntaxKind.Identifier */) { - // A -> typeof A !== undefined && A - var copied = serializeEntityNameAsExpression(node); - return createCheckedValue(copied, copied); - } - if (node.left.kind === 79 /* SyntaxKind.Identifier */) { - // A.B -> typeof A !== undefined && A.B - return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); - } - // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C - var left = serializeEntityNameAsExpressionFallback(node.left); - var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right)); - } - /** - * Serializes an entity name as an expression for decorator type metadata. - * - * @param node The entity name to serialize. - */ - function serializeEntityNameAsExpression(node) { - switch (node.kind) { - case 79 /* SyntaxKind.Identifier */: - // Create a clone of the name with a new parent, and treat it as if it were - // a source tree node for the purposes of the checker. - var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); - name.original = undefined; - ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. - return name; - case 161 /* SyntaxKind.QualifiedName */: - return serializeQualifiedNameAsExpression(node); - } - } - /** - * Serializes an qualified name as an expression for decorator type metadata. - * - * @param node The qualified name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * qualified name at runtime. - */ - function serializeQualifiedNameAsExpression(node) { - return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); - } - /** - * Gets an expression that points to the global "Symbol" constructor at runtime if it is - * available. - */ - function getGlobalSymbolNameWithFallback() { - return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("Symbol"), - /*colonToken*/ undefined, factory.createIdentifier("Object")); - } - /** - * Gets an expression that points to the global "BigInt" constructor at runtime if it is - * available. - */ - function getGlobalBigIntNameWithFallback() { - return languageVersion < 99 /* ScriptTarget.ESNext */ - ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), - /*questionToken*/ undefined, factory.createIdentifier("BigInt"), - /*colonToken*/ undefined, factory.createIdentifier("Object")) - : factory.createIdentifier("BigInt"); - } - /** - * Gets an expression that represents a property name (for decorated properties or enums). - * For a computed property, a name is generated for the node. - * - * @param member The member whose name should be converted into an expression. - */ - function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { - var name = member.name; - if (ts.isPrivateIdentifier(name)) { - return factory.createIdentifier(""); - } - else if (ts.isComputedPropertyName(name)) { - return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression) - ? factory.getGeneratedNameForNode(name) - : name.expression; - } - else if (ts.isIdentifier(name)) { - return factory.createStringLiteral(ts.idText(name)); - } - else { - return factory.cloneNode(name); - } - } - /** - * Visits the property name of a class element, for use when emitting property - * initializers. For a computed property on a node with decorators, a temporary - * value is stored for later use. - * - * @param member The member whose name should be visited. - */ - function visitPropertyNameOfClassElement(member) { - var name = member.name; - // Computed property names need to be transformed into a hoisted variable when they are used more than once. - // The names are used more than once when: - // - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments). - // - the property has a decorator. - if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) { - var expression = ts.visitNode(name.expression, visitor, ts.isExpression); - var innerExpression = ts.skipPartiallyEmittedExpressions(expression); - if (!ts.isSimpleInlineableExpression(innerExpression)) { - var generatedName = factory.getGeneratedNameForNode(name); - hoistVariableDeclaration(generatedName); - return factory.updateComputedPropertyName(name, factory.createAssignment(generatedName, expression)); - } - } - return ts.visitNode(name, visitor, ts.isPropertyName); - } - /** - * Transforms a HeritageClause with TypeScript syntax. - * - * This function will only be called when one of the following conditions are met: - * - The node is a non-`extends` heritage clause that should be elided. - * - The node is an `extends` heritage clause that should be visited, but only allow a single type. - * - * @param node The HeritageClause to transform. - */ - function visitHeritageClause(node) { - if (node.token === 117 /* SyntaxKind.ImplementsKeyword */) { - // implements clauses are elided - return undefined; - } - return ts.visitEachChild(node, visitor, context); - } - /** - * Transforms an ExpressionWithTypeArguments with TypeScript syntax. + * Transforms an ExpressionWithTypeArguments with TypeScript syntax. * * This function will only be called when one of the following conditions are met: * - The node contains type arguments that should be elided. @@ -92890,28 +93552,29 @@ var ts; function shouldEmitFunctionLikeDeclaration(node) { return !ts.nodeIsMissing(node.body); } - function visitPropertyDeclaration(node) { - if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)) { + function visitPropertyDeclaration(node, parent) { + var isAmbient = node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */); + if (isAmbient && !ts.hasDecorators(node)) { return undefined; } - var updated = factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), + var allDecorators = ts.getAllDecoratorsOfClassElement(node, parent); + var decorators = transformAllDecoratorsOfDeclaration(node, parent, allDecorators); + // Preserve a `declare x` property with decorators to be handled by the decorators transform + if (isAmbient) { + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, factory.createModifiersFromModifierFlags(2 /* ModifierFlags.Ambient */)), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + return factory.updatePropertyDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } return factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node)); } function transformConstructorBody(body, constructor) { @@ -92950,7 +93613,8 @@ var ts; statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, prologueStatementCount), true), parameterPropertyAssignments, true), statements.slice(prologueStatementCount), true); } // Add remaining statements from the body, skipping the super() call if it was found and any (already added) prologue statements - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, superStatementIndex + 1 + prologueStatementCount)); + var start = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount; + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, start)); // End the lexical environment. statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true); @@ -92976,22 +93640,19 @@ var ts; ts.setEmitFlags(localName, 1536 /* EmitFlags.NoComments */); return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(factory.createExpressionStatement(factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1)))); } - function visitMethodDeclaration(node) { + function visitMethodDeclaration(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; } - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), + var allDecorators = ts.isClassLike(parent) ? ts.getAllDecoratorsOfClassElement(node, parent) : undefined; + var decorators = ts.isClassLike(parent) ? transformAllDecoratorsOfDeclaration(node, parent, allDecorators) : undefined; + return factory.updateMethodDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), node.asteriskToken, visitPropertyNameOfClassElement(node), /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } /** * Determines whether to emit an accessor declaration. We should not emit the @@ -93002,41 +93663,36 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* ModifierFlags.Abstract */)); } - function visitGetAccessor(node) { + function visitGetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateGetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; } - function visitSetAccessor(node) { + function visitSetAccessor(node, parent) { + if (!(node.transformFlags & 1 /* TransformFlags.ContainsTypeScript */)) { + return node; + } if (!shouldEmitAccessorDeclaration(node)) { return undefined; } - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); - if (updated !== node) { - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setCommentRange(updated, node); - ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node)); - } - return updated; + var decorators = ts.isClassLike(parent) ? + transformAllDecoratorsOfDeclaration(node, parent, ts.getAllDecoratorsOfClassElement(node, parent)) : + undefined; + return factory.updateSetAccessorDeclaration(node, ts.concatenate(decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike)), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return factory.createNotEmittedStatement(node); } - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, + var updated = factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([])); if (isExportOfNamespace(node)) { @@ -93065,9 +93721,8 @@ var ts; if (ts.parameterIsThisKeyword(node)) { return undefined; } - var updated = factory.updateParameterDeclaration(node, - /*decorators*/ undefined, - /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), // preserve positions, if available + node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); if (updated !== node) { @@ -93227,7 +93882,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); @@ -93457,7 +94112,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); @@ -93570,7 +94225,6 @@ var ts; compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* ImportsNotUsedAsValues.Error */ ? factory.updateImportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, importClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -93645,7 +94299,6 @@ var ts; var exportClause = ts.visitNode(node.exportClause, function (bindings) { return visitNamedExportBindings(bindings, allowEmpty); }, ts.isNamedExportBindings); return exportClause ? factory.updateExportDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier, node.assertClause) : undefined; } @@ -93703,7 +94356,6 @@ var ts; // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'. if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* ImportsNotUsedAsValues.Preserve */) { return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, node.moduleReference.expression, /*assertClause*/ undefined), node), node); @@ -93763,12 +94415,6 @@ var ts; return isExternalModuleExport(node) && ts.hasSyntacticModifier(node, 512 /* ModifierFlags.Default */); } - /** - * Creates a statement for the provided expression. This is used in calls to `map`. - */ - function expressionToStatement(expression) { - return factory.createExpressionStatement(expression); - } function addExportMemberAssignment(statements, node) { var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); @@ -93800,44 +94446,12 @@ var ts; function getNamespaceContainerName(node) { return factory.getGeneratedNameForNode(node); } - /** - * Gets a local alias for a class declaration if it is a decorated class with an internal - * reference to the static side of the class. This is necessary to avoid issues with - * double-binding semantics for the class name. - */ - function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { - enableSubstitutionForClassAliases(); - var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); - classAliases[ts.getOriginalNodeId(node)] = classAlias; - hoistVariableDeclaration(classAlias); - return classAlias; - } - } - function getClassPrototype(node) { - return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); - } - function getClassMemberPrefix(node, member) { - return ts.isStatic(member) - ? factory.getDeclarationName(node) - : getClassPrototype(node); - } function enableSubstitutionForNonQualifiedEnumMembers() { if ((enabledSubstitutions & 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */) === 0) { enabledSubstitutions |= 8 /* TypeScriptSubstitutionFlags.NonQualifiedEnumMembers */; context.enableSubstitution(79 /* SyntaxKind.Identifier */); } } - function enableSubstitutionForClassAliases() { - if ((enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) === 0) { - enabledSubstitutions |= 1 /* TypeScriptSubstitutionFlags.ClassAliases */; - // We need to enable substitutions for identifiers. This allows us to - // substitute class names inside of a class declaration. - context.enableSubstitution(79 /* SyntaxKind.Identifier */); - // Keep track of class aliases. - classAliases = []; - } - } function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2 /* TypeScriptSubstitutionFlags.NamespaceExports */) === 0) { enabledSubstitutions |= 2 /* TypeScriptSubstitutionFlags.NamespaceExports */; @@ -93922,32 +94536,9 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - return trySubstituteClassAlias(node) - || trySubstituteNamespaceExportedName(node) + return trySubstituteNamespaceExportedName(node) || node; } - function trySubstituteClassAlias(node) { - if (enabledSubstitutions & 1 /* TypeScriptSubstitutionFlags.ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - // Also, when emitting statics for class expressions, we must substitute a class alias for - // constructor references in static property initializers. - var declaration = resolver.getReferencedValueDeclaration(node); - if (declaration) { - var classAlias = classAliases[declaration.id]; // TODO: GH#18217 - if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; - } - } - } - } - return undefined; - } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { @@ -94085,7 +94676,7 @@ var ts; return visited; } function visitorWorker(node, valueIsDiscarded) { - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */) { + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */) { switch (node.kind) { case 226 /* SyntaxKind.ClassExpression */: case 257 /* SyntaxKind.ClassDeclaration */: @@ -94100,8 +94691,8 @@ var ts; return visitClassStaticBlockDeclaration(node); } } - if (node.transformFlags & 8388608 /* TransformFlags.ContainsClassFields */ || - node.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */ && + if (node.transformFlags & 16777216 /* TransformFlags.ContainsClassFields */ || + node.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */ && shouldTransformSuperInStaticInitializers && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { @@ -94241,7 +94832,7 @@ var ts; return node; } function visitMethodOrAccessorDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.isPrivateIdentifier(node.name)) { return ts.visitEachChild(node, classElementVisitor, context); } @@ -94253,7 +94844,7 @@ var ts; } var functionName = getHoistedFunctionName(node); if (functionName) { - getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return ts.isModifier(m) && !ts.isStaticModifier(m); }), node.asteriskToken, functionName, /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); } @@ -94277,7 +94868,7 @@ var ts; } } function visitPropertyDeclaration(node) { - ts.Debug.assert(!ts.some(node.decorators)); + ts.Debug.assert(!ts.hasDecorators(node)); if (ts.isPrivateIdentifier(node.name)) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { if (ts.isStatic(node)) { @@ -94285,8 +94876,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + return factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); @@ -94308,9 +94898,7 @@ var ts; if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); if (initializerStatement) { - var staticBlock = factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([initializerStatement])); + var staticBlock = factory.createClassStaticBlockDeclaration(factory.createBlock([initializerStatement])); ts.setOriginalNode(staticBlock, node); ts.setCommentRange(staticBlock, node); // Set the comment range for the statement to an empty synthetic range @@ -94386,10 +94974,11 @@ var ts; } function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) { if (node.operator === 45 /* SyntaxKind.PlusPlusToken */ || node.operator === 46 /* SyntaxKind.MinusMinusToken */) { - if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + var operand = ts.skipParentheses(node.operand); + if (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierPropertyAccessExpression(operand)) { var info = void 0; - if (info = accessPrivateIdentifier(node.operand.name)) { - var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression); + if (info = accessPrivateIdentifier(operand.name)) { + var receiver = ts.visitNode(operand.expression, visitor, ts.isExpression); var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; var expression = createPrivateIdentifierAccess(info, readExpression); var temp = ts.isPrefixUnaryExpression(node) || valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); @@ -94405,7 +94994,7 @@ var ts; } } else if (shouldTransformSuperInStaticInitializers && - ts.isSuperProperty(node.operand) && + ts.isSuperProperty(operand) && currentStaticPropertyDeclarationOrStaticBlock && currentClassLexicalEnvironment) { // converts `++super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = ++_a), _classTemp), _b)` @@ -94418,31 +95007,31 @@ var ts; // converts `super[f()]--` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = _b--), _classTemp), _c)` var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; if (facts & 1 /* ClassFacts.ClassWasDecorated */) { - var operand = visitInvalidSuperProperty(node.operand); + var expression = visitInvalidSuperProperty(operand); return ts.isPrefixUnaryExpression(node) ? - factory.updatePrefixUnaryExpression(node, operand) : - factory.updatePostfixUnaryExpression(node, operand); + factory.updatePrefixUnaryExpression(node, expression) : + factory.updatePostfixUnaryExpression(node, expression); } if (classConstructor && superClassReference) { var setterName = void 0; var getterName = void 0; - if (ts.isPropertyAccessExpression(node.operand)) { - if (ts.isIdentifier(node.operand.name)) { - getterName = setterName = factory.createStringLiteralFromNode(node.operand.name); + if (ts.isPropertyAccessExpression(operand)) { + if (ts.isIdentifier(operand.name)) { + getterName = setterName = factory.createStringLiteralFromNode(operand.name); } } else { - if (ts.isSimpleInlineableExpression(node.operand.argumentExpression)) { - getterName = setterName = node.operand.argumentExpression; + if (ts.isSimpleInlineableExpression(operand.argumentExpression)) { + getterName = setterName = operand.argumentExpression; } else { getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, ts.visitNode(node.operand.argumentExpression, visitor, ts.isExpression)); + setterName = factory.createAssignment(getterName, ts.visitNode(operand.argumentExpression, visitor, ts.isExpression)); } } if (setterName && getterName) { var expression = factory.createReflectGetCall(superClassReference, getterName, classConstructor); - ts.setTextRange(expression, node.operand); + ts.setTextRange(expression, operand); var temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); expression = ts.expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp); expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor); @@ -94675,13 +95264,13 @@ var ts; facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } if (ts.isPropertyDeclaration(member) || ts.isClassStaticBlockDeclaration(member)) { - if (shouldTransformThisInStaticInitializers && member.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */) { + if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */) { facts |= 8 /* ClassFacts.NeedsSubstitutionForThisInClassStaticField */; if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */; } } - if (shouldTransformSuperInStaticInitializers && member.transformFlags & 33554432 /* TransformFlags.ContainsLexicalSuper */) { + if (shouldTransformSuperInStaticInitializers && member.transformFlags & 134217728 /* TransformFlags.ContainsLexicalSuper */) { if (!(facts & 1 /* ClassFacts.ClassWasDecorated */)) { facts |= 2 /* ClassFacts.NeedsClassConstructorReference */ | 4 /* ClassFacts.NeedsClassSuperReference */; } @@ -94719,8 +95308,7 @@ var ts; var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 104 /* SyntaxKind.NullKeyword */); var statements = [ - factory.updateClassDeclaration(node, - /*decorators*/ undefined, node.modifiers, node.name, + factory.updateClassDeclaration(node, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; if (pendingClassReferenceAssignment) { @@ -94772,7 +95360,7 @@ var ts; temp = createClassTempVar(); getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); } - var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, + var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || ts.isPrivateIdentifier(p.name); }); if (hasTransformableStatics || ts.some(pendingExpressions)) { @@ -94840,9 +95428,7 @@ var ts; members.push(constructor); } if (!shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(pendingExpressions)) { - members.push(factory.createClassStaticBlockDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, factory.createBlock([ + members.push(factory.createClassStaticBlockDeclaration(factory.createBlock([ factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)) ]))); pendingExpressions = undefined; @@ -94879,7 +95465,6 @@ var ts; return undefined; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { @@ -95103,16 +95688,1449 @@ var ts; return factory.createAssignment(memberAccess, initializer); } else { - var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression - : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) - : propertyName; - var descriptor = factory.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true }); - return factory.createObjectDefinePropertyCall(receiver, name, descriptor); + var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression + : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) + : propertyName; + var descriptor = factory.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true }); + return factory.createObjectDefinePropertyCall(receiver, name, descriptor); + } + } + function enableSubstitutionForClassAliases() { + if ((enabledSubstitutions & 1 /* ClassPropertySubstitutionFlags.ClassAliases */) === 0) { + enabledSubstitutions |= 1 /* ClassPropertySubstitutionFlags.ClassAliases */; + // We need to enable substitutions for identifiers. This allows us to + // substitute class names inside of a class declaration. + context.enableSubstitution(79 /* SyntaxKind.Identifier */); + // Keep track of class aliases. + classAliases = []; + } + } + function enableSubstitutionForClassStaticThisOrSuperReference() { + if ((enabledSubstitutions & 2 /* ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference */) === 0) { + enabledSubstitutions |= 2 /* ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference */; + // substitute `this` in a static field initializer + context.enableSubstitution(108 /* SyntaxKind.ThisKeyword */); + // these push a new lexical environment that is not the class lexical environment + context.enableEmitNotification(256 /* SyntaxKind.FunctionDeclaration */); + context.enableEmitNotification(213 /* SyntaxKind.FunctionExpression */); + context.enableEmitNotification(171 /* SyntaxKind.Constructor */); + // these push a new lexical environment that is not the class lexical environment, except + // when they have a computed property name + context.enableEmitNotification(172 /* SyntaxKind.GetAccessor */); + context.enableEmitNotification(173 /* SyntaxKind.SetAccessor */); + context.enableEmitNotification(169 /* SyntaxKind.MethodDeclaration */); + context.enableEmitNotification(167 /* SyntaxKind.PropertyDeclaration */); + // class lexical environments are restored when entering a computed property name + context.enableEmitNotification(162 /* SyntaxKind.ComputedPropertyName */); + } + } + /** + * Generates brand-check initializer for private methods. + * + * @param statements Statement list that should be used to append new statements. + * @param methods An array of method declarations. + * @param receiver The receiver on which each method should be assigned. + */ + function addMethodStatements(statements, methods, receiver) { + if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.some(methods)) { + return; + } + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + statements.push(factory.createExpressionStatement(createPrivateInstanceMethodInitializer(receiver, weakSetName))); + } + function visitInvalidSuperProperty(node) { + return ts.isPropertyAccessExpression(node) ? + factory.updatePropertyAccessExpression(node, factory.createVoidZero(), node.name) : + factory.updateElementAccessExpression(node, factory.createVoidZero(), ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); + } + function onEmitNode(hint, node, emitCallback) { + var original = ts.getOriginalNode(node); + if (original.id) { + var classLexicalEnvironment = classLexicalEnvironmentMap.get(original.id); + if (classLexicalEnvironment) { + var savedClassLexicalEnvironment = currentClassLexicalEnvironment; + var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; + currentClassLexicalEnvironment = classLexicalEnvironment; + currentComputedPropertyNameClassLexicalEnvironment = classLexicalEnvironment; + previousOnEmitNode(hint, node, emitCallback); + currentClassLexicalEnvironment = savedClassLexicalEnvironment; + currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment; + return; + } + } + switch (node.kind) { + case 213 /* SyntaxKind.FunctionExpression */: + if (ts.isArrowFunction(original) || ts.getEmitFlags(node) & 262144 /* EmitFlags.AsyncFunctionBody */) { + break; + } + // falls through + case 256 /* SyntaxKind.FunctionDeclaration */: + case 171 /* SyntaxKind.Constructor */: { + var savedClassLexicalEnvironment = currentClassLexicalEnvironment; + var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; + currentClassLexicalEnvironment = undefined; + currentComputedPropertyNameClassLexicalEnvironment = undefined; + previousOnEmitNode(hint, node, emitCallback); + currentClassLexicalEnvironment = savedClassLexicalEnvironment; + currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment; + return; + } + case 172 /* SyntaxKind.GetAccessor */: + case 173 /* SyntaxKind.SetAccessor */: + case 169 /* SyntaxKind.MethodDeclaration */: + case 167 /* SyntaxKind.PropertyDeclaration */: { + var savedClassLexicalEnvironment = currentClassLexicalEnvironment; + var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; + currentComputedPropertyNameClassLexicalEnvironment = currentClassLexicalEnvironment; + currentClassLexicalEnvironment = undefined; + previousOnEmitNode(hint, node, emitCallback); + currentClassLexicalEnvironment = savedClassLexicalEnvironment; + currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment; + return; + } + case 162 /* SyntaxKind.ComputedPropertyName */: { + var savedClassLexicalEnvironment = currentClassLexicalEnvironment; + var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; + currentClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; + currentComputedPropertyNameClassLexicalEnvironment = undefined; + previousOnEmitNode(hint, node, emitCallback); + currentClassLexicalEnvironment = savedClassLexicalEnvironment; + currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment; + return; + } + } + previousOnEmitNode(hint, node, emitCallback); + } + /** + * Hooks node substitutions. + * + * @param hint The context for the emitter. + * @param node The node to substitute. + */ + function onSubstituteNode(hint, node) { + node = previousOnSubstituteNode(hint, node); + if (hint === 1 /* EmitHint.Expression */) { + return substituteExpression(node); + } + return node; + } + function substituteExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + return substituteExpressionIdentifier(node); + case 108 /* SyntaxKind.ThisKeyword */: + return substituteThisExpression(node); + } + return node; + } + function substituteThisExpression(node) { + if (enabledSubstitutions & 2 /* ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference */ && currentClassLexicalEnvironment) { + var facts = currentClassLexicalEnvironment.facts, classConstructor = currentClassLexicalEnvironment.classConstructor; + if (facts & 1 /* ClassFacts.ClassWasDecorated */) { + return factory.createParenthesizedExpression(factory.createVoidZero()); + } + if (classConstructor) { + return ts.setTextRange(ts.setOriginalNode(factory.cloneNode(classConstructor), node), node); + } + } + return node; + } + function substituteExpressionIdentifier(node) { + return trySubstituteClassAlias(node) || node; + } + function trySubstituteClassAlias(node) { + if (enabledSubstitutions & 1 /* ClassPropertySubstitutionFlags.ClassAliases */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + // Also, when emitting statics for class expressions, we must substitute a class alias for + // constructor references in static property initializers. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 + if (classAlias) { + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; + } + } + } + } + return undefined; + } + /** + * If the name is a computed property, this function transforms it, then either returns an expression which caches the + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + */ + function getPropertyNameExpressionIfNeeded(name, shouldHoist) { + if (ts.isComputedPropertyName(name)) { + var expression = ts.visitNode(name.expression, visitor, ts.isExpression); + var innerExpression = ts.skipPartiallyEmittedExpressions(expression); + var inlinable = ts.isSimpleInlineableExpression(innerExpression); + var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left); + if (!alreadyTransformed && !inlinable && shouldHoist) { + var generatedName = factory.getGeneratedNameForNode(name); + if (resolver.getNodeCheckFlags(name) & 524288 /* NodeCheckFlags.BlockScopedBindingInLoop */) { + addBlockScopedVariable(generatedName); + } + else { + hoistVariableDeclaration(generatedName); + } + return factory.createAssignment(generatedName, expression); + } + return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression; + } + } + function startClassLexicalEnvironment() { + classLexicalEnvironmentStack.push(currentClassLexicalEnvironment); + currentClassLexicalEnvironment = undefined; + } + function endClassLexicalEnvironment() { + currentClassLexicalEnvironment = classLexicalEnvironmentStack.pop(); + } + function getClassLexicalEnvironment() { + return currentClassLexicalEnvironment || (currentClassLexicalEnvironment = { + facts: 0 /* ClassFacts.None */, + classConstructor: undefined, + superClassReference: undefined, + privateIdentifierEnvironment: undefined, + }); + } + function getPrivateIdentifierEnvironment() { + var lex = getClassLexicalEnvironment(); + lex.privateIdentifierEnvironment || (lex.privateIdentifierEnvironment = { + className: "", + identifiers: new ts.Map() + }); + return lex.privateIdentifierEnvironment; + } + function getPendingExpressions() { + return pendingExpressions || (pendingExpressions = []); + } + function addPrivateIdentifierToEnvironment(node) { + var _a; + var text = ts.getTextOfPropertyName(node.name); + var lex = getClassLexicalEnvironment(); + var classConstructor = lex.classConstructor; + var privateEnv = getPrivateIdentifierEnvironment(); + var weakSetName = privateEnv.weakSetName; + var assignmentExpressions = []; + var privateName = node.name.escapedText; + var previousInfo = privateEnv.identifiers.get(privateName); + var isValid = !isReservedPrivateName(node.name) && previousInfo === undefined; + if (ts.hasStaticModifier(node)) { + ts.Debug.assert(classConstructor, "weakSetName should be set in private identifier environment"); + if (ts.isPropertyDeclaration(node)) { + var variableName = createHoistedVariableForPrivateName(text, node); + privateEnv.identifiers.set(privateName, { + kind: "f" /* PrivateIdentifierKind.Field */, + variableName: variableName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isMethodDeclaration(node)) { + var functionName = createHoistedVariableForPrivateName(text, node); + privateEnv.identifiers.set(privateName, { + kind: "m" /* PrivateIdentifierKind.Method */, + methodName: functionName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isGetAccessorDeclaration(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + privateEnv.identifiers.set(privateName, { + kind: "a" /* PrivateIdentifierKind.Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else if (ts.isSetAccessorDeclaration(node)) { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + privateEnv.identifiers.set(privateName, { + kind: "a" /* PrivateIdentifierKind.Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + } + else if (ts.isPropertyDeclaration(node)) { + var weakMapName = createHoistedVariableForPrivateName(text, node); + privateEnv.identifiers.set(privateName, { + kind: "f" /* PrivateIdentifierKind.Field */, + brandCheckIdentifier: weakMapName, + isStatic: false, + variableName: undefined, + isValid: isValid, + }); + assignmentExpressions.push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), + /*typeArguments*/ undefined, []))); + } + else if (ts.isMethodDeclaration(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + privateEnv.identifiers.set(privateName, { + kind: "m" /* PrivateIdentifierKind.Method */, + methodName: createHoistedVariableForPrivateName(text, node), + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + else if (ts.isAccessor(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + if (ts.isGetAccessor(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && !previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + privateEnv.identifiers.set(privateName, { + kind: "a" /* PrivateIdentifierKind.Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + else { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && !previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + privateEnv.identifiers.set(privateName, { + kind: "a" /* PrivateIdentifierKind.Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + (_a = getPendingExpressions()).push.apply(_a, assignmentExpressions); + } + function createHoistedVariableForClass(name, node) { + var className = getPrivateIdentifierEnvironment().className; + var prefix = className ? "_".concat(className) : ""; + var identifier = factory.createUniqueName("".concat(prefix, "_").concat(name), 16 /* GeneratedIdentifierFlags.Optimistic */); + if (resolver.getNodeCheckFlags(node) & 524288 /* NodeCheckFlags.BlockScopedBindingInLoop */) { + addBlockScopedVariable(identifier); + } + else { + hoistVariableDeclaration(identifier); + } + return identifier; + } + function createHoistedVariableForPrivateName(privateName, node) { + return createHoistedVariableForClass(privateName.substring(1), node.name); + } + function accessPrivateIdentifier(name) { + var _a; + if (currentClassLexicalEnvironment === null || currentClassLexicalEnvironment === void 0 ? void 0 : currentClassLexicalEnvironment.privateIdentifierEnvironment) { + var info = currentClassLexicalEnvironment.privateIdentifierEnvironment.identifiers.get(name.escapedText); + if (info) { + return info; + } + } + for (var i = classLexicalEnvironmentStack.length - 1; i >= 0; --i) { + var env = classLexicalEnvironmentStack[i]; + if (!env) { + continue; + } + var info = (_a = env.privateIdentifierEnvironment) === null || _a === void 0 ? void 0 : _a.identifiers.get(name.escapedText); + if (info) { + return info; + } + } + return undefined; + } + function wrapPrivateIdentifierForDestructuringTarget(node) { + var parameter = factory.getGeneratedNameForNode(node); + var info = accessPrivateIdentifier(node.name); + if (!info) { + return ts.visitEachChild(node, visitor, context); + } + var receiver = node.expression; + // We cannot copy `this` or `super` into the function because they will be bound + // differently inside the function. + if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) { + receiver = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true); + getPendingExpressions().push(factory.createBinaryExpression(receiver, 63 /* SyntaxKind.EqualsToken */, ts.visitNode(node.expression, visitor, ts.isExpression))); + } + return factory.createAssignmentTargetWrapper(parameter, createPrivateIdentifierAssignment(info, receiver, parameter, 63 /* SyntaxKind.EqualsToken */)); + } + function visitArrayAssignmentTarget(node) { + var target = ts.getTargetOfBindingOrAssignmentElement(node); + if (target) { + var wrapped = void 0; + if (ts.isPrivateIdentifierPropertyAccessExpression(target)) { + wrapped = wrapPrivateIdentifierForDestructuringTarget(target); + } + else if (shouldTransformSuperInStaticInitializers && + ts.isSuperProperty(target) && + currentStaticPropertyDeclarationOrStaticBlock && + currentClassLexicalEnvironment) { + var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; + if (facts & 1 /* ClassFacts.ClassWasDecorated */) { + wrapped = visitInvalidSuperProperty(target); + } + else if (classConstructor && superClassReference) { + var name = ts.isElementAccessExpression(target) ? ts.visitNode(target.argumentExpression, visitor, ts.isExpression) : + ts.isIdentifier(target.name) ? factory.createStringLiteralFromNode(target.name) : + undefined; + if (name) { + var temp = factory.createTempVariable(/*recordTempVariable*/ undefined); + wrapped = factory.createAssignmentTargetWrapper(temp, factory.createReflectSetCall(superClassReference, name, temp, classConstructor)); + } + } + } + if (wrapped) { + if (ts.isAssignmentExpression(node)) { + return factory.updateBinaryExpression(node, wrapped, node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression)); + } + else if (ts.isSpreadElement(node)) { + return factory.updateSpreadElement(node, wrapped); + } + else { + return wrapped; + } + } + } + return ts.visitNode(node, visitorDestructuringTarget); + } + function visitObjectAssignmentTarget(node) { + if (ts.isObjectBindingOrAssignmentElement(node) && !ts.isShorthandPropertyAssignment(node)) { + var target = ts.getTargetOfBindingOrAssignmentElement(node); + var wrapped = void 0; + if (target) { + if (ts.isPrivateIdentifierPropertyAccessExpression(target)) { + wrapped = wrapPrivateIdentifierForDestructuringTarget(target); + } + else if (shouldTransformSuperInStaticInitializers && + ts.isSuperProperty(target) && + currentStaticPropertyDeclarationOrStaticBlock && + currentClassLexicalEnvironment) { + var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; + if (facts & 1 /* ClassFacts.ClassWasDecorated */) { + wrapped = visitInvalidSuperProperty(target); + } + else if (classConstructor && superClassReference) { + var name = ts.isElementAccessExpression(target) ? ts.visitNode(target.argumentExpression, visitor, ts.isExpression) : + ts.isIdentifier(target.name) ? factory.createStringLiteralFromNode(target.name) : + undefined; + if (name) { + var temp = factory.createTempVariable(/*recordTempVariable*/ undefined); + wrapped = factory.createAssignmentTargetWrapper(temp, factory.createReflectSetCall(superClassReference, name, temp, classConstructor)); + } + } + } + } + if (ts.isPropertyAssignment(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor, ts.isPropertyName), wrapped ? + initializer ? factory.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped : + ts.visitNode(node.initializer, visitorDestructuringTarget, ts.isExpression)); + } + if (ts.isSpreadAssignment(node)) { + return factory.updateSpreadAssignment(node, wrapped || ts.visitNode(node.expression, visitorDestructuringTarget, ts.isExpression)); + } + ts.Debug.assert(wrapped === undefined, "Should not have generated a wrapped target"); + } + return ts.visitNode(node, visitor); + } + function visitAssignmentPattern(node) { + if (ts.isArrayLiteralExpression(node)) { + // Transforms private names in destructuring assignment array bindings. + // Transforms SuperProperty assignments in destructuring assignment array bindings in static initializers. + // + // Source: + // ([ this.#myProp ] = [ "hello" ]); + // + // Transformation: + // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ]; + return factory.updateArrayLiteralExpression(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression)); + } + else { + // Transforms private names in destructuring assignment object bindings. + // Transforms SuperProperty assignments in destructuring assignment object bindings in static initializers. + // + // Source: + // ({ stringProperty: this.#myProp } = { stringProperty: "hello" }); + // + // Transformation: + // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" }; + return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike)); + } + } + } + ts.transformClassFields = transformClassFields; + function createPrivateStaticFieldInitializer(variableName, initializer) { + return ts.factory.createAssignment(variableName, ts.factory.createObjectLiteralExpression([ + ts.factory.createPropertyAssignment("value", initializer || ts.factory.createVoidZero()) + ])); + } + function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) { + return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), + /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]); + } + function createPrivateInstanceMethodInitializer(receiver, weakSetName) { + return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakSetName, "add"), + /*typeArguments*/ undefined, [receiver]); + } + function isReservedPrivateName(node) { + return node.escapedText === "#constructor"; + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function createRuntimeTypeSerializer(context) { + var hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); + var currentLexicalScope; + var currentNameScope; + return { + serializeTypeNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeNode, node); }, + serializeTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeTypeOfNode, node); }, + serializeParameterTypesOfNode: function (serializerContext, node, container) { return setSerializerContextAnd(serializerContext, serializeParameterTypesOfNode, node, container); }, + serializeReturnTypeOfNode: function (serializerContext, node) { return setSerializerContextAnd(serializerContext, serializeReturnTypeOfNode, node); }, + }; + function setSerializerContextAnd(serializerContext, cb, node, arg) { + var savedCurrentLexicalScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; + currentLexicalScope = serializerContext.currentLexicalScope; + currentNameScope = serializerContext.currentNameScope; + var result = arg === undefined ? cb(node) : cb(node, arg); + currentLexicalScope = savedCurrentLexicalScope; + currentNameScope = savedCurrentNameScope; + return result; + } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeTypeOfNode(node) { + switch (node.kind) { + case 167 /* SyntaxKind.PropertyDeclaration */: + case 164 /* SyntaxKind.Parameter */: + return serializeTypeNode(node.type); + case 173 /* SyntaxKind.SetAccessor */: + case 172 /* SyntaxKind.GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 257 /* SyntaxKind.ClassDeclaration */: + case 226 /* SyntaxKind.ClassExpression */: + case 169 /* SyntaxKind.MethodDeclaration */: + return ts.factory.createIdentifier("Function"); + default: + return ts.factory.createVoidZero(); + } + } + /** + * Serializes the type of a node for use with decorator type metadata. + * @param node The node that should have its type serialized. + */ + function serializeParameterTypesOfNode(node, container) { + var valueDeclaration = ts.isClassLike(node) + ? ts.getFirstConstructorWithBody(node) + : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) + ? node + : undefined; + var expressions = []; + if (valueDeclaration) { + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); + var numParameters = parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i]; + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { + continue; + } + if (parameter.dotDotDotToken) { + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); + } + else { + expressions.push(serializeTypeOfNode(parameter)); + } + } + } + return ts.factory.createArrayLiteralExpression(expressions); + } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 172 /* SyntaxKind.GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } + /** + * Serializes the return type of a node for use with decorator type metadata. + * @param node The node that should have its return type serialized. + */ + function serializeReturnTypeOfNode(node) { + if (ts.isFunctionLike(node) && node.type) { + return serializeTypeNode(node.type); + } + else if (ts.isAsyncFunction(node)) { + return ts.factory.createIdentifier("Promise"); + } + return ts.factory.createVoidZero(); + } + /** + * Serializes a type node for use with decorator type metadata. + * + * Types are serialized in the following fashion: + * - Void types point to "undefined" (e.g. "void 0") + * - Function and Constructor types point to the global "Function" constructor. + * - Interface types with a call or construct signature types point to the global + * "Function" constructor. + * - Array and Tuple types point to the global "Array" constructor. + * - Type predicates and booleans point to the global "Boolean" constructor. + * - String literal types and strings point to the global "String" constructor. + * - Enum and number types point to the global "Number" constructor. + * - Symbol types point to the global "Symbol" constructor. + * - Type references to classes (or class-like variables) point to the constructor for the class. + * - Anything else points to the global "Object" constructor. + * + * @param node The type node to serialize. + */ + function serializeTypeNode(node) { + if (node === undefined) { + return ts.factory.createIdentifier("Object"); + } + node = ts.skipTypeParentheses(node); + switch (node.kind) { + case 114 /* SyntaxKind.VoidKeyword */: + case 153 /* SyntaxKind.UndefinedKeyword */: + case 143 /* SyntaxKind.NeverKeyword */: + return ts.factory.createVoidZero(); + case 179 /* SyntaxKind.FunctionType */: + case 180 /* SyntaxKind.ConstructorType */: + return ts.factory.createIdentifier("Function"); + case 183 /* SyntaxKind.ArrayType */: + case 184 /* SyntaxKind.TupleType */: + return ts.factory.createIdentifier("Array"); + case 177 /* SyntaxKind.TypePredicate */: + return node.assertsModifier ? + ts.factory.createVoidZero() : + ts.factory.createIdentifier("Boolean"); + case 133 /* SyntaxKind.BooleanKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 198 /* SyntaxKind.TemplateLiteralType */: + case 150 /* SyntaxKind.StringKeyword */: + return ts.factory.createIdentifier("String"); + case 148 /* SyntaxKind.ObjectKeyword */: + return ts.factory.createIdentifier("Object"); + case 196 /* SyntaxKind.LiteralType */: + return serializeLiteralOfLiteralTypeNode(node.literal); + case 147 /* SyntaxKind.NumberKeyword */: + return ts.factory.createIdentifier("Number"); + case 158 /* SyntaxKind.BigIntKeyword */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 151 /* SyntaxKind.SymbolKeyword */: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case 178 /* SyntaxKind.TypeReference */: + return serializeTypeReferenceNode(node); + case 188 /* SyntaxKind.IntersectionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ true); + case 187 /* SyntaxKind.UnionType */: + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ false); + case 189 /* SyntaxKind.ConditionalType */: + return serializeUnionOrIntersectionConstituents([node.trueType, node.falseType], /*isIntersection*/ false); + case 193 /* SyntaxKind.TypeOperator */: + if (node.operator === 145 /* SyntaxKind.ReadonlyKeyword */) { + return serializeTypeNode(node.type); + } + break; + case 181 /* SyntaxKind.TypeQuery */: + case 194 /* SyntaxKind.IndexedAccessType */: + case 195 /* SyntaxKind.MappedType */: + case 182 /* SyntaxKind.TypeLiteral */: + case 130 /* SyntaxKind.AnyKeyword */: + case 155 /* SyntaxKind.UnknownKeyword */: + case 192 /* SyntaxKind.ThisType */: + case 200 /* SyntaxKind.ImportType */: + break; + // handle JSDoc types from an invalid parse + case 312 /* SyntaxKind.JSDocAllType */: + case 313 /* SyntaxKind.JSDocUnknownType */: + case 317 /* SyntaxKind.JSDocFunctionType */: + case 318 /* SyntaxKind.JSDocVariadicType */: + case 319 /* SyntaxKind.JSDocNamepathType */: + break; + case 314 /* SyntaxKind.JSDocNullableType */: + case 315 /* SyntaxKind.JSDocNonNullableType */: + case 316 /* SyntaxKind.JSDocOptionalType */: + return serializeTypeNode(node.type); + default: + return ts.Debug.failBadSyntaxKind(node); + } + return ts.factory.createIdentifier("Object"); + } + function serializeLiteralOfLiteralTypeNode(node) { + switch (node.kind) { + case 10 /* SyntaxKind.StringLiteral */: + case 14 /* SyntaxKind.NoSubstitutionTemplateLiteral */: + return ts.factory.createIdentifier("String"); + case 219 /* SyntaxKind.PrefixUnaryExpression */: { + var operand = node.operand; + switch (operand.kind) { + case 8 /* SyntaxKind.NumericLiteral */: + case 9 /* SyntaxKind.BigIntLiteral */: + return serializeLiteralOfLiteralTypeNode(operand); + default: + return ts.Debug.failBadSyntaxKind(operand); + } + } + case 8 /* SyntaxKind.NumericLiteral */: + return ts.factory.createIdentifier("Number"); + case 9 /* SyntaxKind.BigIntLiteral */: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case 110 /* SyntaxKind.TrueKeyword */: + case 95 /* SyntaxKind.FalseKeyword */: + return ts.factory.createIdentifier("Boolean"); + case 104 /* SyntaxKind.NullKeyword */: + return ts.factory.createVoidZero(); + default: + return ts.Debug.failBadSyntaxKind(node); + } + } + function serializeUnionOrIntersectionConstituents(types, isIntersection) { + // Note when updating logic here also update `getEntityNameForDecoratorMetadata` in checker.ts so that aliases can be marked as referenced + var serializedType; + for (var _i = 0, types_22 = types; _i < types_22.length; _i++) { + var typeNode = types_22[_i]; + typeNode = ts.skipTypeParentheses(typeNode); + if (typeNode.kind === 143 /* SyntaxKind.NeverKeyword */) { + if (isIntersection) + return ts.factory.createVoidZero(); // Reduce to `never` in an intersection + continue; // Elide `never` in a union + } + if (typeNode.kind === 155 /* SyntaxKind.UnknownKeyword */) { + if (!isIntersection) + return ts.factory.createIdentifier("Object"); // Reduce to `unknown` in a union + continue; // Elide `unknown` in an intersection + } + if (typeNode.kind === 130 /* SyntaxKind.AnyKeyword */) { + return ts.factory.createIdentifier("Object"); // Reduce to `any` in a union or intersection + } + if (!strictNullChecks && ((ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === 104 /* SyntaxKind.NullKeyword */) || typeNode.kind === 153 /* SyntaxKind.UndefinedKeyword */)) { + continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks + } + var serializedConstituent = serializeTypeNode(typeNode); + if (ts.isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") { + // One of the individual is global object, return immediately + return serializedConstituent; + } + // If there exists union that is not `void 0` expression, check if the the common type is identifier. + // anything more complex and we will just default to Object + if (serializedType) { + // Different types + if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) { + return ts.factory.createIdentifier("Object"); + } + } + else { + // Initialize the union type + serializedType = serializedConstituent; + } + } + // If we were able to find common type, use it + return serializedType !== null && serializedType !== void 0 ? serializedType : (ts.factory.createVoidZero()); // Fallback is only hit if all union constituents are null/undefined/never + } + function equateSerializedTypeNodes(left, right) { + return ( + // temp vars used in fallback + ts.isGeneratedIdentifier(left) ? ts.isGeneratedIdentifier(right) : + // entity names + ts.isIdentifier(left) ? ts.isIdentifier(right) + && left.escapedText === right.escapedText : + ts.isPropertyAccessExpression(left) ? ts.isPropertyAccessExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) + && equateSerializedTypeNodes(left.name, right.name) : + // `void 0` + ts.isVoidExpression(left) ? ts.isVoidExpression(right) + && ts.isNumericLiteral(left.expression) && left.expression.text === "0" + && ts.isNumericLiteral(right.expression) && right.expression.text === "0" : + // `"undefined"` or `"function"` in `typeof` checks + ts.isStringLiteral(left) ? ts.isStringLiteral(right) + && left.text === right.text : + // used in `typeof` checks for fallback + ts.isTypeOfExpression(left) ? ts.isTypeOfExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // parens in `typeof` checks with temps + ts.isParenthesizedExpression(left) ? ts.isParenthesizedExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // conditionals used in fallback + ts.isConditionalExpression(left) ? ts.isConditionalExpression(right) + && equateSerializedTypeNodes(left.condition, right.condition) + && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) + && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : + // logical binary and assignments used in fallback + ts.isBinaryExpression(left) ? ts.isBinaryExpression(right) + && left.operatorToken.kind === right.operatorToken.kind + && equateSerializedTypeNodes(left.left, right.left) + && equateSerializedTypeNodes(left.right, right.right) : + false); + } + /** + * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with decorator type metadata. + * @param node The type reference node. + */ + function serializeTypeReferenceNode(node) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope !== null && currentNameScope !== void 0 ? currentNameScope : currentLexicalScope); + switch (kind) { + case ts.TypeReferenceSerializationKind.Unknown: + // From conditional type type reference that cannot be resolved is Similar to any or unknown + if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) { + return ts.factory.createIdentifier("Object"); + } + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createAssignment(temp, serialized), "function"), + /*questionToken*/ undefined, temp, + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + return serializeEntityNameAsExpression(node.typeName); + case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: + return ts.factory.createVoidZero(); + case ts.TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalConstructor("BigInt", 7 /* ScriptTarget.ES2020 */); + case ts.TypeReferenceSerializationKind.BooleanType: + return ts.factory.createIdentifier("Boolean"); + case ts.TypeReferenceSerializationKind.NumberLikeType: + return ts.factory.createIdentifier("Number"); + case ts.TypeReferenceSerializationKind.StringLikeType: + return ts.factory.createIdentifier("String"); + case ts.TypeReferenceSerializationKind.ArrayLikeType: + return ts.factory.createIdentifier("Array"); + case ts.TypeReferenceSerializationKind.ESSymbolType: + return getGlobalConstructor("Symbol", 2 /* ScriptTarget.ES2015 */); + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + return ts.factory.createIdentifier("Function"); + case ts.TypeReferenceSerializationKind.Promise: + return ts.factory.createIdentifier("Promise"); + case ts.TypeReferenceSerializationKind.ObjectType: + return ts.factory.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); + } + } + /** + * Produces an expression that results in `right` if `left` is not undefined at runtime: + * + * ``` + * typeof left !== "undefined" && right + * ``` + * + * We use `typeof L !== "undefined"` (rather than `L !== undefined`) since `L` may not be declared. + * It's acceptable for this expression to result in `false` at runtime, as the result is intended to be + * further checked by any containing expression. + */ + function createCheckedValue(left, right) { + return ts.factory.createLogicalAnd(ts.factory.createStrictInequality(ts.factory.createTypeOfExpression(left), ts.factory.createStringLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 79 /* SyntaxKind.Identifier */) { + // A -> typeof A !== "undefined" && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 79 /* SyntaxKind.Identifier */) { + // A.B -> typeof A !== "undefined" && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== "undefined" && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.factory.createTempVariable(hoistVariableDeclaration); + return ts.factory.createLogicalAnd(ts.factory.createLogicalAnd(left.left, ts.factory.createStrictInequality(ts.factory.createAssignment(temp, left.right), ts.factory.createVoidZero())), ts.factory.createPropertyAccessExpression(temp, node.right)); + } + /** + * Serializes an entity name as an expression for decorator type metadata. + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpression(node) { + switch (node.kind) { + case 79 /* SyntaxKind.Identifier */: + // Create a clone of the name with a new parent, and treat it as if it were + // a source tree node for the purposes of the checker. + var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent); + name.original = undefined; + ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. + return name; + case 161 /* SyntaxKind.QualifiedName */: + return serializeQualifiedNameAsExpression(node); + } + } + /** + * Serializes an qualified name as an expression for decorator type metadata. + * @param node The qualified name to serialize. + */ + function serializeQualifiedNameAsExpression(node) { + return ts.factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); + } + function getGlobalConstructorWithFallback(name) { + return ts.factory.createConditionalExpression(ts.factory.createTypeCheck(ts.factory.createIdentifier(name), "function"), + /*questionToken*/ undefined, ts.factory.createIdentifier(name), + /*colonToken*/ undefined, ts.factory.createIdentifier("Object")); + } + function getGlobalConstructor(name, minLanguageVersion) { + return languageVersion < minLanguageVersion ? + getGlobalConstructorWithFallback(name) : + ts.factory.createIdentifier(name); + } + } + ts.createRuntimeTypeSerializer = createRuntimeTypeSerializer; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformLegacyDecorators(context) { + var factory = context.factory, emitHelpers = context.getEmitHelperFactory, hoistVariableDeclaration = context.hoistVariableDeclaration; + var resolver = context.getEmitResolver(); + var compilerOptions = context.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + // Save the previous transformation hooks. + var previousOnSubstituteNode = context.onSubstituteNode; + // Set new transformation hooks. + context.onSubstituteNode = onSubstituteNode; + /** + * A map that keeps track of aliases created for classes with decorators to avoid issues + * with the double-binding behavior of classes. + */ + var classAliases; + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + var visited = ts.visitEachChild(node, visitor, context); + ts.addEmitHelpers(visited, context.readEmitHelpers()); + return visited; + } + function modifierVisitor(node) { + return ts.isDecorator(node) ? undefined : node; + } + function visitor(node) { + if (!(node.transformFlags & 33554432 /* TransformFlags.ContainsDecorators */)) { + return node; + } + switch (node.kind) { + case 165 /* SyntaxKind.Decorator */: + // Decorators are elided. They will be emitted as part of `visitClassDeclaration`. + return undefined; + case 257 /* SyntaxKind.ClassDeclaration */: + return visitClassDeclaration(node); + case 226 /* SyntaxKind.ClassExpression */: + return visitClassExpression(node); + case 171 /* SyntaxKind.Constructor */: + return visitConstructorDeclaration(node); + case 169 /* SyntaxKind.MethodDeclaration */: + return visitMethodDeclaration(node); + case 173 /* SyntaxKind.SetAccessor */: + return visitSetAccessorDeclaration(node); + case 172 /* SyntaxKind.GetAccessor */: + return visitGetAccessorDeclaration(node); + case 167 /* SyntaxKind.PropertyDeclaration */: + return visitPropertyDeclaration(node); + case 164 /* SyntaxKind.Parameter */: + return visitParameterDeclaration(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitClassDeclaration(node) { + if (!(ts.classOrConstructorParameterIsDecorated(node) || ts.childIsDecorated(node))) + return ts.visitEachChild(node, visitor, context); + var statements = ts.hasDecorators(node) ? + transformClassDeclarationWithClassDecorators(node, node.name) : + transformClassDeclarationWithoutClassDecorators(node, node.name); + if (statements.length > 1) { + // Add a DeclarationMarker as a marker for the end of the declaration + statements.push(factory.createEndOfDeclarationMarker(node)); + ts.setEmitFlags(statements[0], ts.getEmitFlags(statements[0]) | 4194304 /* EmitFlags.HasEndOfDeclarationMarker */); + } + return ts.singleOrMany(statements); + } + function decoratorContainsPrivateIdentifierInExpression(decorator) { + return !!(decorator.transformFlags & 536870912 /* TransformFlags.ContainsPrivateIdentifierInExpression */); + } + function parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators) { + return ts.some(parameterDecorators, decoratorContainsPrivateIdentifierInExpression); + } + function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.canHaveDecorators(member)) + continue; + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) + return true; + if (ts.some(allDecorators === null || allDecorators === void 0 ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) + return true; + } + return false; + } + function transformDecoratorsOfClassElements(node, members) { + var decorationStatements = []; + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ false); + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ true); + if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { + members = ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], members, true), [ + factory.createClassStaticBlockDeclaration(factory.createBlock(decorationStatements, /*multiLine*/ true)) + ], false)), members); + decorationStatements = undefined; + } + return { decorationStatements: decorationStatements, members: members }; + } + /** + * Transforms a non-decorated class declaration. + * + * @param node A ClassDeclaration node. + * @param name The name of the class. + */ + function transformClassDeclarationWithoutClassDecorators(node, name) { + // ${modifiers} class ${name} ${heritageClauses} { + // ${members} + // } + var _a; + var modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier); + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var updated = factory.updateClassDeclaration(node, modifiers, name, + /*typeParameters*/ undefined, heritageClauses, members); + return ts.addRange([updated], decorationStatements); + } + /** + * Transforms a decorated class declaration and appends the resulting statements. If + * the class requires an alias to avoid issues with double-binding, the alias is returned. + */ + function transformClassDeclarationWithClassDecorators(node, name) { + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. + // + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: + // + // [Example 1] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // | export { C }; + // --------------------------------------------------------------------- + // + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. + // + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: + // + // [Example 2] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = C_1 = class C { + // class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | var C_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export { C }; + // | var C_1; + // --------------------------------------------------------------------- + // + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: + // + // [Example 3] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: + // + // [Example 4] + // --------------------------------------------------------------------- + // TypeScript | Javascript + // --------------------------------------------------------------------- + // @dec | let C = class C { + // export default class C { | static x() { return C_1.y; } + // static x() { return C.y; } | } + // static y = 1; | C.y = 1; + // } | C = C_1 = __decorate([dec], C); + // | export default C; + // | var C_1; + // --------------------------------------------------------------------- + // + var _a; + var location = ts.moveRangePastModifiers(node); + var classAlias = getClassAliasIfNeeded(node); + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var declName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + // ... = class ${name} ${heritageClauses} { + // ${members} + // } + var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); + var members = ts.visitNodes(node.members, visitor, ts.isClassElement); + var decorationStatements = []; + (_a = transformDecoratorsOfClassElements(node, members), members = _a.members, decorationStatements = _a.decorationStatements); + var classExpression = factory.createClassExpression( + /*modifiers*/ undefined, name, + /*typeParameters*/ undefined, heritageClauses, members); + ts.setOriginalNode(classExpression, node); + ts.setTextRange(classExpression, location); + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. + var statement = factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList([ + factory.createVariableDeclaration(declName, + /*exclamationToken*/ undefined, + /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression) + ], 1 /* NodeFlags.Let */)); + ts.setOriginalNode(statement, node); + ts.setTextRange(statement, location); + ts.setCommentRange(statement, node); + var statements = [statement]; + ts.addRange(statements, decorationStatements); + addConstructorDecorationStatement(statements, node); + return statements; + } + function visitClassExpression(node) { + // Legacy decorators were not supported on class expressions + return factory.updateClassExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)); + } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)); + } + function finishClassElement(updated, original) { + if (updated !== original) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, original); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(original)); + } + return updated; + } + function visitMethodDeclaration(node) { + return finishClassElement(factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitGetAccessorDeclaration(node) { + return finishClassElement(factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitSetAccessorDeclaration(node) { + return finishClassElement(factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), ts.visitNode(node.body, visitor, ts.isBlock)), node); + } + function visitPropertyDeclaration(node) { + if (node.flags & 16777216 /* NodeFlags.Ambient */ || ts.hasSyntacticModifier(node, 2 /* ModifierFlags.Ambient */)) { + return undefined; + } + return finishClassElement(factory.updatePropertyDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.visitNode(node.name, visitor, ts.isPropertyName), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)), node); + } + function visitParameterDeclaration(node) { + var updated = factory.updateParameterDeclaration(node, ts.elideNodes(factory, node.modifiers), node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), + /*questionToken*/ undefined, + /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* EmitFlags.NoTrailingSourceMap */); + } + return updated; + } + /** + * Transforms all of the decorators for a declaration into an array of expressions. + * + * @param allDecorators An object containing all of the decorators for the declaration. + */ + function transformAllDecoratorsOfDeclaration(allDecorators) { + if (!allDecorators) { + return undefined; + } + var decoratorExpressions = []; + ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); + ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); + return decoratorExpressions; + } + /** + * Generates statements used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate statements for static or + * instance members. + */ + function addClassElementDecorationStatements(statements, node, isStatic) { + ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), function (expr) { return factory.createExpressionStatement(expr); })); + } + /** + * Determines whether a class member is either a static or an instance member of a class + * that is decorated, or has parameters that are decorated. + * + * @param member The class member. + */ + function isDecoratedClassElement(member, isStaticElement, parent) { + return ts.nodeOrChildIsDecorated(member, parent) + && isStaticElement === ts.isStatic(member); + } + /** + * Gets either the static or instance members of a class that are decorated, or have + * parameters that are decorated. + * + * @param node The class containing the member. + * @param isStatic A value indicating whether to retrieve static or instance members of + * the class. + */ + function getDecoratedClassElements(node, isStatic) { + return ts.filter(node.members, function (m) { return isDecoratedClassElement(m, isStatic, node); }); + } + /** + * Generates expressions used to apply decorators to either the static or instance members + * of a class. + * + * @param node The class node. + * @param isStatic A value indicating whether to generate expressions for static or + * instance members. + */ + function generateClassElementDecorationExpressions(node, isStatic) { + var members = getDecoratedClassElements(node, isStatic); + var expressions; + for (var _i = 0, members_8 = members; _i < members_8.length; _i++) { + var member = members_8[_i]; + expressions = ts.append(expressions, generateClassElementDecorationExpression(node, member)); + } + return expressions; + } + /** + * Generates an expression used to evaluate class element decorators at runtime. + * + * @param node The class node that contains the member. + * @param member The class member. + */ + function generateClassElementDecorationExpression(node, member) { + var allDecorators = ts.getAllDecoratorsOfClassElement(member, node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", null); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", null); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + var prefix = getClassMemberPrefix(node, member); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* ModifierFlags.Ambient */)); + var descriptor = languageVersion > 0 /* ScriptTarget.ES3 */ + ? member.kind === 167 /* SyntaxKind.PropertyDeclaration */ + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + ? factory.createVoidZero() + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + : factory.createNull() + : undefined; + var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(helper, ts.moveRangePastModifiers(member)); + return helper; + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function addConstructorDecorationStatement(statements, node) { + var expression = generateConstructorDecorationExpression(node); + if (expression) { + statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node)); + } + } + /** + * Generates a __decorate helper call for a class constructor. + * + * @param node The class node. + */ + function generateConstructorDecorationExpression(node) { + var allDecorators = ts.getAllDecoratorsOfClass(node); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); + if (!decoratorExpressions) { + return undefined; + } + var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)]; + // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name + // without any block-scoped variable collision handling + var localName = languageVersion <= 2 /* ScriptTarget.ES2015 */ ? + factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); + var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate); + ts.setEmitFlags(expression, 1536 /* EmitFlags.NoComments */); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(node)); + return expression; + } + /** + * Transforms a decorator into an expression. + * + * @param decorator The decorator node. + */ + function transformDecorator(decorator) { + return ts.visitNode(decorator.expression, visitor, ts.isExpression); + } + /** + * Transforms the decorators of a parameter. + * + * @param decorators The decorators for the parameter at the provided offset. + * @param parameterOffset The offset of the parameter. + */ + function transformDecoratorsOfParameter(decorators, parameterOffset) { + var expressions; + if (decorators) { + expressions = []; + for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { + var decorator = decorators_1[_i]; + var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); + ts.setTextRange(helper, decorator.expression); + ts.setEmitFlags(helper, 1536 /* EmitFlags.NoComments */); + expressions.push(helper); + } + } + return expressions; + } + /** + * Gets an expression that represents a property name (for decorated properties or enums). + * For a computed property, a name is generated for the node. + * + * @param member The member whose name should be converted into an expression. + */ + function getExpressionForPropertyName(member, generateNameForComputedPropertyName) { + var name = member.name; + if (ts.isPrivateIdentifier(name)) { + return factory.createIdentifier(""); + } + else if (ts.isComputedPropertyName(name)) { + return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression) + ? factory.getGeneratedNameForNode(name) + : name.expression; + } + else if (ts.isIdentifier(name)) { + return factory.createStringLiteral(ts.idText(name)); + } + else { + return factory.cloneNode(name); } } function enableSubstitutionForClassAliases() { - if ((enabledSubstitutions & 1 /* ClassPropertySubstitutionFlags.ClassAliases */) === 0) { - enabledSubstitutions |= 1 /* ClassPropertySubstitutionFlags.ClassAliases */; + if (!classAliases) { // We need to enable substitutions for identifiers. This allows us to // substitute class names inside of a class declaration. context.enableSubstitution(79 /* SyntaxKind.Identifier */); @@ -95120,107 +97138,32 @@ var ts; classAliases = []; } } - function enableSubstitutionForClassStaticThisOrSuperReference() { - if ((enabledSubstitutions & 2 /* ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference */) === 0) { - enabledSubstitutions |= 2 /* ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference */; - // substitute `this` in a static field initializer - context.enableSubstitution(108 /* SyntaxKind.ThisKeyword */); - // these push a new lexical environment that is not the class lexical environment - context.enableEmitNotification(256 /* SyntaxKind.FunctionDeclaration */); - context.enableEmitNotification(213 /* SyntaxKind.FunctionExpression */); - context.enableEmitNotification(171 /* SyntaxKind.Constructor */); - // these push a new lexical environment that is not the class lexical environment, except - // when they have a computed property name - context.enableEmitNotification(172 /* SyntaxKind.GetAccessor */); - context.enableEmitNotification(173 /* SyntaxKind.SetAccessor */); - context.enableEmitNotification(169 /* SyntaxKind.MethodDeclaration */); - context.enableEmitNotification(167 /* SyntaxKind.PropertyDeclaration */); - // class lexical environments are restored when entering a computed property name - context.enableEmitNotification(162 /* SyntaxKind.ComputedPropertyName */); - } - } /** - * Generates brand-check initializer for private methods. - * - * @param statements Statement list that should be used to append new statements. - * @param methods An array of method declarations. - * @param receiver The receiver on which each method should be assigned. + * Gets a local alias for a class declaration if it is a decorated class with an internal + * reference to the static side of the class. This is necessary to avoid issues with + * double-binding semantics for the class name. */ - function addMethodStatements(statements, methods, receiver) { - if (!shouldTransformPrivateElementsOrClassStaticBlocks || !ts.some(methods)) { - return; + function getClassAliasIfNeeded(node) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* NodeCheckFlags.ClassWithConstructorReference */) { + enableSubstitutionForClassAliases(); + var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); + classAliases[ts.getOriginalNodeId(node)] = classAlias; + hoistVariableDeclaration(classAlias); + return classAlias; } - var weakSetName = getPrivateIdentifierEnvironment().weakSetName; - ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); - statements.push(factory.createExpressionStatement(createPrivateInstanceMethodInitializer(receiver, weakSetName))); } - function visitInvalidSuperProperty(node) { - return ts.isPropertyAccessExpression(node) ? - factory.updatePropertyAccessExpression(node, factory.createVoidZero(), node.name) : - factory.updateElementAccessExpression(node, factory.createVoidZero(), ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); + function getClassPrototype(node) { + return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype"); } - function onEmitNode(hint, node, emitCallback) { - var original = ts.getOriginalNode(node); - if (original.id) { - var classLexicalEnvironment = classLexicalEnvironmentMap.get(original.id); - if (classLexicalEnvironment) { - var savedClassLexicalEnvironment = currentClassLexicalEnvironment; - var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; - currentClassLexicalEnvironment = classLexicalEnvironment; - currentComputedPropertyNameClassLexicalEnvironment = classLexicalEnvironment; - previousOnEmitNode(hint, node, emitCallback); - currentClassLexicalEnvironment = savedClassLexicalEnvironment; - currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment; - return; - } - } - switch (node.kind) { - case 213 /* SyntaxKind.FunctionExpression */: - if (ts.isArrowFunction(original) || ts.getEmitFlags(node) & 262144 /* EmitFlags.AsyncFunctionBody */) { - break; - } - // falls through - case 256 /* SyntaxKind.FunctionDeclaration */: - case 171 /* SyntaxKind.Constructor */: { - var savedClassLexicalEnvironment = currentClassLexicalEnvironment; - var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; - currentClassLexicalEnvironment = undefined; - currentComputedPropertyNameClassLexicalEnvironment = undefined; - previousOnEmitNode(hint, node, emitCallback); - currentClassLexicalEnvironment = savedClassLexicalEnvironment; - currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment; - return; - } - case 172 /* SyntaxKind.GetAccessor */: - case 173 /* SyntaxKind.SetAccessor */: - case 169 /* SyntaxKind.MethodDeclaration */: - case 167 /* SyntaxKind.PropertyDeclaration */: { - var savedClassLexicalEnvironment = currentClassLexicalEnvironment; - var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; - currentComputedPropertyNameClassLexicalEnvironment = currentClassLexicalEnvironment; - currentClassLexicalEnvironment = undefined; - previousOnEmitNode(hint, node, emitCallback); - currentClassLexicalEnvironment = savedClassLexicalEnvironment; - currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment; - return; - } - case 162 /* SyntaxKind.ComputedPropertyName */: { - var savedClassLexicalEnvironment = currentClassLexicalEnvironment; - var savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; - currentClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment; - currentComputedPropertyNameClassLexicalEnvironment = undefined; - previousOnEmitNode(hint, node, emitCallback); - currentClassLexicalEnvironment = savedClassLexicalEnvironment; - currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment; - return; - } - } - previousOnEmitNode(hint, node, emitCallback); + function getClassMemberPrefix(node, member) { + return ts.isStatic(member) + ? factory.getDeclarationName(node) + : getClassPrototype(node); } /** * Hooks node substitutions. * - * @param hint The context for the emitter. + * @param hint A hint as to the intended usage of the node. * @param node The node to substitute. */ function onSubstituteNode(hint, node) { @@ -95234,28 +97177,15 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: return substituteExpressionIdentifier(node); - case 108 /* SyntaxKind.ThisKeyword */: - return substituteThisExpression(node); - } - return node; - } - function substituteThisExpression(node) { - if (enabledSubstitutions & 2 /* ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference */ && currentClassLexicalEnvironment) { - var facts = currentClassLexicalEnvironment.facts, classConstructor = currentClassLexicalEnvironment.classConstructor; - if (facts & 1 /* ClassFacts.ClassWasDecorated */) { - return factory.createParenthesizedExpression(factory.createVoidZero()); - } - if (classConstructor) { - return ts.setTextRange(ts.setOriginalNode(factory.cloneNode(classConstructor), node), node); - } } return node; } function substituteExpressionIdentifier(node) { - return trySubstituteClassAlias(node) || node; + var _a; + return (_a = trySubstituteClassAlias(node)) !== null && _a !== void 0 ? _a : node; } function trySubstituteClassAlias(node) { - if (enabledSubstitutions & 1 /* ClassPropertySubstitutionFlags.ClassAliases */) { + if (classAliases) { if (resolver.getNodeCheckFlags(node) & 33554432 /* NodeCheckFlags.ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind @@ -95276,358 +97206,8 @@ var ts; } return undefined; } - /** - * If the name is a computed property, this function transforms it, then either returns an expression which caches the - * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations - * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) - */ - function getPropertyNameExpressionIfNeeded(name, shouldHoist) { - if (ts.isComputedPropertyName(name)) { - var expression = ts.visitNode(name.expression, visitor, ts.isExpression); - var innerExpression = ts.skipPartiallyEmittedExpressions(expression); - var inlinable = ts.isSimpleInlineableExpression(innerExpression); - var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left); - if (!alreadyTransformed && !inlinable && shouldHoist) { - var generatedName = factory.getGeneratedNameForNode(name); - if (resolver.getNodeCheckFlags(name) & 524288 /* NodeCheckFlags.BlockScopedBindingInLoop */) { - addBlockScopedVariable(generatedName); - } - else { - hoistVariableDeclaration(generatedName); - } - return factory.createAssignment(generatedName, expression); - } - return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression; - } - } - function startClassLexicalEnvironment() { - classLexicalEnvironmentStack.push(currentClassLexicalEnvironment); - currentClassLexicalEnvironment = undefined; - } - function endClassLexicalEnvironment() { - currentClassLexicalEnvironment = classLexicalEnvironmentStack.pop(); - } - function getClassLexicalEnvironment() { - return currentClassLexicalEnvironment || (currentClassLexicalEnvironment = { - facts: 0 /* ClassFacts.None */, - classConstructor: undefined, - superClassReference: undefined, - privateIdentifierEnvironment: undefined, - }); - } - function getPrivateIdentifierEnvironment() { - var lex = getClassLexicalEnvironment(); - lex.privateIdentifierEnvironment || (lex.privateIdentifierEnvironment = { - className: "", - identifiers: new ts.Map() - }); - return lex.privateIdentifierEnvironment; - } - function getPendingExpressions() { - return pendingExpressions || (pendingExpressions = []); - } - function addPrivateIdentifierToEnvironment(node) { - var _a; - var text = ts.getTextOfPropertyName(node.name); - var lex = getClassLexicalEnvironment(); - var classConstructor = lex.classConstructor; - var privateEnv = getPrivateIdentifierEnvironment(); - var weakSetName = privateEnv.weakSetName; - var assignmentExpressions = []; - var privateName = node.name.escapedText; - var previousInfo = privateEnv.identifiers.get(privateName); - var isValid = !isReservedPrivateName(node.name) && previousInfo === undefined; - if (ts.hasStaticModifier(node)) { - ts.Debug.assert(classConstructor, "weakSetName should be set in private identifier environment"); - if (ts.isPropertyDeclaration(node)) { - var variableName = createHoistedVariableForPrivateName(text, node); - privateEnv.identifiers.set(privateName, { - kind: "f" /* PrivateIdentifierKind.Field */, - variableName: variableName, - brandCheckIdentifier: classConstructor, - isStatic: true, - isValid: isValid, - }); - } - else if (ts.isMethodDeclaration(node)) { - var functionName = createHoistedVariableForPrivateName(text, node); - privateEnv.identifiers.set(privateName, { - kind: "m" /* PrivateIdentifierKind.Method */, - methodName: functionName, - brandCheckIdentifier: classConstructor, - isStatic: true, - isValid: isValid, - }); - } - else if (ts.isGetAccessorDeclaration(node)) { - var getterName = createHoistedVariableForPrivateName(text + "_get", node); - if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && previousInfo.isStatic && !previousInfo.getterName) { - previousInfo.getterName = getterName; - } - else { - privateEnv.identifiers.set(privateName, { - kind: "a" /* PrivateIdentifierKind.Accessor */, - getterName: getterName, - setterName: undefined, - brandCheckIdentifier: classConstructor, - isStatic: true, - isValid: isValid, - }); - } - } - else if (ts.isSetAccessorDeclaration(node)) { - var setterName = createHoistedVariableForPrivateName(text + "_set", node); - if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && previousInfo.isStatic && !previousInfo.setterName) { - previousInfo.setterName = setterName; - } - else { - privateEnv.identifiers.set(privateName, { - kind: "a" /* PrivateIdentifierKind.Accessor */, - getterName: undefined, - setterName: setterName, - brandCheckIdentifier: classConstructor, - isStatic: true, - isValid: isValid, - }); - } - } - else { - ts.Debug.assertNever(node, "Unknown class element type."); - } - } - else if (ts.isPropertyDeclaration(node)) { - var weakMapName = createHoistedVariableForPrivateName(text, node); - privateEnv.identifiers.set(privateName, { - kind: "f" /* PrivateIdentifierKind.Field */, - brandCheckIdentifier: weakMapName, - isStatic: false, - variableName: undefined, - isValid: isValid, - }); - assignmentExpressions.push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), - /*typeArguments*/ undefined, []))); - } - else if (ts.isMethodDeclaration(node)) { - ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); - privateEnv.identifiers.set(privateName, { - kind: "m" /* PrivateIdentifierKind.Method */, - methodName: createHoistedVariableForPrivateName(text, node), - brandCheckIdentifier: weakSetName, - isStatic: false, - isValid: isValid, - }); - } - else if (ts.isAccessor(node)) { - ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); - if (ts.isGetAccessor(node)) { - var getterName = createHoistedVariableForPrivateName(text + "_get", node); - if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && !previousInfo.isStatic && !previousInfo.getterName) { - previousInfo.getterName = getterName; - } - else { - privateEnv.identifiers.set(privateName, { - kind: "a" /* PrivateIdentifierKind.Accessor */, - getterName: getterName, - setterName: undefined, - brandCheckIdentifier: weakSetName, - isStatic: false, - isValid: isValid, - }); - } - } - else { - var setterName = createHoistedVariableForPrivateName(text + "_set", node); - if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* PrivateIdentifierKind.Accessor */ && !previousInfo.isStatic && !previousInfo.setterName) { - previousInfo.setterName = setterName; - } - else { - privateEnv.identifiers.set(privateName, { - kind: "a" /* PrivateIdentifierKind.Accessor */, - getterName: undefined, - setterName: setterName, - brandCheckIdentifier: weakSetName, - isStatic: false, - isValid: isValid, - }); - } - } - } - else { - ts.Debug.assertNever(node, "Unknown class element type."); - } - (_a = getPendingExpressions()).push.apply(_a, assignmentExpressions); - } - function createHoistedVariableForClass(name, node) { - var className = getPrivateIdentifierEnvironment().className; - var prefix = className ? "_".concat(className) : ""; - var identifier = factory.createUniqueName("".concat(prefix, "_").concat(name), 16 /* GeneratedIdentifierFlags.Optimistic */); - if (resolver.getNodeCheckFlags(node) & 524288 /* NodeCheckFlags.BlockScopedBindingInLoop */) { - addBlockScopedVariable(identifier); - } - else { - hoistVariableDeclaration(identifier); - } - return identifier; - } - function createHoistedVariableForPrivateName(privateName, node) { - return createHoistedVariableForClass(privateName.substring(1), node.name); - } - function accessPrivateIdentifier(name) { - var _a; - if (currentClassLexicalEnvironment === null || currentClassLexicalEnvironment === void 0 ? void 0 : currentClassLexicalEnvironment.privateIdentifierEnvironment) { - var info = currentClassLexicalEnvironment.privateIdentifierEnvironment.identifiers.get(name.escapedText); - if (info) { - return info; - } - } - for (var i = classLexicalEnvironmentStack.length - 1; i >= 0; --i) { - var env = classLexicalEnvironmentStack[i]; - if (!env) { - continue; - } - var info = (_a = env.privateIdentifierEnvironment) === null || _a === void 0 ? void 0 : _a.identifiers.get(name.escapedText); - if (info) { - return info; - } - } - return undefined; - } - function wrapPrivateIdentifierForDestructuringTarget(node) { - var parameter = factory.getGeneratedNameForNode(node); - var info = accessPrivateIdentifier(node.name); - if (!info) { - return ts.visitEachChild(node, visitor, context); - } - var receiver = node.expression; - // We cannot copy `this` or `super` into the function because they will be bound - // differently inside the function. - if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) { - receiver = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true); - getPendingExpressions().push(factory.createBinaryExpression(receiver, 63 /* SyntaxKind.EqualsToken */, ts.visitNode(node.expression, visitor, ts.isExpression))); - } - return factory.createAssignmentTargetWrapper(parameter, createPrivateIdentifierAssignment(info, receiver, parameter, 63 /* SyntaxKind.EqualsToken */)); - } - function visitArrayAssignmentTarget(node) { - var target = ts.getTargetOfBindingOrAssignmentElement(node); - if (target) { - var wrapped = void 0; - if (ts.isPrivateIdentifierPropertyAccessExpression(target)) { - wrapped = wrapPrivateIdentifierForDestructuringTarget(target); - } - else if (shouldTransformSuperInStaticInitializers && - ts.isSuperProperty(target) && - currentStaticPropertyDeclarationOrStaticBlock && - currentClassLexicalEnvironment) { - var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; - if (facts & 1 /* ClassFacts.ClassWasDecorated */) { - wrapped = visitInvalidSuperProperty(target); - } - else if (classConstructor && superClassReference) { - var name = ts.isElementAccessExpression(target) ? ts.visitNode(target.argumentExpression, visitor, ts.isExpression) : - ts.isIdentifier(target.name) ? factory.createStringLiteralFromNode(target.name) : - undefined; - if (name) { - var temp = factory.createTempVariable(/*recordTempVariable*/ undefined); - wrapped = factory.createAssignmentTargetWrapper(temp, factory.createReflectSetCall(superClassReference, name, temp, classConstructor)); - } - } - } - if (wrapped) { - if (ts.isAssignmentExpression(node)) { - return factory.updateBinaryExpression(node, wrapped, node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression)); - } - else if (ts.isSpreadElement(node)) { - return factory.updateSpreadElement(node, wrapped); - } - else { - return wrapped; - } - } - } - return ts.visitNode(node, visitorDestructuringTarget); - } - function visitObjectAssignmentTarget(node) { - if (ts.isObjectBindingOrAssignmentElement(node) && !ts.isShorthandPropertyAssignment(node)) { - var target = ts.getTargetOfBindingOrAssignmentElement(node); - var wrapped = void 0; - if (target) { - if (ts.isPrivateIdentifierPropertyAccessExpression(target)) { - wrapped = wrapPrivateIdentifierForDestructuringTarget(target); - } - else if (shouldTransformSuperInStaticInitializers && - ts.isSuperProperty(target) && - currentStaticPropertyDeclarationOrStaticBlock && - currentClassLexicalEnvironment) { - var classConstructor = currentClassLexicalEnvironment.classConstructor, superClassReference = currentClassLexicalEnvironment.superClassReference, facts = currentClassLexicalEnvironment.facts; - if (facts & 1 /* ClassFacts.ClassWasDecorated */) { - wrapped = visitInvalidSuperProperty(target); - } - else if (classConstructor && superClassReference) { - var name = ts.isElementAccessExpression(target) ? ts.visitNode(target.argumentExpression, visitor, ts.isExpression) : - ts.isIdentifier(target.name) ? factory.createStringLiteralFromNode(target.name) : - undefined; - if (name) { - var temp = factory.createTempVariable(/*recordTempVariable*/ undefined); - wrapped = factory.createAssignmentTargetWrapper(temp, factory.createReflectSetCall(superClassReference, name, temp, classConstructor)); - } - } - } - } - if (ts.isPropertyAssignment(node)) { - var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); - return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor, ts.isPropertyName), wrapped ? - initializer ? factory.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped : - ts.visitNode(node.initializer, visitorDestructuringTarget, ts.isExpression)); - } - if (ts.isSpreadAssignment(node)) { - return factory.updateSpreadAssignment(node, wrapped || ts.visitNode(node.expression, visitorDestructuringTarget, ts.isExpression)); - } - ts.Debug.assert(wrapped === undefined, "Should not have generated a wrapped target"); - } - return ts.visitNode(node, visitor); - } - function visitAssignmentPattern(node) { - if (ts.isArrayLiteralExpression(node)) { - // Transforms private names in destructuring assignment array bindings. - // Transforms SuperProperty assignments in destructuring assignment array bindings in static initializers. - // - // Source: - // ([ this.#myProp ] = [ "hello" ]); - // - // Transformation: - // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ]; - return factory.updateArrayLiteralExpression(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression)); - } - else { - // Transforms private names in destructuring assignment object bindings. - // Transforms SuperProperty assignments in destructuring assignment object bindings in static initializers. - // - // Source: - // ({ stringProperty: this.#myProp } = { stringProperty: "hello" }); - // - // Transformation: - // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" }; - return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike)); - } - } - } - ts.transformClassFields = transformClassFields; - function createPrivateStaticFieldInitializer(variableName, initializer) { - return ts.factory.createAssignment(variableName, ts.factory.createObjectLiteralExpression([ - ts.factory.createPropertyAssignment("value", initializer || ts.factory.createVoidZero()) - ])); - } - function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) { - return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), - /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]); - } - function createPrivateInstanceMethodInitializer(receiver, weakSetName) { - return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakSetName, "add"), - /*typeArguments*/ undefined, [receiver]); - } - function isReservedPrivateName(node) { - return node.escapedText === "#constructor"; } + ts.transformLegacyDecorators = transformLegacyDecorators; })(ts || (ts = {})); /*@internal*/ var ts; @@ -95849,8 +97429,7 @@ var ts; * @param node The node to visit. */ function visitMethodDeclaration(node) { - return factory.updateMethodDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ @@ -95866,8 +97445,7 @@ var ts; * @param node The node to visit. */ function visitFunctionDeclaration(node) { - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -95882,7 +97460,7 @@ var ts; * @param node The node to visit. */ function visitFunctionExpression(node) { - return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, + return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -95897,7 +97475,7 @@ var ts; * @param node The node to visit. */ function visitArrowFunction(node) { - return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), + return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) @@ -96199,7 +97777,6 @@ var ts; /* typeParameters */ undefined, /* parameters */ [ factory.createParameterDeclaration( - /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, "v", /* questionToken */ undefined, @@ -96479,7 +98056,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -96552,7 +98129,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* SyntaxKind.CommaToken */) { @@ -96583,7 +98160,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* FlattenLevel.ObjectRest */); @@ -96624,7 +98201,7 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* FlattenLevel.ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } @@ -96643,7 +98220,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* HierarchyFacts.IterationStatementExcludes */, 2 /* HierarchyFacts.IterationStatementIncludes */); - if (node.initializer.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -96750,17 +98327,15 @@ var ts; function visitParameter(node) { if (parametersWithPrecedingObjectRestOrSpread === null || parametersWithPrecedingObjectRestOrSpread === void 0 ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); } - if (node.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + if (node.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, - /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); @@ -96774,7 +98349,7 @@ var ts; if (parameters) { parameters.add(parameter); } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { parameters = new ts.Set(); } } @@ -96785,8 +98360,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateConstructorDeclaration(node, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -96796,8 +98370,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), + var updated = factory.updateGetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -96808,8 +98381,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); + var updated = factory.updateSetAccessorDeclaration(node, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -96819,9 +98391,8 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateMethodDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ - ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) + var updated = factory.updateMethodDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifierLike) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), @@ -96838,8 +98409,7 @@ var ts; var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - var updated = factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ + var updated = factory.updateFunctionDeclaration(node, enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* FunctionFlags.Async */ ? undefined @@ -96997,7 +98567,7 @@ var ts; statements = ts.append(statements, statement); } } - else if (parameter.transformFlags & 32768 /* TransformFlags.ContainsObjectRestOrSpread */) { + else if (parameter.transformFlags & 65536 /* TransformFlags.ContainsObjectRestOrSpread */) { containsPrecedingObjectRestOrSpread = true; var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* FlattenLevel.ObjectRest */, factory.getGeneratedNameForNode(parameter), /*doNotRecordTempVariablesInLine*/ false, @@ -97494,7 +99064,7 @@ var ts; var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1]; if (ts.isExternalModule(node)) { // Add `import` statement - var importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); + var importStatement = factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined); ts.setParentRecursive(importStatement, /*incremental*/ false); statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement); } @@ -97725,22 +99295,29 @@ var ts; if (node === undefined) { return factory.createTrue(); } - else if (node.kind === 10 /* SyntaxKind.StringLiteral */) { + if (node.kind === 10 /* SyntaxKind.StringLiteral */) { // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which // Need to be escaped to be handled correctly in a normal string var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 288 /* SyntaxKind.JsxExpression */) { + if (node.kind === 288 /* SyntaxKind.JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } return ts.visitNode(node.expression, visitor, ts.isExpression); } - else { - return ts.Debug.failBadSyntaxKind(node); + if (ts.isJsxElement(node)) { + return visitJsxElement(node, /*isChild*/ false); + } + if (ts.isJsxSelfClosingElement(node)) { + return visitJsxSelfClosingElement(node, /*isChild*/ false); } + if (ts.isJsxFragment(node)) { + return visitJsxFragment(node, /*isChild*/ false); + } + return ts.Debug.failBadSyntaxKind(node); } function visitJsxText(node) { var fixed = fixupWhitespaceAndDecodeEntities(node.text); @@ -98362,7 +99939,7 @@ var ts; && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -98735,7 +100312,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], + /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */))] : [], /*type*/ undefined, transformClassBody(node, extendsClauseElement)); // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier @@ -98813,7 +100390,6 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), @@ -98926,7 +100502,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass || superCallExpression) { - if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */)) { + if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -99078,7 +100654,6 @@ var ts; // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, @@ -99090,7 +100665,6 @@ var ts; else if (node.initializer) { // Initializers are elided return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, node.name, /*questionToken*/ undefined, @@ -99471,7 +101045,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { + if (node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* HierarchyFacts.StaticInitializer */)) { hierarchyFacts |= 65536 /* HierarchyFacts.CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -99530,8 +101104,7 @@ var ts; : node.name; exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; - return factory.updateFunctionDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, + return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -99757,7 +101330,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */) { + if (node.flags & 3 /* NodeFlags.BlockScoped */ || node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */) { if (node.flags & 3 /* NodeFlags.BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -99770,7 +101343,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 262144 /* TransformFlags.ContainsBindingPattern */ + if (node.transformFlags & 524288 /* TransformFlags.ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -100094,7 +101667,7 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 524288 /* TransformFlags.ContainsYield */ && + if ((property.transformFlags & 1048576 /* TransformFlags.ContainsYield */ && hierarchyFacts & 4 /* HierarchyFacts.AsyncFunctionBody */) || (hasComputed = ts.Debug.checkDefined(property.name).kind === 162 /* SyntaxKind.ComputedPropertyName */)) { numInitialProperties = i; @@ -100367,7 +101940,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 0 /* EmitFlags.None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -100482,7 +102055,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; var emitFlags = 524288 /* EmitFlags.ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* EmitFlags.CapturesThis */; @@ -100625,7 +102198,7 @@ var ts; } } else { - loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); + loopParameters.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); var checkFlags = resolver.getNodeCheckFlags(decl); if (checkFlags & 4194304 /* NodeCheckFlags.NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { var outParamName = factory.createUniqueName("out_" + ts.idText(name)); @@ -100782,10 +102355,10 @@ var ts; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); if (node.kind === 172 /* SyntaxKind.GetAccessor */) { - updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + updated = factory.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body); } else { - updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body); + updated = factory.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 98304 /* HierarchyFacts.FunctionSubtreeExcludes */, 0 /* HierarchyFacts.None */); convertedLoopState = savedConvertedLoopState; @@ -100964,7 +102537,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */ || + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */ || node.expression.kind === 106 /* SyntaxKind.SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -100972,7 +102545,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* EmitFlags.NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 16384 /* TransformFlags.ContainsRestOrSpread */) { + if (node.transformFlags & 32768 /* TransformFlags.ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -101814,10 +103387,10 @@ var ts; case 247 /* SyntaxKind.ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 2097152 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (2048 /* TransformFlags.ContainsGenerator */ | 4194304 /* TransformFlags.ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -101881,8 +103454,7 @@ var ts; function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. if (node.asteriskToken) { - node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, node.modifiers, + node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(node.modifiers, /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, transformGeneratorFunctionBody(node.body)), @@ -102022,7 +103594,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) { + if (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -103080,7 +104652,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 524288 /* TransformFlags.ContainsYield */) !== 0; + return !!node && (node.transformFlags & 1048576 /* TransformFlags.ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -103711,7 +105283,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], /*type*/ undefined, factory.createBlock(buildResult, /*multiLine*/ buildResult.length > 0)), 524288 /* EmitFlags.ReuseTempVariableScope */)); } @@ -104129,7 +105701,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */ || + node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -104230,8 +105802,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ], false))) @@ -104252,7 +105824,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], /*type*/ undefined, ts.setTextRange(factory.createBlock([ factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([ factory.createVariableStatement( @@ -104301,8 +105873,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, __spreadArray([ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") ], importAliasNames, true), /*type*/ undefined, transformAsynchronousModuleBody(node)) ])) @@ -104331,7 +105903,7 @@ var ts; var amdDependency = _a[_i]; if (amdDependency.name) { aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); } else { unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); @@ -104352,7 +105924,7 @@ var ts; // This is so that when printer will not substitute the identifier ts.setEmitFlags(importAliasName, 4 /* EmitFlags.NoSubstitution */); aliasedModuleNames.push(externalModuleName); - importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); + importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); } else { unaliasedModuleNames.push(externalModuleName); @@ -104466,7 +106038,7 @@ var ts; function visitorWorker(node, valueIsDiscarded) { // This visitor does not need to descend into the tree if there is no dynamic import, destructuring assignment, or update expression // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & (4194304 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (8388608 /* TransformFlags.ContainsDynamicImport */ | 4096 /* TransformFlags.ContainsDestructuringAssignment */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -104617,7 +106189,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), visitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 8192 /* TransformFlags.ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 16384 /* TransformFlags.ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -104672,8 +106244,8 @@ var ts; var resolve = factory.createUniqueName("resolve"); var reject = factory.createUniqueName("reject"); var parameters = [ - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) ]; var body = factory.createBlock([ factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), @@ -104961,8 +106533,7 @@ var ts; function visitFunctionDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor), /*type*/ undefined, ts.visitEachChild(node.body, visitor, context)), /*location*/ node), @@ -104989,8 +106560,7 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor), ts.visitNodes(node.members, visitor)), node), node)); } else { @@ -105604,7 +107174,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* TransformFlags.ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* TransformFlags.ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -105637,8 +107207,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), - factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) ], /*type*/ undefined, moduleBodyBlock); // Write the call to `System.register` @@ -105773,7 +107343,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 1048576 /* TransformFlags.ContainsAwait */ ? + var modifiers = node.transformFlags & 2097152 /* TransformFlags.ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* ModifierFlags.Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -105860,10 +107430,9 @@ var ts; /*typeArguments*/ undefined, [n]))); } return factory.createFunctionDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, exportStarFunction, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], /*type*/ undefined, factory.createBlock([ factory.createVariableStatement( /*modifiers*/ undefined, factory.createVariableDeclarationList([ @@ -105954,7 +107523,7 @@ var ts; /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], + /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true))); } return factory.createArrayLiteralExpression(setters, /*multiLine*/ true); @@ -106052,7 +107621,7 @@ var ts; */ function visitFunctionDeclaration(node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { - hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), + hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, ts.visitNodes(node.parameters, visitor, ts.isParameterDeclaration), /*type*/ undefined, ts.visitNode(node.body, visitor, ts.isBlock))); } @@ -106080,8 +107649,7 @@ var ts; var name = factory.getLocalName(node); hoistVariableDeclaration(name); // Rewrite the class declaration into an assignment of a class expression. - statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, visitor, ts.isDecorator), - /*modifiers*/ undefined, node.name, + statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifierLike), node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), ts.visitNodes(node.members, visitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -106682,7 +108250,7 @@ var ts; * @param node The node to visit. */ function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 4194304 /* TransformFlags.ContainsDynamicImport */ | 67108864 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (4096 /* TransformFlags.ContainsDestructuringAssignment */ | 8388608 /* TransformFlags.ContainsDynamicImport */ | 268435456 /* TransformFlags.ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -107129,7 +108697,7 @@ var ts; // Though an error in es2020 modules, in node-flavor es2020 modules, we can helpfully transform this to a synthetic `require` call // To give easy access to a synchronous `require` in node-flavor esm. We do the transform even in scenarios where we error, but `import.meta.url` // is available, just because the output is reasonable for a node-like runtime. - return ts.getEmitScriptTarget(compilerOptions) >= ts.ModuleKind.ES2020 ? visitImportEqualsDeclaration(node) : undefined; + return ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.Node16 ? visitImportEqualsDeclaration(node) : undefined; case 271 /* SyntaxKind.ExportAssignment */: return visitExportAssignment(node); case 272 /* SyntaxKind.ExportDeclaration */: @@ -107152,7 +108720,6 @@ var ts; if (!importRequireStatements) { var createRequireName = factory.createUniqueName("_createRequire", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */); var importStatement = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamedImports([ @@ -107195,7 +108762,6 @@ var ts; function appendExportsOfImportEqualsDeclaration(statements, node) { if (ts.hasSyntacticModifier(node, 1 /* ModifierFlags.Export */)) { statements = ts.append(statements, factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, node.isTypeOnly, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, ts.idText(node.name))]))); } return statements; @@ -107216,13 +108782,11 @@ var ts; var oldIdentifier = node.exportClause.name; var synthName = factory.getGeneratedNameForNode(oldIdentifier); var importDecl = factory.createImportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier, node.assertClause); ts.setOriginalNode(importDecl, node.exportClause); var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, synthName, oldIdentifier)])); ts.setOriginalNode(exportDecl, node); @@ -107474,7 +109038,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.SyntaxKind[node.kind])); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(node.kind))); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 254 /* SyntaxKind.VariableDeclaration */ || node.kind === 203 /* SyntaxKind.BindingElement */) { @@ -107685,7 +109249,7 @@ var ts; ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1; default: - return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.SyntaxKind[node.parent.kind])); + return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.Debug.formatSyntaxKind(node.parent.kind))); } } function getTypeParameterConstraintVisibilityError() { @@ -107850,7 +109414,8 @@ var ts; trackReferencedAmbientModule: trackReferencedAmbientModule, trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, reportNonlocalAugmentation: reportNonlocalAugmentation, - reportNonSerializableProperty: reportNonSerializableProperty + reportNonSerializableProperty: reportNonSerializableProperty, + reportImportTypeNodeResolutionModeOverride: reportImportTypeNodeResolutionModeOverride, }; var errorNameNode; var errorFallbackNode; @@ -107977,6 +109542,11 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName)); } } + function reportImportTypeNodeResolutionModeOverride() { + if (!ts.isNightly() && (errorNameNode || errorFallbackNode)) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ @@ -108016,7 +109586,7 @@ var ts; resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -108159,7 +109729,7 @@ var ts; }); return ret; } - function filterBindingPatternInitializers(name) { + function filterBindingPatternInitializersAndRenamings(name) { if (name.kind === 79 /* SyntaxKind.Identifier */) { return name; } @@ -108175,7 +109745,12 @@ var ts; if (elem.kind === 227 /* SyntaxKind.OmittedExpression */) { return elem; } - return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + if (elem.propertyName && ts.isIdentifier(elem.propertyName) && ts.isIdentifier(elem.name) && !elem.symbol.isReferenced) { + // Unnecessary property renaming is forbidden in types, so remove renaming + return factory.updateBindingElement(elem, elem.dotDotDotToken, + /* propertyName */ undefined, elem.propertyName, shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializersAndRenamings(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); } } function ensureParameter(p, modifierMask, type) { @@ -108184,8 +109759,7 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); } - var newParam = factory.updateParameterDeclaration(p, - /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + var newParam = factory.updateParameterDeclaration(p, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(57 /* SyntaxKind.QuestionToken */)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; @@ -108236,7 +109810,7 @@ var ts; if (node.kind === 164 /* SyntaxKind.Parameter */ || node.kind === 167 /* SyntaxKind.PropertyDeclaration */ || node.kind === 166 /* SyntaxKind.PropertySignature */) { - if (!node.initializer) + if (ts.isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } @@ -108322,7 +109896,6 @@ var ts; } if (!newValueParameter) { newValueParameter = factory.createParameterDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "value"); } @@ -108380,8 +109953,7 @@ var ts; if (decl.moduleReference.kind === 277 /* SyntaxKind.ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); - return factory.updateImportEqualsDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + return factory.updateImportEqualsDeclaration(decl, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } else { var oldDiag = getSymbolAccessibilityDiagnostic; @@ -108394,31 +109966,28 @@ var ts; function transformImportDeclaration(decl) { if (!decl.importClause) { // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // The `importClause` visibility corresponds to the default's visibility. var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; if (!decl.importClause.namedBindings) { // No named bindings (either namespace or list), meaning the import is just default or should be elided - return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, + return visibleDefaultBinding && factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } if (decl.importClause.namedBindings.kind === 268 /* SyntaxKind.NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; - return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; + return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; } // Named imports (optionally with visible default) var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); if ((bindingList && bindingList.length) || visibleDefaultBinding) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Augmentation of export depends on import if (resolver.isImportRequiredByAugmentation(decl)) { - return factory.updateImportDeclaration(decl, - /*decorators*/ undefined, decl.modifiers, + return factory.updateImportDeclaration(decl, decl.modifiers, /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); } // Nothing visible @@ -108427,7 +109996,7 @@ var ts; var mode = ts.getResolutionModeOverrideForClause(assertClause); if (mode !== undefined) { if (!ts.isNightly()) { - context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.Resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); + context.addDiagnostic(ts.createDiagnosticForNode(assertClause, ts.Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next)); } return assertClause; } @@ -108451,7 +110020,7 @@ var ts; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.Debug.formatSyntaxKind(i.kind))); } var priorNeedsDeclare = needsDeclare; needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); @@ -108515,7 +110084,7 @@ var ts; if (ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)) { if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; // Elide all but the first overload - return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + return cleanup(factory.createPropertyDeclaration(ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); } } if (canProduceDiagnostic && !suppressNewDiagnosticContexts) { @@ -108547,7 +110116,6 @@ var ts; case 171 /* SyntaxKind.Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( - /*decorators*/ undefined, /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* ModifierFlags.None */), /*body*/ undefined); return cleanup(ctor); @@ -108556,8 +110124,7 @@ var ts; if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - var sig = factory.createMethodDeclaration( - /*decorators*/ undefined, ensureModifiers(input), + var sig = factory.createMethodDeclaration(ensureModifiers(input), /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined); return cleanup(sig); @@ -108567,24 +110134,21 @@ var ts; return cleanup(/*returnValue*/ undefined); } var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); - return cleanup(factory.updateGetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), + return cleanup(factory.updateGetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), ensureType(input, accessorType), /*body*/ undefined)); } case 173 /* SyntaxKind.SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updateSetAccessorDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), + return cleanup(factory.updateSetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* ModifierFlags.Private */)), /*body*/ undefined)); } case 167 /* SyntaxKind.PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } - return cleanup(factory.updatePropertyDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); + return cleanup(factory.updatePropertyDeclaration(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); case 166 /* SyntaxKind.PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); @@ -108600,8 +110164,7 @@ var ts; return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } case 176 /* SyntaxKind.IndexSignature */: { - return cleanup(factory.updateIndexSignature(input, - /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); + return cleanup(factory.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(130 /* SyntaxKind.AnyKeyword */))); } case 254 /* SyntaxKind.VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { @@ -108640,7 +110203,7 @@ var ts; return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.assertions, input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); } - default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.SyntaxKind[input.kind])); + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.Debug.formatSyntaxKind(input.kind))); } } if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) { @@ -108684,8 +110247,7 @@ var ts; resultHasScopeMarker = true; // Always visible if the parent node isn't dropped for being not visible // Rewrite external module names if necessary - return factory.updateExportDeclaration(input, - /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); + return factory.updateExportDeclaration(input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), ts.getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined); } case 271 /* SyntaxKind.ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible @@ -108708,7 +110270,7 @@ var ts; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(135 /* SyntaxKind.DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* NodeFlags.Const */)); preserveJsDoc(statement, input); ts.removeAllComments(input); - return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + return [statement, factory.updateExportAssignment(input, input.modifiers, newId)]; } } } @@ -108723,7 +110285,7 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (125951 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (257023 /* ModifierFlags.All */ ^ 1 /* ModifierFlags.Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { @@ -108759,22 +110321,19 @@ var ts; var previousNeedsDeclare = needsDeclare; switch (input.kind) { case 259 /* SyntaxKind.TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all - return cleanup(factory.updateTypeAliasDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + return cleanup(factory.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); case 258 /* SyntaxKind.InterfaceDeclaration */: { - return cleanup(factory.updateInterfaceDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + return cleanup(factory.updateInterfaceDeclaration(input, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 256 /* SyntaxKind.FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - var clean = cleanup(factory.updateFunctionDeclaration(input, - /*decorators*/ undefined, ensureModifiers(input), + var clean = cleanup(factory.updateFunctionDeclaration(input, ensureModifiers(input), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); if (clean && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { var props = resolver.getPropertiesOfContainerFunction(input); // Use parseNodeFactory so it is usable as an enclosing declaration - var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); + var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* NodeFlags.Namespace */); ts.setParent(fakespace_1, enclosingDeclaration); fakespace_1.locals = ts.createSymbolTable(props); fakespace_1.symbol = props[0].parent; @@ -108800,26 +110359,22 @@ var ts; } else { declarations.push(factory.createExportDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) { var gen = _a[0], exp = _a[1]; return factory.createExportSpecifier(/*isTypeOnly*/ false, gen, exp); })))); } - var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); + var namespaceDecl = factory.createModuleDeclaration(ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* NodeFlags.Namespace */); if (!ts.hasEffectiveModifier(clean, 512 /* ModifierFlags.Default */)) { return [clean, namespaceDecl]; } var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ModifierFlags.ExportDefault */) | 2 /* ModifierFlags.Ambient */); - var cleanDeclaration = factory.updateFunctionDeclaration(clean, - /*decorators*/ undefined, modifiers, + var cleanDeclaration = factory.updateFunctionDeclaration(clean, modifiers, /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, /*body*/ undefined); - var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, - /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body); + var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, modifiers, namespaceDecl.name, namespaceDecl.body); var exportDefaultDeclaration = factory.createExportAssignment( - /*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, namespaceDecl.name); if (ts.isSourceFile(input.parent)) { @@ -108862,8 +110417,7 @@ var ts; needsScopeFixMarker = oldNeedsScopeFix; resultHasScopeMarker = oldHasScopeFix; var mods = ensureModifiers(input); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); } else { needsDeclare = previousNeedsDeclare; @@ -108874,8 +110428,7 @@ var ts; var id = ts.getOriginalNodeId(inner); // TODO: GH#18217 var body = lateStatementReplacementMap.get(id); lateStatementReplacementMap.delete(id); - return cleanup(factory.updateModuleDeclaration(input, - /*decorators*/ undefined, mods, input.name, body)); + return cleanup(factory.updateModuleDeclaration(input, mods, input.name, body)); } } case 257 /* SyntaxKind.ClassDeclaration */: { @@ -108892,8 +110445,7 @@ var ts; return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 79 /* SyntaxKind.Identifier */) { - return preserveJsDoc(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + return preserveJsDoc(factory.createPropertyDeclaration(ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); } else { // Pattern - this is currently an error, but we emit declarations for it somewhat correctly @@ -108909,8 +110461,7 @@ var ts; elems = ts.concatenate(elems, walkBindingPattern(elem.name)); } elems = elems || []; - elems.push(factory.createPropertyDeclaration( - /*decorators*/ undefined, ensureModifiers(param), elem.name, + elems.push(factory.createPropertyDeclaration(ensureModifiers(param), elem.name, /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), /*initializer*/ undefined)); } @@ -108924,7 +110475,6 @@ var ts; // Prevents other classes with the same public members from being used in place of the current class var privateIdentifier = hasPrivateIdentifier ? [ factory.createPropertyDeclaration( - /*decorators*/ undefined, /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"), /*questionToken*/ undefined, /*type*/ undefined, @@ -108954,20 +110504,18 @@ var ts; } return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 104 /* SyntaxKind.NullKeyword */; })), visitDeclarationSubtree)); })); - return [statement, cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + return [statement, cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 } else { var heritageClauses = transformHeritageClauses(input.heritageClauses); - return cleanup(factory.updateClassDeclaration(input, - /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + return cleanup(factory.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members)); } } case 237 /* SyntaxKind.VariableStatement */: { return cleanup(transformVariableStatement(input)); } case 260 /* SyntaxKind.EnumDeclaration */: { - return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { + return cleanup(factory.updateEnumDeclaration(input, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; // Rewrite enum values to their constants, if available @@ -108977,7 +110525,7 @@ var ts; } } // Anything left unhandled is an error, so this should be unreachable - return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.SyntaxKind[input.kind])); + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.Debug.formatSyntaxKind(input.kind))); function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; @@ -109051,12 +110599,12 @@ var ts; var currentFlags = ts.getEffectiveModifierFlags(node); var newFlags = ensureModifierFlags(node); if (currentFlags === newFlags) { - return node.modifiers; + return ts.visitArray(node.modifiers, function (n) { return ts.tryCast(n, ts.isModifier); }, ts.isModifier); } return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 125951 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files + var mask = 257023 /* ModifierFlags.All */ ^ (4 /* ModifierFlags.Public */ | 256 /* ModifierFlags.Async */ | 16384 /* ModifierFlags.Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* ModifierFlags.Ambient */ : 0 /* ModifierFlags.None */; var parentIsFile = node.parent.kind === 305 /* SyntaxKind.SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { @@ -109097,7 +110645,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 125951 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } + if (modifierMask === void 0) { modifierMask = 257023 /* ModifierFlags.All */ ^ 4 /* ModifierFlags.Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* ModifierFlags.None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* ModifierFlags.Default */ && !(flags & 1 /* ModifierFlags.Export */)) { @@ -109219,6 +110767,7 @@ var ts; var transformers = []; ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory)); transformers.push(ts.transformTypeScript); + transformers.push(ts.transformLegacyDecorators); transformers.push(ts.transformClassFields); if (ts.getJSXTransformEnabled(compilerOptions)) { transformers.push(ts.transformJsx); @@ -109979,7 +111528,6 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; - var exportedModulesFromDeclarationEmit; // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); @@ -109989,7 +111537,6 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, - exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath; @@ -110043,14 +111590,16 @@ var ts; return; } var version = ts.version; // Extracted into a const so the form is stable between namespace and module - ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false); + var buildInfo = { bundle: bundle, program: program, version: version }; + // Pass buildinfo as additional data to avoid having to reparse + ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText(buildInfo), /*writeByteOrderMark*/ false, /*sourceFiles*/ undefined, { buildInfo: buildInfo }); } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) { if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) { return; } // Make sure not to write js file and source map file if any of them cannot be written - if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit) { emitSkipped = true; return; } @@ -110079,7 +111628,7 @@ var ts; substituteNode: transform.substituteNode, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); if (bundleBuildInfo) @@ -110115,7 +111664,7 @@ var ts; noEmitHelpers: true, module: compilerOptions.module, target: compilerOptions.target, - sourceMap: compilerOptions.sourceMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, inlineSourceMap: compilerOptions.inlineSourceMap, extendedDiagnostics: compilerOptions.extendedDiagnostics, onlyPrintJsDocStyle: true, @@ -110135,17 +111684,13 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: !forceDtsEmit && compilerOptions.declarationMap, + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform, declarationPrinter, { + sourceMap: printerOptions.sourceMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 305 /* SyntaxKind.SourceFile */) { - var sourceFile = declarationTransform.transformed[0]; - exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; - } } declarationTransform.dispose(); if (bundleBuildInfo) @@ -110164,7 +111709,8 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, mapOptions) { + var sourceFileOrBundle = transform.transformed[0]; var bundle = sourceFileOrBundle.kind === 306 /* SyntaxKind.Bundle */ ? sourceFileOrBundle : undefined; var sourceFile = sourceFileOrBundle.kind === 305 /* SyntaxKind.SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; @@ -110197,13 +111743,20 @@ var ts; if (sourceMapFilePath) { var sourceMap = sourceMapGenerator.toString(); ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles); + if (printer.bundleFileInfo) + printer.bundleFileInfo.mapHash = ts.computeSignature(sourceMap, ts.maybeBind(host, host.createHash)); } } else { writer.writeLine(); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos }); + var text = writer.getText(); + ts.writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos: sourceMapUrlPos, diagnostics: transform.diagnostics }); + // We store the hash of the text written in the buildinfo to ensure that text of the referenced d.ts file is same as whats in the buildinfo + // This is needed because incremental can be toggled between two runs and we might use stale file text to do text manipulation in prepend mode + if (printer.bundleFileInfo) + printer.bundleFileInfo.hash = ts.computeSignature(text, ts.maybeBind(host, host.createHash)); // Reset state writer.clear(); } @@ -110346,34 +111899,56 @@ var ts; } /*@internal*/ function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) { + var createHash = ts.maybeBind(host, host.createHash); var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath)); - if (!buildInfoText) + var buildInfo; + if (host.getBuildInfo) { + // If host directly provides buildinfo we can get it directly. This allows host to cache the buildinfo + var hostBuildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); + if (!hostBuildInfo) + return buildInfoPath; + buildInfo = hostBuildInfo; + } + else { + var buildInfoText = host.readFile(buildInfoPath); + if (!buildInfoText) + return buildInfoPath; + buildInfo = getBuildInfo(buildInfoText); + } + if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationFilePath && !buildInfo.bundle.dts)) return buildInfoPath; var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath)); if (!jsFileText) return jsFilePath; + // If the jsFileText is not same has what it was created with, tsbuildinfo is stale so dont use it + if (ts.computeSignature(jsFileText, createHash) !== buildInfo.bundle.js.hash) + return jsFilePath; var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); // error if no source map or for now if inline sourcemap if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap) return sourceMapFilePath || "inline sourcemap decoding"; + if (sourceMapFilePath && ts.computeSignature(sourceMapText, createHash) !== buildInfo.bundle.js.mapHash) + return sourceMapFilePath; // read declaration text var declarationText = declarationFilePath && host.readFile(declarationFilePath); if (declarationFilePath && !declarationText) return declarationFilePath; + if (declarationFilePath && ts.computeSignature(declarationText, createHash) !== buildInfo.bundle.dts.hash) + return declarationFilePath; var declarationMapText = declarationMapPath && host.readFile(declarationMapPath); // error if no source map or for now if inline sourcemap if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding"; - var buildInfo = getBuildInfo(buildInfoText); - if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts)) - return buildInfoPath; + if (declarationMapPath && ts.computeSignature(declarationMapText, createHash) !== buildInfo.bundle.dts.mapHash) + return declarationMapPath; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, /*onlyOwnText*/ true); var outputFiles = []; var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); }); var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host); + var changedDtsText; + var changedDtsData; var emitHost = { getPrependNodes: ts.memoize(function () { return __spreadArray(__spreadArray([], prependNodes, true), [ownPrependInput], false); }), getCanonicalFileName: host.getCanonicalFileName, @@ -110389,7 +111964,7 @@ var ts; getResolvedProjectReferenceToRedirect: ts.returnUndefined, getProjectReferenceRedirect: ts.returnUndefined, isSourceOfProjectReferenceRedirect: ts.returnFalse, - writeFile: function (name, text, writeByteOrderMark) { + writeFile: function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { switch (name) { case jsFilePath: if (jsFileText === text) @@ -110400,8 +111975,12 @@ var ts; return; break; case buildInfoPath: - var newBuildInfo = getBuildInfo(text); + var newBuildInfo = data.buildInfo; newBuildInfo.program = buildInfo.program; + if (newBuildInfo.program && changedDtsText !== undefined && config.options.composite) { + // Update the output signature + newBuildInfo.program.outSignature = ts.computeSignature(changedDtsText, createHash, changedDtsData); + } // Update sourceFileInfo var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles; newBuildInfo.bundle.js.sources = js.sources; @@ -110409,11 +111988,13 @@ var ts; newBuildInfo.bundle.dts.sources = dts.sources; } newBuildInfo.bundle.sourceFiles = sourceFiles; - outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark }); + outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark, buildInfo: newBuildInfo }); return; case declarationFilePath: if (declarationText === text) return; + changedDtsText = text; + changedDtsData = data; break; case declarationMapPath: if (declarationMapText === text) @@ -110432,6 +112013,7 @@ var ts; getSourceFileFromReference: ts.returnUndefined, redirectTargetsMap: ts.createMultiMap(), getFileIncludeReasons: ts.notImplemented, + createHash: createHash, }; emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers)); @@ -111519,8 +113101,7 @@ var ts; } } function emitParameter(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); @@ -111531,7 +113112,7 @@ var ts; emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); @@ -111541,7 +113122,6 @@ var ts; // Type members // function emitPropertySignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); @@ -111549,8 +113129,7 @@ var ts; writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); emit(node.exclamationToken); @@ -111560,7 +113139,6 @@ var ts; } function emitMethodSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emit(node.questionToken); @@ -111571,16 +113149,13 @@ var ts; popNameGenerationScope(node); } function emitMethodDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); emit(node.asteriskToken); emit(node.name); emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitClassStaticBlockDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("static"); emitBlockFunctionBody(node.body); } @@ -111590,8 +113165,7 @@ var ts; emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword(node.kind === 172 /* SyntaxKind.GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); @@ -111599,8 +113173,6 @@ var ts; } function emitCallSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); @@ -111609,8 +113181,6 @@ var ts; } function emitConstructSignature(node) { pushNameGenerationScope(node); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -111620,7 +113190,6 @@ var ts; popNameGenerationScope(node); } function emitIndexSignature(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); @@ -112013,7 +113582,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitSignatureAndBody(node, emitArrowFunctionHead); } @@ -112494,7 +114062,6 @@ var ts; emitFunctionDeclarationOrExpression(node); } function emitFunctionDeclarationOrExpression(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); emit(node.asteriskToken); @@ -112552,8 +114119,8 @@ var ts; if (!ts.nodeIsSynthesized(body) && currentSourceFile && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { return false; } - if (getLeadingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */) - || getClosingLineTerminatorCount(body, body.statements, 2 /* ListFormat.PreserveLines */)) { + if (getLeadingLineTerminatorCount(body, ts.firstOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */) + || getClosingLineTerminatorCount(body, ts.lastOrUndefined(body.statements), 2 /* ListFormat.PreserveLines */, body.statements)) { return false; } var previousStatement; @@ -112601,8 +114168,7 @@ var ts; } function emitClassDeclarationOrExpression(node) { ts.forEach(node.members, generateMemberNames); - emitDecorators(node, node.decorators); - emitModifiers(node, node.modifiers); + emitDecoratorsAndModifiers(node, node.modifiers); writeKeyword("class"); if (node.name) { writeSpace(); @@ -112623,7 +114189,6 @@ var ts; } } function emitInterfaceDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("interface"); writeSpace(); @@ -112636,7 +114201,6 @@ var ts; writePunctuation("}"); } function emitTypeAliasDeclaration(node) { - emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("type"); writeSpace(); @@ -113263,8 +114827,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* BundleFileSectionKind.Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_24 = types; _d < types_24.length; _d++) { - var directive = types_24[_d]; + for (var _d = 0, types_23 = types; _d < types_23.length; _d++) { + var directive = types_23[_d]; var pos = writer.getTextPos(); var resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.impliedNodeFormat) ? "resolution-mode=\"".concat(directive.resolutionMode === ts.ModuleKind.ESNext ? "import" : "require", "\"") @@ -113438,12 +115002,52 @@ var ts; emit(node); write = savedWrite; } - function emitModifiers(node, modifiers) { - if (modifiers && modifiers.length) { - emitList(node, modifiers, 262656 /* ListFormat.Modifiers */); - writeSpace(); + function emitDecoratorsAndModifiers(node, modifiers) { + if (modifiers === null || modifiers === void 0 ? void 0 : modifiers.length) { + if (ts.every(modifiers, ts.isModifier)) { + // if all modifier-likes are `Modifier`, simply emit the array as modifiers. + return emitModifiers(node, modifiers); + } + if (ts.every(modifiers, ts.isDecorator)) { + // if all modifier-likes are `Decorator`, simply emit the array as decorators. + return emitDecorators(node, modifiers); + } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(modifiers); + // partition modifiers into contiguous chunks of `Modifier` or `Decorator` + var lastMode = void 0; + var mode = void 0; + var start = 0; + var pos = 0; + while (start < modifiers.length) { + while (pos < modifiers.length) { + var modifier = modifiers[pos]; + mode = ts.isDecorator(modifier) ? "decorators" : "modifiers"; + if (lastMode === undefined) { + lastMode = mode; + } + else if (mode !== lastMode) { + break; + } + pos++; + } + var textRange = { pos: -1, end: -1 }; + if (start === 0) + textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) + textRange.end = modifiers.end; + emitNodeListItems(emit, node, modifiers, lastMode === "modifiers" ? 2359808 /* ListFormat.Modifiers */ : 2146305 /* ListFormat.Decorators */, + /*parenthesizerRule*/ undefined, start, pos - start, + /*hasTrailingComma*/ false, textRange); + start = pos; + lastMode = mode; + pos++; + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(modifiers); } } + function emitModifiers(node, modifiers) { + emitList(node, modifiers, 2359808 /* ListFormat.Modifiers */); + } function emitTypeAnnotation(node) { if (node) { writePunctuation(":"); @@ -113521,11 +115125,9 @@ var ts; && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head && !parentNode.type // arrow function may not have return type annotation - && !ts.some(parentNode.decorators) // parent may not have decorators - && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.modifiers) // parent may not have decorators or modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters - && !ts.some(parameter.decorators) // parameter may not have decorators - && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !ts.some(parameter.modifiers) // parameter may not have decorators or modifiers && !parameter.dotDotDotToken // parameter may not be rest && !parameter.questionToken // parameter may not be optional && !parameter.type // parameter may not have a type annotation @@ -113580,12 +115182,8 @@ var ts; } var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 32768 /* ListFormat.OptionalIfEmpty */) { - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); return; } if (format & 15360 /* ListFormat.BracketsMask */) { @@ -113594,9 +115192,7 @@ var ts; emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } - if (onBeforeEmitNodeArray) { - onBeforeEmitNodeArray(children); - } + onBeforeEmitNodeArray === null || onBeforeEmitNodeArray === void 0 ? void 0 : onBeforeEmitNodeArray(children); if (isEmpty) { // Write a line terminator if the parent node was multi-line if (format & 1 /* ListFormat.MultiLine */ && !(preserveSourceNewlines && (!parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { @@ -113607,123 +115203,128 @@ var ts; } } else { - ts.Debug.type(children); - // Write the opening line terminator or leading whitespace. - var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; - var shouldEmitInterveningComments = mayEmitInterveningComments; - var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217 - if (leadingLineTerminatorCount) { - writeLine(leadingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { - writeSpace(); - } - // Increase the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { - increaseIndent(); + emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, children.hasTrailingComma, children); + } + onAfterEmitNodeArray === null || onAfterEmitNodeArray === void 0 ? void 0 : onAfterEmitNodeArray(children); + if (format & 15360 /* ListFormat.BracketsMask */) { + if (isEmpty && children) { + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } - var emitListItem = getEmitListItem(emit, parenthesizerRule); - // Emit each child. - var previousSibling = void 0; - var previousSourceFileTextKind = void 0; - var shouldDecreaseIndentAfterEmit = false; - for (var i = 0; i < count; i++) { - var child = children[start + i]; - // Write the delimiter if this is not the first node. - if (format & 32 /* ListFormat.AsteriskDelimited */) { - // always write JSDoc in the format "\n *" - writeLine(); - writeDelimiter(format); - } - else if (previousSibling) { - // i.e - // function commentedParameters( - // /* Parameter a */ - // a - // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline - // , - if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { - emitLeadingCommentsOfPosition(previousSibling.end); - } - writeDelimiter(format); - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write either a line terminator or whitespace to separate the elements. - var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); - if (separatingLineTerminatorCount > 0) { - // If a synthesized node in a single-line list starts on a new - // line, we should increase the indent. - if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { - increaseIndent(); - shouldDecreaseIndentAfterEmit = true; - } - writeLine(separatingLineTerminatorCount); - shouldEmitInterveningComments = false; - } - else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { - writeSpace(); - } - } - // Emit this child. - previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); - if (shouldEmitInterveningComments) { - var commentRange = ts.getCommentRange(child); - emitTrailingCommentsOfPosition(commentRange.pos); - } - else { - shouldEmitInterveningComments = mayEmitInterveningComments; - } - nextListElementPos = child.pos; - emitListItem(child, emit, parenthesizerRule, i); - if (shouldDecreaseIndentAfterEmit) { - decreaseIndent(); - shouldDecreaseIndentAfterEmit = false; + writePunctuation(getClosingBracket(format)); + } + } + /** + * Emits a list without brackets or raising events. + * + * NOTE: You probably don't want to call this directly and should be using `emitList` or `emitExpressionList` instead. + */ + function emitNodeListItems(emit, parentNode, children, format, parenthesizerRule, start, count, hasTrailingComma, childrenTextRange) { + // Write the opening line terminator or leading whitespace. + var mayEmitInterveningComments = (format & 262144 /* ListFormat.NoInterveningComments */) === 0; + var shouldEmitInterveningComments = mayEmitInterveningComments; + var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children[start], format); + if (leadingLineTerminatorCount) { + writeLine(leadingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (format & 256 /* ListFormat.SpaceBetweenBraces */) { + writeSpace(); + } + // Increase the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + increaseIndent(); + } + var emitListItem = getEmitListItem(emit, parenthesizerRule); + // Emit each child. + var previousSibling; + var previousSourceFileTextKind; + var shouldDecreaseIndentAfterEmit = false; + for (var i = 0; i < count; i++) { + var child = children[start + i]; + // Write the delimiter if this is not the first node. + if (format & 32 /* ListFormat.AsteriskDelimited */) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (format & 60 /* ListFormat.DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + writeDelimiter(format); + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write either a line terminator or whitespace to separate the elements. + var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); + if (separatingLineTerminatorCount > 0) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (3 /* ListFormat.LinesMask */ | 128 /* ListFormat.Indented */)) === 0 /* ListFormat.SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(separatingLineTerminatorCount); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & 512 /* ListFormat.SpaceBetweenSiblings */) { + writeSpace(); } - previousSibling = child; } - // Write a trailing comma, if requested. - var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; - var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); - var hasTrailingComma = (children === null || children === void 0 ? void 0 : children.hasTrailingComma) && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); - if (hasTrailingComma) { - if (previousSibling && !skipTrailingComments) { - emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); - } - else { - writePunctuation(","); - } + // Emit this child. + previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); + if (shouldEmitInterveningComments) { + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); } - // Emit any trailing comment of the last element in the list - // i.e - // var array = [... - // 2 - // /* end of element 2 */ - // ]; - if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { - emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); + else { + shouldEmitInterveningComments = mayEmitInterveningComments; } - // Decrease the indent, if requested. - if (format & 128 /* ListFormat.Indented */) { + nextListElementPos = child.pos; + emitListItem(child, emit, parenthesizerRule, i); + if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; } - recordBundleFileInternalSectionEnd(previousSourceFileTextKind); - // Write the closing line terminator or closing whitespace. - var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format); - if (closingLineTerminatorCount) { - writeLine(closingLineTerminatorCount); + previousSibling = child; + } + // Write a trailing comma, if requested. + var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0; + var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* EmitFlags.NoTrailingComments */); + var emitTrailingComma = hasTrailingComma && (format & 64 /* ListFormat.AllowTrailingComma */) && (format & 16 /* ListFormat.CommaDelimited */); + if (emitTrailingComma) { + if (previousSibling && !skipTrailingComments) { + emitTokenWithComment(27 /* SyntaxKind.CommaToken */, previousSibling.end, writePunctuation, previousSibling); } - else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { - writeSpace(); + else { + writePunctuation(","); } } - if (onAfterEmitNodeArray) { - onAfterEmitNodeArray(children); + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* ListFormat.DelimitersMask */) && !skipTrailingComments) { + emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange === null || childrenTextRange === void 0 ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end); } - if (format & 15360 /* ListFormat.BracketsMask */) { - if (isEmpty && children) { - emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists - } - writePunctuation(getClosingBracket(format)); + // Decrease the indent, if requested. + if (format & 128 /* ListFormat.Indented */) { + decreaseIndent(); + } + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + // Write the closing line terminator or closing whitespace. + var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children[start + count - 1], format, childrenTextRange); + if (closingLineTerminatorCount) { + writeLine(closingLineTerminatorCount); + } + else if (format & (2097152 /* ListFormat.SpaceAfterList */ | 256 /* ListFormat.SpaceBetweenBraces */)) { + writeSpace(); } } // Writers @@ -113853,16 +115454,15 @@ var ts; decreaseIndent(); } } - function getLeadingLineTerminatorCount(parentNode, children, format) { + function getLeadingLineTerminatorCount(parentNode, firstChild, format) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var firstChild_1 = children[0]; - if (firstChild_1 === undefined) { + if (firstChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (firstChild_1.pos === nextListElementPos) { + if (firstChild.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading // line terminators have already been written as the separating line terminators of the // parent list. Example: @@ -113880,20 +115480,20 @@ var ts; // leading newline to start the modifiers. return 0; } - if (firstChild_1.kind === 11 /* SyntaxKind.JsxText */) { + if (firstChild.kind === 11 /* SyntaxKind.JsxText */) { // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && - !ts.nodeIsSynthesized(firstChild_1) && - (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { + !ts.nodeIsSynthesized(firstChild) && + (!firstChild.parent || ts.getOriginalNode(firstChild.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild.pos, parentNode.pos, currentSourceFile, includeComments); }); } - return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; + return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; } - if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) { + if (synthesizedNodeStartsOnNewLine(firstChild, format)) { return 1; } } @@ -113933,18 +115533,17 @@ var ts; } return format & 1 /* ListFormat.MultiLine */ ? 1 : 0; } - function getClosingLineTerminatorCount(parentNode, children, format) { + function getClosingLineTerminatorCount(parentNode, lastChild, format, childrenTextRange) { if (format & 2 /* ListFormat.PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* ListFormat.PreferNewLine */) { return 1; } - var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { return !parentNode || currentSourceFile && ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (currentSourceFile && parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { - var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; + var end_1 = childrenTextRange && !ts.positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; @@ -113982,14 +115581,14 @@ var ts; return lines; } function writeLineSeparatorsAndIndentBefore(node, parent) { - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, node, 0 /* ListFormat.None */); if (leadingNewlines) { writeLinesAndIndent(leadingNewlines, /*writeSpaceIfNotIndenting*/ false); } return !!leadingNewlines; } function writeLineSeparatorsAfter(node, parent) { - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* ListFormat.None */); + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, node, 0 /* ListFormat.None */, /*childrenTextRange*/ undefined); if (trailingNewlines) { writeLine(trailingNewlines); } @@ -115516,12 +117115,10 @@ var ts; } ts.createCompilerHost = createCompilerHost; /*@internal*/ - // TODO(shkamat): update this after reworking ts build API function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = new ts.Map(); var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); - var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash; function getSourceFile(fileName, languageVersionOrOptions, onError) { var text; try { @@ -115554,7 +117151,7 @@ var ts; // NOTE: If patchWriteFileEnsuringDirectory has been called, // the system.writeFile will do its own directory creation and // the ensureDirectoriesExist call will always be redundant. - ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return writeFileWorker(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); + ts.writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, function (path) { return (compilerHost.createDirectory || system.createDirectory)(path); }, function (path) { return directoryExists(path); }); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } @@ -115564,35 +117161,6 @@ var ts; } } } - var outputFingerprints; - function writeFileWorker(fileName, data, writeByteOrderMark) { - if (!ts.isWatchSet(options) || !system.getModifiedTime) { - system.writeFile(fileName, data, writeByteOrderMark); - return; - } - if (!outputFingerprints) { - outputFingerprints = new ts.Map(); - } - var hash = computeHash(data); - var mtimeBefore = system.getModifiedTime(fileName); - if (mtimeBefore) { - var fingerprint = outputFingerprints.get(fileName); - // If output has not been changed, and the file has no external modification - if (fingerprint && - fingerprint.byteOrderMark === writeByteOrderMark && - fingerprint.hash === hash && - fingerprint.mtime.getTime() === mtimeBefore.getTime()) { - return; - } - } - system.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; - outputFingerprints.set(fileName, { - hash: hash, - byteOrderMark: writeByteOrderMark, - mtime: mtimeAfter - }); - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } @@ -115699,7 +117267,7 @@ var ts; }; } // directoryExists - if (originalDirectoryExists && originalCreateDirectory) { + if (originalDirectoryExists) { host.directoryExists = function (directory) { var key = toPath(directory); var value = directoryExistsCache.get(key); @@ -115709,11 +117277,13 @@ var ts; directoryExistsCache.set(key, !!newValue); return newValue; }; - host.createDirectory = function (directory) { - var key = toPath(directory); - directoryExistsCache.delete(key); - originalCreateDirectory.call(host, directory); - }; + if (originalCreateDirectory) { + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } } return { originalReadFile: originalReadFile, @@ -115934,12 +117504,14 @@ var ts; } ts.loadWithTypeDirectiveCache = loadWithTypeDirectiveCache; ; - /* @internal */ + /** + * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly + * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. + */ function getModeForFileReference(ref, containingFileMode) { return (ts.isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode; } ts.getModeForFileReference = getModeForFileReference; - /* @internal */ function getModeForResolutionAtIndex(file, index) { if (file.impliedNodeFormat === undefined) return undefined; @@ -115960,7 +117532,15 @@ var ts; return false; } ts.isExclusivelyTypeOnlyImportOrExport = isExclusivelyTypeOnlyImportOrExport; - /* @internal */ + /** + * Calculates the final resolution mode for a given module reference node. This is generally the explicitly provided resolution mode, if + * one exists, or the mode of the containing source file. (Excepting import=require, which is always commonjs, and dynamic import, which is always esm). + * Notably, this function always returns `undefined` if the containing file has an `undefined` `impliedNodeFormat` - this field is only set when + * `moduleResolution` is `node16`+. + * @param file The file the import or import-like reference is contained within + * @param usage The module reference string + * @returns The final resolution mode of the import + */ function getModeForUsageLocation(file, usage) { var _a, _b; if (file.impliedNodeFormat === undefined) @@ -116206,6 +117786,12 @@ var ts; * @returns `undefined` if the path has no relevant implied format, `ModuleKind.ESNext` for esm format, and `ModuleKind.CommonJS` for cjs format */ function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, options) { + var result = getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options); + return typeof result === "object" ? result.impliedNodeFormat : result; + } + ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + /*@internal*/ + function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) { switch (ts.getEmitModuleResolutionKind(options)) { case ts.ModuleResolutionKind.Node16: case ts.ModuleResolutionKind.NodeNext: @@ -116217,11 +117803,16 @@ var ts; return undefined; } function lookupFromPackageJson() { - var scope = ts.getPackageScopeForPath(fileName, packageJsonInfoCache, host, options); - return (scope === null || scope === void 0 ? void 0 : scope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + var state = ts.getTemporaryModuleResolutionState(packageJsonInfoCache, host, options); + var packageJsonLocations = []; + state.failedLookupLocations = packageJsonLocations; + state.affectingLocations = packageJsonLocations; + var packageJsonScope = ts.getPackageScopeForPath(fileName, state); + var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS; + return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope }; } } - ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + ts.getImpliedNodeFormatForFileWorker = getImpliedNodeFormatForFileWorker; /** @internal */ ts.plainJSErrors = new ts.Set([ // binder errors @@ -116314,6 +117905,9 @@ var ts; ts.Diagnostics.extends_clause_already_seen.code, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + ts.Diagnostics.Class_constructor_may_not_be_a_generator.code, + ts.Diagnostics.Class_constructor_may_not_be_an_accessor.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]); /** * Determine if source file needs to be re-created even if its text hasn't changed @@ -116543,7 +118137,7 @@ var ts; for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { var oldSourceFile = oldSourceFiles_1[_i]; var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); - if (shouldCreateNewSourceFile || !newFile || + if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // old file wasn't redirect but new file is (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); @@ -116880,7 +118474,7 @@ var ts; // `result[i]` is either a `ResolvedModuleFull` or a marker. // If it is the former, we can leave it as is. if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; // TODO: GH#18217 + result[i] = undefined; } } else { @@ -116936,7 +118530,7 @@ var ts; }); } function tryReuseStructureFromOldProgram() { - var _a; + var _a, _b; if (!oldProgram) { return 0 /* StructureIsReused.Not */; } @@ -116977,12 +118571,15 @@ var ts; var seenPackageNames = new ts.Map(); for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; + var sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options); var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options), /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat) + : host.getSourceFile(oldSourceFile.fileName, sourceFileOptions, /*onError*/ undefined, shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat); // TODO: GH#18217 if (!newSourceFile) { return 0 /* StructureIsReused.Not */; } + newSourceFile.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope; ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); var fileChanged = void 0; if (oldSourceFile.redirectInfo) { @@ -117022,38 +118619,43 @@ var ts; seenPackageNames.set(packageName, newKind); } if (fileChanged) { + if (oldSourceFile.impliedNodeFormat !== newSourceFile.impliedNodeFormat) { + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } // The `newSourceFile` object was created for the new program. - if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { // 'lib' references has changed. Matches behavior in changesAffectModuleResolution structureIsReused = 1 /* StructureIsReused.SafeModules */; } - if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + else if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files structureIsReused = 1 /* StructureIsReused.SafeModules */; } // check tripleslash references - if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + else if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed structureIsReused = 1 /* StructureIsReused.SafeModules */; } - // check imports and module augmentations - collectExternalModuleReferences(newSourceFile); - if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - // imports has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - // moduleAugmentations has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { - // dynamicImport has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - // 'types' references has changed - structureIsReused = 1 /* StructureIsReused.SafeModules */; + else { + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if ((oldSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* NodeFlags.PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } + else if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + structureIsReused = 1 /* StructureIsReused.SafeModules */; + } } // tentatively approve the file modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); @@ -117071,18 +118673,18 @@ var ts; return structureIsReused; } var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; }); - for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) { - var oldFile = oldSourceFiles_3[_b]; + for (var _c = 0, oldSourceFiles_3 = oldSourceFiles; _c < oldSourceFiles_3.length; _c++) { + var oldFile = oldSourceFiles_3[_c]; if (!ts.contains(modifiedFiles, oldFile)) { - for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) { - var moduleName = _d[_c]; + for (var _d = 0, _e = oldFile.ambientModuleNames; _d < _e.length; _d++) { + var moduleName = _e[_d]; ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); } } } // try to verify results of module resolution - for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) { - var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile; + for (var _f = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _f < modifiedSourceFiles_1.length; _f++) { + var _g = modifiedSourceFiles_1[_f], oldSourceFile = _g.oldFile, newSourceFile = _g.newFile; var moduleNames = getModuleNames(newSourceFile); var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); // ensure that module resolution results are still correct @@ -117109,14 +118711,14 @@ var ts; if (structureIsReused !== 2 /* StructureIsReused.Completely */) { return structureIsReused; } - if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host))) { + if (ts.changesAffectingProgramStructure(oldOptions, options) || ((_b = host.hasChangedAutomaticTypeDirectiveNames) === null || _b === void 0 ? void 0 : _b.call(host))) { return 1 /* StructureIsReused.SafeModules */; } missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); - for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) { - var newSourceFile = newSourceFiles_1[_g]; + for (var _h = 0, newSourceFiles_1 = newSourceFiles; _h < newSourceFiles_1.length; _h++) { + var newSourceFile = newSourceFiles_1[_h]; filesByName.set(newSourceFile.path, newSourceFile); } var oldFilesByNameMap = oldProgram.getFilesByNameMap(); @@ -117178,6 +118780,7 @@ var ts; getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); }, redirectTargetsMap: redirectTargetsMap, getFileIncludeReasons: program.getFileIncludeReasons, + createHash: ts.maybeBind(host, host.createHash), }; } function writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data) { @@ -117531,7 +119134,7 @@ var ts; } } function walkArray(nodes, parent) { - if (parent.decorators === nodes && !options.experimentalDecorators) { + if (ts.canHaveModifiers(parent) && parent.modifiers === nodes && ts.some(nodes, ts.isDecorator) && !options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { @@ -117562,7 +119165,7 @@ var ts; if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; - if (modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { + if (ts.isModifier(modifier) && modifier.kind !== 124 /* SyntaxKind.StaticKeyword */) { diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); } } @@ -117571,7 +119174,7 @@ var ts; break; case 164 /* SyntaxKind.Parameter */: // Check modifiers of parameter declaration - if (nodes === parent.modifiers) { + if (nodes === parent.modifiers && ts.some(nodes, ts.isModifier)) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -117690,7 +119293,7 @@ var ts; } function createSyntheticImport(text, file) { var externalHelpersModuleReference = ts.factory.createStringLiteral(text); - var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); + var importDecl = ts.factory.createImportDeclaration(/*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined); ts.addEmitFlags(importDecl, 67108864 /* EmitFlags.NeverApplyImportHelper */); ts.setParent(externalHelpersModuleReference, importDecl); ts.setParent(importDecl, file); @@ -117898,13 +119501,16 @@ var ts; addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) { + var _a; var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; redirect.resolvedPath = resolvedPath; redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + redirect.packageJsonLocations = ((_a = sourceFileOptions.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) ? sourceFileOptions.packageJsonLocations : undefined; + redirect.packageJsonScope = sourceFileOptions.packageJsonScope; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { @@ -117933,14 +119539,14 @@ var ts; // It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache // and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way // to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront. - var impliedNodeFormat = getImpliedNodeFormatForFile(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); - return { - languageVersion: ts.getEmitScriptTarget(options), - impliedNodeFormat: impliedNodeFormat, - setExternalModuleIndicator: ts.getSetExternalModuleIndicator(options) - }; + var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options); + var languageVersion = ts.getEmitScriptTarget(options); + var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options); + return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) : + { languageVersion: languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator }; } function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { + var _a, _b; var path = toPath(fileName); if (useSourceOfProjectReferenceRedirect) { var source = getSourceOfProjectReferenceRedirect(path); @@ -118027,14 +119633,15 @@ var ts; } } // We haven't looked for this file, do so now and cache result - var file = host.getSourceFile(fileName, getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options), function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile); + var sourceFileOptions = getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options); + var file = host.getSourceFile(fileName, sourceFileOptions, function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile || (((_a = oldProgram === null || oldProgram === void 0 ? void 0 : oldProgram.getSourceFileByPath(toPath(fileName))) === null || _a === void 0 ? void 0 : _a.impliedNodeFormat) !== sourceFileOptions.impliedNodeFormat)); if (packageId) { var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName, sourceFileOptions); redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, redirectedPath); addFileIncludeReason(dupFile, reason); @@ -118055,6 +119662,8 @@ var ts; file.path = path; file.resolvedPath = toPath(fileName); file.originalFileName = originalFileName; + file.packageJsonLocations = ((_b = sourceFileOptions.packageJsonLocations) === null || _b === void 0 ? void 0 : _b.length) ? sourceFileOptions.packageJsonLocations : undefined; + file.packageJsonScope = sourceFileOptions.packageJsonScope; addFileIncludeReason(file, reason); if (host.useCaseSensitiveFileNames()) { var pathLowerCase = ts.toFileNameLowerCase(path); @@ -118194,13 +119803,13 @@ var ts; ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); var mode = ref.resolutionMode || file.impliedNodeFormat; if (mode && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { - programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); + programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext)); } processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, }); } } function processTypeReferenceDirective(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -118685,7 +120294,7 @@ var ts; fileIncludeReasons = undefined; var location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason); var fileIncludeReasonDetails = fileIncludeReasons && ts.chainDiagnosticMessages(fileIncludeReasons, ts.Diagnostics.The_file_is_in_the_program_because_Colon); - var redirectInfo = file && ts.explainIfFileIsRedirect(file); + var redirectInfo = file && ts.explainIfFileIsRedirectAndImpliedFormat(file); var chain = ts.chainDiagnosticMessages.apply(void 0, __spreadArray([redirectInfo ? fileIncludeReasonDetails ? __spreadArray([fileIncludeReasonDetails], redirectInfo, true) : redirectInfo : fileIncludeReasonDetails, diagnostic], args || ts.emptyArray, false)); return location && isReferenceFileLocation(location) ? ts.createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : @@ -118755,7 +120364,7 @@ var ts; } var matchedByInclude = ts.getMatchedIncludeSpec(program, fileName); // Could be additional files specified as roots - if (!matchedByInclude) + if (!matchedByInclude || !ts.isString(matchedByInclude)) return undefined; configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude); message = ts.Diagnostics.File_is_matched_by_include_pattern_specified_here; @@ -119279,8 +120888,8 @@ var ts; (function (ts) { function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) { var outputFiles = []; - var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit; - return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; + var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics; + return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -119291,13 +120900,9 @@ var ts; function createManyToManyPathMap() { function create(forward, reverse, deleted) { var map = { - clone: function () { return create(new ts.Map(forward), new ts.Map(reverse), deleted && new ts.Set(deleted)); }, - forEach: function (fn) { return forward.forEach(fn); }, getKeys: function (v) { return reverse.get(v); }, getValues: function (k) { return forward.get(k); }, - hasKey: function (k) { return forward.has(k); }, keys: function () { return forward.keys(); }, - deletedKeys: function () { return deleted; }, deleteKey: function (k) { (deleted || (deleted = new ts.Set())).add(k); var set = forward.get(k); @@ -119324,11 +120929,6 @@ var ts; }); return map; }, - clear: function () { - forward.clear(); - reverse.clear(); - deleted === null || deleted === void 0 ? void 0 : deleted.clear(); - } }; return map; } @@ -119456,18 +121056,21 @@ var ts; * Creates the state of file references and signature for the new program from oldState if it is safe */ function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b, _c; var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? createManyToManyPathMap() : undefined; var exportedModulesMap = referencedMap ? createManyToManyPathMap() : undefined; - var hasCalledUpdateShapeSignature = new ts.Set(); var useOldState = canReuseOldState(referencedMap, oldState); // Ensure source files have parent pointers set newProgram.getTypeChecker(); // Create the reference map, and set the file infos - for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + for (var _i = 0, _d = newProgram.getSourceFiles(); _i < _d.length; _i++) { + var sourceFile = _d[_i]; var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); - var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined; + var oldUncommittedSignature = useOldState ? (_a = oldState.oldSignatures) === null || _a === void 0 ? void 0 : _a.get(sourceFile.resolvedPath) : undefined; + var signature = oldUncommittedSignature === undefined ? + useOldState ? (_b = oldState.fileInfos.get(sourceFile.resolvedPath)) === null || _b === void 0 ? void 0 : _b.signature : undefined : + oldUncommittedSignature || undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); if (newReferences) { @@ -119475,19 +121078,26 @@ var ts; } // Copy old visible to outside files map if (useOldState) { - var exportedModules = oldState.exportedModulesMap.getValues(sourceFile.resolvedPath); + var oldUncommittedExportedModules = (_c = oldState.oldExportedModulesMap) === null || _c === void 0 ? void 0 : _c.get(sourceFile.resolvedPath); + var exportedModules = oldUncommittedExportedModules === undefined ? + oldState.exportedModulesMap.getValues(sourceFile.resolvedPath) : + oldUncommittedExportedModules || undefined; if (exportedModules) { exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, impliedFormat: sourceFile.impliedNodeFormat }); + fileInfos.set(sourceFile.resolvedPath, { + version: version_2, + signature: signature, + affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, + impliedFormat: sourceFile.impliedNodeFormat + }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } @@ -119501,120 +121111,95 @@ var ts; } BuilderState.releaseCache = releaseCache; /** - * Creates a clone of the state + * Gets the files affected by the path from the program */ - function clone(state) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var _a, _b; - // Dont need to backup allFiles info since its cache anyway - return { - fileInfos: new ts.Map(state.fileInfos), - referencedMap: (_a = state.referencedMap) === null || _a === void 0 ? void 0 : _a.clone(), - exportedModulesMap: (_b = state.exportedModulesMap) === null || _b === void 0 ? void 0 : _b.clone(), - hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), - useFileVersionAsSignature: state.useFileVersionAsSignature, - }; + var result = getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); + return result; } - BuilderState.clone = clone; - /** - * Gets the files affected by the path from the program - */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { - // Since the operation could be cancelled, the signatures are always stored in the cache - // They will be committed once it is safe to use them - // eg when calling this api from tsserver, if there is no cancellation of the operation - // In the other cases the affected files signatures are committed only after the iteration through the result is complete - var signatureCache = cacheToUpdateSignature || new ts.Map(); + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash, getCanonicalFileName) { var sourceFile = programOfThisState.getSourceFileByPath(path); if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); - if (!cacheToUpdateSignature) { - // Commit all the signatures in the signature cache - updateSignaturesFromCache(state, signatureCache); - } - return result; - } - BuilderState.getFilesAffectedBy = getFilesAffectedBy; - /** - * Updates the signatures from the cache into state's fileinfo signatures - * This should be called whenever it is safe to commit the state of the builder - */ - function updateSignaturesFromCache(state, signatureCache) { - signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); }); + return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName); } - BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + BuilderState.getFilesAffectedByWithOldState = getFilesAffectedByWithOldState; function updateSignatureOfFile(state, signature, path) { state.fileInfos.get(path).signature = signature; - state.hasCalledUpdateShapeSignature.add(path); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(path); } BuilderState.updateSignatureOfFile = updateSignatureOfFile; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache, useFileVersionAsSignature) { + function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName, useFileVersionAsSignature) { + var _a; if (useFileVersionAsSignature === void 0) { useFileVersionAsSignature = state.useFileVersionAsSignature; } - ts.Debug.assert(!!sourceFile); - ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) { + if ((_a = state.hasCalledUpdateShapeSignature) === null || _a === void 0 ? void 0 : _a.has(sourceFile.resolvedPath)) return false; - } var info = state.fileInfos.get(sourceFile.resolvedPath); - if (!info) - return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) { - var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, - /*emitOnlyDtsFiles*/ true, cancellationToken, + programOfThisState.emit(sourceFile, function (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) { + ts.Debug.assert(ts.isDeclarationFileName(fileName), "File extension for signature expected to be dts: Got:: ".concat(fileName)); + latestSignature = ts.computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data); + if (latestSignature !== prevSignature) { + updateExportedModules(state, sourceFile, sourceFiles[0].exportedModulesFromDeclarationEmit); + } + }, cancellationToken, + /*emitOnlyDtsFiles*/ true, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); - if (firstDts_1) { - ts.Debug.assert(ts.isDeclarationFileName(firstDts_1.name), "File extension for signature expected to be dts", function () { return "Found: ".concat(ts.getAnyExtensionFromPath(firstDts_1.name), " for ").concat(firstDts_1.name, ":: All output files: ").concat(JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; }))); }); - latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); - if (exportedModulesMapCache && latestSignature !== prevSignature) { - updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); - } - } } // Default is to use file version as signature if (latestSignature === undefined) { latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { + if (state.exportedModulesMap && latestSignature !== prevSignature) { + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); // All the references in this file are exported var references = state.referencedMap ? state.referencedMap.getValues(sourceFile.resolvedPath) : undefined; if (references) { - exportedModulesMapCache.set(sourceFile.resolvedPath, references); + state.exportedModulesMap.set(sourceFile.resolvedPath, references); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } } } - cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); + (state.oldSignatures || (state.oldSignatures = new ts.Map())).set(sourceFile.resolvedPath, prevSignature || false); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = new ts.Set())).add(sourceFile.resolvedPath); + info.signature = latestSignature; return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** * Coverts the declaration emit result into exported modules map */ - function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + function updateExportedModules(state, sourceFile, exportedModulesFromDeclarationEmit) { + if (!state.exportedModulesMap) + return; + (state.oldExportedModulesMap || (state.oldExportedModulesMap = new ts.Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); if (!exportedModulesFromDeclarationEmit) { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); return; } var exportedModules; exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFilesFromImportedModuleSymbol(symbol)); }); if (exportedModules) { - exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules); + state.exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); } else { - exportedModulesMapCache.deleteKey(sourceFile.resolvedPath); + state.exportedModulesMap.deleteKey(sourceFile.resolvedPath); } function addExportedModule(exportedModulePaths) { if (exportedModulePaths === null || exportedModulePaths === void 0 ? void 0 : exportedModulePaths.length) { @@ -119626,19 +121211,6 @@ var ts; } } BuilderState.updateExportedModules = updateExportedModules; - /** - * Updates the exported modules from cache into state's exported modules map - * This should be called whenever it is safe to commit the state of the builder - */ - function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { - var _a; - if (exportedModulesMapCache) { - ts.Debug.assert(!!state.exportedModulesMap); - (_a = exportedModulesMapCache.deletedKeys()) === null || _a === void 0 ? void 0 : _a.forEach(function (path) { return state.exportedModulesMap.deleteKey(path); }); - exportedModulesMapCache.forEach(function (exportedModules, path) { return state.exportedModulesMap.set(path, exportedModules); }); - } - } - BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -119759,7 +121331,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cancellationToken, computeHash, getCanonicalFileName) { if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -119779,7 +121351,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, computeHash, getCanonicalFileName)) { queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } @@ -119805,32 +121377,33 @@ var ts; * Create the state so that we can iterate on changedFiles/affected files */ function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var _a, _b; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; + var outFilePath = ts.outFile(compilerOptions); // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them - if (!ts.outFile(compilerOptions)) { + if (!outFilePath) { state.semanticDiagnosticsPerFile = new ts.Map(); } + else if (compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.outSignature) && outFilePath === ts.outFile(oldState === null || oldState === void 0 ? void 0 : oldState.compilerOptions)) { + state.outSignature = oldState === null || oldState === void 0 ? void 0 : oldState.outSignature; + } state.changedFilesSet = new ts.Set(); + state.latestChangedDtsFile = compilerOptions.composite ? oldState === null || oldState === void 0 ? void 0 : oldState.latestChangedDtsFile : undefined; var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + var canCopyEmitSignatures = compilerOptions.composite && + (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && + !outFilePath && + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); if (useOldState) { - // Verify the sanity of old state - if (!oldState.currentChangedFilePath) { - var affectedSignatures = oldState.currentAffectedFilesSignatures; - ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); - } - var changedFilesSet = oldState.changedFilesSet; - if (canCopySemanticDiagnostics) { - ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); - } // Copy old state's changed files set - changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); }); - if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) { + (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); + if (!outFilePath && oldState.affectedFilesPendingEmit) { state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice(); state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind); state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; @@ -119851,6 +121424,8 @@ var ts; !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || // versions dont match oldInfo.version !== info.version || + // Implied formats dont match + oldInfo.impliedFormat !== info.impliedFormat || // Referenced files changed !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || // Referenced file was deleted in the new program @@ -119874,27 +121449,25 @@ var ts; state.semanticDiagnosticsFromOldState.add(sourceFilePath); } } + if (canCopyEmitSignatures) { + var oldEmitSignature = oldState.emitSignatures.get(sourceFilePath); + if (oldEmitSignature) + (state.emitSignatures || (state.emitSignatures = new ts.Map())).set(sourceFilePath, oldEmitSignature); + } }); // If the global file is removed, add all files as changed if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) { ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined) .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); }); } - else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { + else if (oldCompilerOptions && !outFilePath && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { // Add all files to affectedFilesPendingEmit since emit changed newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* BuilderFileEmit.Full */); }); ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set(); } - if (useOldState) { - // Any time the interpretation of a source file changes, mark it as changed - ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { - if (state.fileInfos.has(sourceFilePath) && state.fileInfos.get(sourceFilePath).impliedFormat !== info.impliedFormat) { - state.changedFilesSet.add(sourceFilePath); - } - }); - } - state.buildInfoEmitPending = !!state.changedFilesSet.size; + // Since old states change files set is copied, any additional change means we would need to emit build info + state.buildInfoEmitPending = !useOldState || state.changedFilesSet.size !== (((_b = oldState.changedFilesSet) === null || _b === void 0 ? void 0 : _b.size) || 0); return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -119930,30 +121503,35 @@ var ts; ts.BuilderState.releaseCache(state); state.program = undefined; } - /** - * Creates a clone of the state - */ - function cloneBuilderProgramState(state) { - var _a; - var newState = ts.BuilderState.clone(state); - newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile); - newState.changedFilesSet = new ts.Set(state.changedFilesSet); - newState.affectedFiles = state.affectedFiles; - newState.affectedFilesIndex = state.affectedFilesIndex; - newState.currentChangedFilePath = state.currentChangedFilePath; - newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures); - newState.currentAffectedFilesExportedModulesMap = (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clone(); - newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles); - newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; - newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState); - newState.program = state.program; - newState.compilerOptions = state.compilerOptions; - newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(); - newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind); - newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; - newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles); - newState.programEmitComplete = state.programEmitComplete; - return newState; + function backupBuilderProgramEmitState(state) { + var outFilePath = ts.outFile(state.compilerOptions); + // Only in --out changeFileSet is kept around till emit + ts.Debug.assert(!state.changedFilesSet.size || outFilePath); + return { + affectedFilesPendingEmit: state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice(), + affectedFilesPendingEmitKind: state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind), + affectedFilesPendingEmitIndex: state.affectedFilesPendingEmitIndex, + seenEmittedFiles: state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles), + programEmitComplete: state.programEmitComplete, + emitSignatures: state.emitSignatures && new ts.Map(state.emitSignatures), + outSignature: state.outSignature, + latestChangedDtsFile: state.latestChangedDtsFile, + hasChangedEmitSignature: state.hasChangedEmitSignature, + changedFilesSet: outFilePath ? new ts.Set(state.changedFilesSet) : undefined, + }; + } + function restoreBuilderProgramEmitState(state, savedEmitState) { + state.affectedFilesPendingEmit = savedEmitState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitKind = savedEmitState.affectedFilesPendingEmitKind; + state.affectedFilesPendingEmitIndex = savedEmitState.affectedFilesPendingEmitIndex; + state.seenEmittedFiles = savedEmitState.seenEmittedFiles; + state.programEmitComplete = savedEmitState.programEmitComplete; + state.emitSignatures = savedEmitState.emitSignatures; + state.outSignature = savedEmitState.outSignature; + state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile; + state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; + if (savedEmitState.changedFilesSet) + state.changedFilesSet = savedEmitState.changedFilesSet; } /** * Verifies that source file is ok to be used in calls that arent handled by next @@ -119967,8 +121545,8 @@ var ts; * This is to allow the callers to be able to actually remove affected file only when the operation is complete * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained */ - function getNextAffectedFile(state, cancellationToken, computeHash, host) { - var _a; + function getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { @@ -119979,7 +121557,7 @@ var ts; if (!seenAffectedFiles.has(affectedFile.resolvedPath)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); return affectedFile; } affectedFilesIndex++; @@ -119988,10 +121566,8 @@ var ts; state.changedFilesSet.delete(state.currentChangedFilePath); state.currentChangedFilePath = undefined; // Commit the changes in file signature - ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); - state.currentAffectedFilesSignatures.clear(); - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); - (_a = state.currentAffectedFilesExportedModulesMap) === null || _a === void 0 ? void 0 : _a.clear(); + (_a = state.oldSignatures) === null || _a === void 0 ? void 0 : _a.clear(); + (_b = state.oldExportedModulesMap) === null || _b === void 0 ? void 0 : _b.clear(); state.affectedFiles = undefined; } // Get next changed file @@ -120009,12 +121585,7 @@ var ts; return program; } // Get next batch of affected files - if (!state.currentAffectedFilesSignatures) - state.currentAffectedFilesSignatures = new ts.Map(); - if (state.exportedModulesMap) { - state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap()); - } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedByWithOldState(state, program, nextKey.value, cancellationToken, computeHash, getCanonicalFileName); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; if (!state.seenAffectedFiles) @@ -120065,8 +121636,7 @@ var ts; * Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ - function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -120074,19 +121644,18 @@ var ts; // When a change affects the global scope, all files are considered to be affected without updating their signature // That means when affected file is handled, its signature can be out of date // To avoid this, ensure that we update the signature for any affected file in this scenario. - ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, cancellationToken, computeHash, getCanonicalFileName); return; } - ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: ".concat(affectedFile.fileName)); if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; - handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host); + handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host); } /** * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled, * Also we need to make sure signature is updated for these files */ - function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, host) { + function handleDtsMayChangeOf(state, path, cancellationToken, computeHash, getCanonicalFileName, host) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { var program = ts.Debug.checkDefined(state.program); @@ -120097,7 +121666,7 @@ var ts; // This ensures that we dont later during incremental builds considering wrong signature. // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build // But we avoid expensive full shape computation, as using file version as shape is enough for correctness. - ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap, !host.disableUseFileVersionAsSignature); + ts.BuilderState.updateShapeSignature(state, program, sourceFile, cancellationToken, computeHash, getCanonicalFileName, !host.disableUseFileVersionAsSignature); // If not dts emit, nothing more to do if (ts.getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, 0 /* BuilderFileEmit.DtsOnly */); @@ -120118,41 +121687,25 @@ var ts; return !state.semanticDiagnosticsFromOldState.size; } function isChangedSignature(state, path) { - var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path); - var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; + var oldSignature = ts.Debug.checkDefined(state.oldSignatures).get(path) || undefined; + var newSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; return newSignature !== oldSignature; } - function forEachKeyOfExportedModulesMap(state, filePath, fn) { - // Go through exported modules from cache first - var keys = state.currentAffectedFilesExportedModulesMap.getKeys(filePath); - var result = keys && ts.forEachKey(keys, fn); - if (result) - return result; - // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - keys = state.exportedModulesMap.getKeys(filePath); - return keys && ts.forEachKey(keys, function (exportedFromPath) { - var _a; - // If the cache had an updated value, skip - return !state.currentAffectedFilesExportedModulesMap.hasKey(exportedFromPath) && - !((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(exportedFromPath)) ? - fn(exportedFromPath) : - undefined; - }); - } - function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host) { var _a; if (!((_a = state.fileInfos.get(filePath)) === null || _a === void 0 ? void 0 : _a.affectsGlobalScope)) return false; // Every file needs to be handled ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, state.program, /*firstSourceFile*/ undefined) - .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, host); }); + .forEach(function (file) { return handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, computeHash, getCanonicalFileName, host); }); removeDiagnosticsOfLibraryFiles(state); return true; } /** * Iterate on referencing modules that export entities from affected file and delete diagnostics and add pending emit */ - function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host) { + function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a; // If there was change in signature (dts output) for the changed file, // then only we need to handle pending file emit if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) @@ -120169,9 +121722,9 @@ var ts; var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { seenFileNamesMap.set(currentPath, true); - if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host)) return; - handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, host); + handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host); if (isChangedSignature(state, currentPath)) { var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath); queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); @@ -120179,16 +121732,15 @@ var ts; } } } - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); var seenFileAndExportsOfFile = new ts.Set(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, affectedFile.resolvedPath, function (exportedFromPath) { - if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, host)) + (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; var references = state.referencedMap.getKeys(exportedFromPath); return references && ts.forEachKey(references, function (filePath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + return handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); }); } @@ -120196,23 +121748,22 @@ var ts; * handle dts and semantic diagnostics on file and iterate on anything that exports this file * return true when all work is done and we can exit handling dts emit and semantic diagnostics */ - function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, host) { - var _a; + function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host) { + var _a, _b; if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) return undefined; - if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host)) + if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host)) return true; - handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, host); - ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host); // If exported modules has path, all files referencing file exported from are affected - forEachKeyOfExportedModulesMap(state, filePath, function (exportedFromPath) { - return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, host); + (_a = state.exportedModulesMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (exportedFromPath) { + return handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, computeHash, getCanonicalFileName, host); }); // Remove diagnostics of files that import this file (without going to exports of referencing files) - (_a = state.referencedMap.getKeys(filePath)) === null || _a === void 0 ? void 0 : _a.forEach(function (referencingFilePath) { + (_b = state.referencedMap.getKeys(filePath)) === null || _b === void 0 ? void 0 : _b.forEach(function (referencingFilePath) { return !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file handleDtsMayChangeOf(// Dont add to seen since this is not yet done with the export removal - state, referencingFilePath, cancellationToken, computeHash, host); + state, referencingFilePath, cancellationToken, computeHash, getCanonicalFileName, host); }); return undefined; } @@ -120230,12 +121781,13 @@ var ts; } else { state.seenAffectedFiles.add(affected.resolvedPath); + // Change in changeSet/affectedFilesPendingEmit, buildInfo needs to be emitted + state.buildInfoEmitPending = true; if (emitKind !== undefined) { (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind); } if (isPendingEmit) { state.affectedFilesPendingEmitIndex++; - state.buildInfoEmitPending = true; } else { state.affectedFilesIndex++; @@ -120283,25 +121835,62 @@ var ts; } return ts.filterSemanticDiagnostics(diagnostics, state.compilerOptions); } + function isProgramBundleEmitBuildInfo(info) { + return !!ts.outFile(info.options || {}); + } + ts.isProgramBundleEmitBuildInfo = isProgramBundleEmitBuildInfo; /** * Gets the program information to be emitted in buildInfo so that we can use it to create new program */ function getProgramBuildInfo(state, getCanonicalFileName) { - if (ts.outFile(state.compilerOptions)) - return undefined; + var outFilePath = ts.outFile(state.compilerOptions); + if (outFilePath && !state.compilerOptions.composite) + return; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); + // Convert the file name to Path here if we set the fileName instead to optimize multiple d.ts file emits and having to compute Canonical path + var latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : undefined; + if (outFilePath) { + var fileNames_1 = []; + var fileInfos_1 = []; + state.program.getRootFileNames().forEach(function (f) { + var sourceFile = state.program.getSourceFile(f); + if (!sourceFile) + return; + fileNames_1.push(relativeToBuildInfo(sourceFile.resolvedPath)); + fileInfos_1.push(sourceFile.version); + }); + var result_15 = { + fileNames: fileNames_1, + fileInfos: fileInfos_1, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsBundleEmitBuildInfo"), + outSignature: state.outSignature, + latestChangedDtsFile: latestChangedDtsFile, + }; + return result_15; + } var fileNames = []; var fileNameToFileId = new ts.Map(); var fileIdsList; var fileNamesToFileIdListId; + var emitSignatures; var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var _b, _c; var key = _a[0], value = _a[1]; // Ensure fileId var fileId = toFileId(key); ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); - var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + var oldSignature = (_b = state.oldSignatures) === null || _b === void 0 ? void 0 : _b.get(key); + var actualSignature = oldSignature !== undefined ? oldSignature || undefined : value.signature; + if (state.compilerOptions.composite) { + var file = state.program.getSourceFileByPath(key); + if (!ts.isJsonSourceFile(file) && ts.sourceFileMayBeEmitted(file, state.program)) { + var emitSignature = (_c = state.emitSignatures) === null || _c === void 0 ? void 0 : _c.get(key); + if (emitSignature !== actualSignature) { + (emitSignatures || (emitSignatures = [])).push(emitSignature === undefined ? fileId : [fileId, emitSignature]); + } + } + } return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? // If file version is same as signature, dont serialize signature @@ -120309,11 +121898,11 @@ var ts; // If file info only contains version and signature and both are same we can just write string value.version : actualSignature !== undefined ? // If signature is not same as version, encode signature in the fileInfo - signature === undefined ? + oldSignature === undefined ? // If we havent computed signature, use fileInfo as is value : // Serialize fileInfo with new updated signature - { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : + { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : // Signature of the FileInfo is undefined, serialize it as false { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }; }); @@ -120328,17 +121917,13 @@ var ts; if (state.exportedModulesMap) { exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var _a; - if (state.currentAffectedFilesExportedModulesMap) { - if ((_a = state.currentAffectedFilesExportedModulesMap.deletedKeys()) === null || _a === void 0 ? void 0 : _a.has(key)) { - return undefined; - } - var newValue = state.currentAffectedFilesExportedModulesMap.getValues(key); - if (newValue) { - return [toFileId(key), toFileIdListId(newValue)]; - } - } + var oldValue = (_a = state.oldExportedModulesMap) === null || _a === void 0 ? void 0 : _a.get(key); // Not in temporary cache, use existing value - return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue === undefined) + return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue) + return [toFileId(key), toFileIdListId(oldValue)]; + return undefined; }); } var semanticDiagnosticsPerFile; @@ -120349,9 +121934,7 @@ var ts; (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ toFileId(key), - state.hasReusableDiagnostic ? - value : - convertToReusableDiagnostics(value, relativeToBuildInfo) + convertToReusableDiagnostics(value, relativeToBuildInfo) ] : toFileId(key)); } @@ -120366,16 +121949,27 @@ var ts; } } } - return { + var changeFileSet; + if (state.changedFilesSet.size) { + for (var _d = 0, _e = ts.arrayFrom(state.changedFilesSet.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { + var path = _e[_d]; + (changeFileSet || (changeFileSet = [])).push(toFileId(path)); + } + } + var result = { fileNames: fileNames, fileInfos: fileInfos, - options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsMultiFileEmitBuildInfo"), fileIdsList: fileIdsList, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, affectedFilesPendingEmit: affectedFilesPendingEmit, + changeFileSet: changeFileSet, + emitSignatures: emitSignatures, + latestChangedDtsFile: latestChangedDtsFile, }; + return result; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } @@ -120400,24 +121994,21 @@ var ts; } return fileIdListId; } - } - function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { - var result; - var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var name = _a[_i]; - var optionKey = name.toLowerCase(); - var optionInfo = optionsNameMap.get(optionKey); - if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || - // We need to store `strict`, even though it won't be examined directly, so that the - // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly from the buildinfo - optionKey === "strict" || - // We need to store these to determine whether `lib` files need to be rechecked. - optionKey === "skiplibcheck" || optionKey === "skipdefaultlibcheck") { - (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); + /** + * @param optionKey key of CommandLineOption to use to determine if the option should be serialized in tsbuildinfo + */ + function convertToProgramBuildInfoCompilerOptions(options, optionKey) { + var result; + var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo[optionKey]) { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfoEnsuringAbsolutePath); + } } + return result; } - return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { if (option) { @@ -120491,6 +122082,41 @@ var ts; return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; } ts.getBuilderCreationParameters = getBuilderCreationParameters; + function getTextHandlingSourceMapForSignature(text, data) { + return (data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text; + } + function computeSignatureWithDiagnostics(sourceFile, text, computeHash, getCanonicalFileName, data) { + var _a; + text = getTextHandlingSourceMapForSignature(text, data); + var sourceFileDirectory; + if ((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length) { + text += data.diagnostics.map(function (diagnostic) { + return "".concat(locationInfo(diagnostic)).concat(ts.DiagnosticCategory[diagnostic.category]).concat(diagnostic.code, ": ").concat(flattenDiagnosticMessageText(diagnostic.messageText)); + }).join("\n"); + } + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(text); + function flattenDiagnosticMessageText(diagnostic) { + return ts.isString(diagnostic) ? + diagnostic : + diagnostic === undefined ? + "" : + !diagnostic.next ? + diagnostic.messageText : + diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText).join("\n"); + } + function locationInfo(diagnostic) { + if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) + return "(".concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + if (sourceFileDirectory === undefined) + sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath); + return "".concat(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceFileDirectory, diagnostic.file.resolvedPath, getCanonicalFileName)), "(").concat(diagnostic.start, ",").concat(diagnostic.length, ")"); + } + } + ts.computeSignatureWithDiagnostics = computeSignatureWithDiagnostics; + function computeSignature(text, computeHash, data) { + return (computeHash !== null && computeHash !== void 0 ? computeHash : ts.generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); + } + ts.computeSignature = computeSignature; function createBuilderProgram(kind, _a) { var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; // Return same program if underlying program doesnt change @@ -120509,7 +122135,6 @@ var ts; */ var computeHash = ts.maybeBind(host, host.createHash); var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); - var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 @@ -120518,21 +122143,13 @@ var ts; var getState = function () { return state; }; var builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics); builderProgram.getState = getState; - builderProgram.backupState = function () { - ts.Debug.assert(backupState === undefined); - backupState = cloneBuilderProgramState(state); - }; - builderProgram.restoreState = function () { - state = ts.Debug.checkDefined(backupState); - backupState = undefined; - }; + builderProgram.saveEmitState = function () { return backupBuilderProgramEmitState(state); }; + builderProgram.restoreEmitState = function (saved) { return restoreBuilderProgramEmitState(state, saved); }; + builderProgram.hasChangedEmitSignature = function () { return !!state.hasChangedEmitSignature; }; builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); }; builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; builderProgram.emit = emit; - builderProgram.releaseProgram = function () { - releaseCache(state); - backupState = undefined; - }; + builderProgram.releaseProgram = function () { return releaseCache(state); }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; } @@ -120559,7 +122176,7 @@ var ts; * in that order would be used to write the files */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); var emitKind = 1 /* BuilderFileEmit.Full */; var isPendingEmitFile = false; if (!affected) { @@ -120590,34 +122207,68 @@ var ts; return toAffectedFileEmitResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, affected !== state.program && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* BuilderFileEmit.DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile); } - function getWriteFileUpdatingSignatureCallback(writeFile) { + function getWriteFileCallback(writeFile, customTransformers) { return function (fileName, text, writeByteOrderMark, onError, sourceFiles, data) { - var _a; + var _a, _b, _c, _d, _e, _f, _g; if (ts.isDeclarationFileName(fileName)) { - ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); - var file = sourceFiles[0]; - var info = state.fileInfos.get(file.resolvedPath); - var signature = ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.get(file.resolvedPath)) || info.signature; - if (signature === file.version) { - var newSignature = (computeHash || ts.generateDjb2Hash)((data === null || data === void 0 ? void 0 : data.sourceMapUrlPos) !== undefined ? text.substring(0, data.sourceMapUrlPos) : text); - if (newSignature !== file.version) { // Update it - if (host.storeFilesChangingSignatureDuringEmit) - (state.filesChangingSignature || (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); - if (state.exportedModulesMap) - ts.BuilderState.updateExportedModules(file, file.exportedModulesFromDeclarationEmit, state.currentAffectedFilesExportedModulesMap || (state.currentAffectedFilesExportedModulesMap = ts.BuilderState.createManyToManyPathMap())); - if (state.affectedFiles && state.affectedFilesIndex < state.affectedFiles.length) { - state.currentAffectedFilesSignatures.set(file.resolvedPath, newSignature); - } - else { - info.signature = newSignature; - if (state.exportedModulesMap) - ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); + if (!ts.outFile(state.compilerOptions)) { + ts.Debug.assert((sourceFiles === null || sourceFiles === void 0 ? void 0 : sourceFiles.length) === 1); + var emitSignature = void 0; + if (!customTransformers) { + var file = sourceFiles[0]; + var info = state.fileInfos.get(file.resolvedPath); + if (info.signature === file.version) { + var signature = computeSignatureWithDiagnostics(file, text, computeHash, getCanonicalFileName, data); + // With d.ts diagnostics they are also part of the signature so emitSignature will be different from it since its just hash of d.ts + if (!((_a = data === null || data === void 0 ? void 0 : data.diagnostics) === null || _a === void 0 ? void 0 : _a.length)) + emitSignature = signature; + if (signature !== file.version) { // Update it + if (host.storeFilesChangingSignatureDuringEmit) + ((_b = state.filesChangingSignature) !== null && _b !== void 0 ? _b : (state.filesChangingSignature = new ts.Set())).add(file.resolvedPath); + if (state.exportedModulesMap) + ts.BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit); + if (state.affectedFiles) { + // Keep old signature so we know what to undo if cancellation happens + var existing = (_c = state.oldSignatures) === null || _c === void 0 ? void 0 : _c.get(file.resolvedPath); + if (existing === undefined) + ((_d = state.oldSignatures) !== null && _d !== void 0 ? _d : (state.oldSignatures = new ts.Map())).set(file.resolvedPath, info.signature || false); + info.signature = signature; + } + else { + // These are directly commited + info.signature = signature; + (_e = state.oldExportedModulesMap) === null || _e === void 0 ? void 0 : _e.clear(); + } + } } } + // Store d.ts emit hash so later can be compared to check if d.ts has changed. + // Currently we do this only for composite projects since these are the only projects that can be referenced by other projects + // and would need their d.ts change time in --build mode + if (state.compilerOptions.composite) { + var filePath = sourceFiles[0].resolvedPath; + var oldSignature = (_f = state.emitSignatures) === null || _f === void 0 ? void 0 : _f.get(filePath); + emitSignature !== null && emitSignature !== void 0 ? emitSignature : (emitSignature = computeSignature(text, computeHash, data)); + // Dont write dts files if they didn't change + if (emitSignature === oldSignature) + return; + ((_g = state.emitSignatures) !== null && _g !== void 0 ? _g : (state.emitSignatures = new ts.Map())).set(filePath, emitSignature); + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; + } + } + else if (state.compilerOptions.composite) { + var newSignature = computeSignature(text, computeHash, data); + // Dont write dts files if they didn't change + if (newSignature === state.outSignature) + return; + state.outSignature = newSignature; + state.hasChangedEmitSignature = true; + state.latestChangedDtsFile = fileName; } } if (writeFile) @@ -120683,8 +122334,8 @@ var ts; } } } - return ts.Debug.checkDefined(state.program).emit(targetSourceFile, !ts.outFile(state.compilerOptions) && ts.getEmitDeclarations(state.compilerOptions) && !customTransformers ? - getWriteFileUpdatingSignatureCallback(writeFile) : + return ts.Debug.checkDefined(state.program).emit(targetSourceFile, ts.getEmitDeclarations(state.compilerOptions) ? + getWriteFileCallback(writeFile, customTransformers) : writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers); } /** @@ -120693,7 +122344,7 @@ var ts; */ function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { while (true) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash, host); + var affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host); if (!affected) { // Done return undefined; @@ -120773,29 +122424,59 @@ var ts; { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; } ts.toBuilderStateFileInfo = toBuilderStateFileInfo; - function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { - var _a; + function createBuilderProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a, _b, _c, _d; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var filePaths = program.fileNames.map(toPath); - var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); - var fileInfos = new ts.Map(); - program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); - var state = { - fileInfos: fileInfos, - compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, - referencedMap: toManyToManyPathMap(program.referencedMap), - exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), - hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), - affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, - }; + var state; + var filePaths; + var filePathsSetList; + var latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : undefined; + if (isProgramBundleEmitBuildInfo(program)) { + state = { + fileInfos: new ts.Map(), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + latestChangedDtsFile: latestChangedDtsFile, + outSignature: program.outSignature, + }; + } + else { + filePaths = (_a = program.fileNames) === null || _a === void 0 ? void 0 : _a.map(toPath); + filePathsSetList = (_b = program.fileIdsList) === null || _b === void 0 ? void 0 : _b.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); + var fileInfos_2 = new ts.Map(); + var emitSignatures_1 = ((_c = program.options) === null || _c === void 0 ? void 0 : _c.composite) && !ts.outFile(program.options) ? new ts.Map() : undefined; + program.fileInfos.forEach(function (fileInfo, index) { + var path = toFilePath(index + 1); + var stateFileInfo = toBuilderStateFileInfo(fileInfo); + fileInfos_2.set(path, stateFileInfo); + if (emitSignatures_1 && stateFileInfo.signature) + emitSignatures_1.set(path, stateFileInfo.signature); + }); + (_d = program.emitSignatures) === null || _d === void 0 ? void 0 : _d.forEach(function (value) { + if (ts.isNumber(value)) + emitSignatures_1.delete(toFilePath(value)); + else + emitSignatures_1.set(toFilePath(value[0]), value[1]); + }); + state = { + fileInfos: fileInfos_2, + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toManyToManyPathMap(program.referencedMap), + exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), + hasReusableDiagnostic: true, + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, + changedFilesSet: new ts.Set(ts.map(program.changeFileSet, toFilePath)), + latestChangedDtsFile: latestChangedDtsFile, + emitSignatures: (emitSignatures_1 === null || emitSignatures_1 === void 0 ? void 0 : emitSignatures_1.size) ? emitSignatures_1 : undefined, + }; + } return { getState: function () { return state; }, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: ts.notImplemented, getProgramOrUndefined: ts.returnUndefined, releaseProgram: ts.noop, @@ -120815,6 +122496,7 @@ var ts; getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented, emitBuildInfo: ts.notImplemented, close: ts.noop, + hasChangedEmitSignature: ts.returnFalse, }; function toPath(path) { return ts.toPath(path, buildInfoDirectory, getCanonicalFileName); @@ -120840,12 +122522,24 @@ var ts; return map; } } - ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; + ts.createBuilderProgramUsingProgramBuildInfo = createBuilderProgramUsingProgramBuildInfo; + function getBuildInfoFileVersionMap(program, buildInfoPath, host) { + var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var fileInfos = new ts.Map(); + program.fileInfos.forEach(function (fileInfo, index) { + var path = ts.toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName); + var version = ts.isString(fileInfo) ? fileInfo : fileInfo.version; // eslint-disable-line @typescript-eslint/no-unnecessary-type-assertion + fileInfos.set(path, version); + }); + return fileInfos; + } + ts.getBuildInfoFileVersionMap = getBuildInfoFileVersionMap; function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { return { getState: ts.notImplemented, - backupState: ts.noop, - restoreState: ts.noop, + saveEmitState: ts.noop, + restoreEmitState: ts.noop, getProgram: getProgram, getProgramOrUndefined: function () { return getState().program; }, releaseProgram: function () { return getState().program = undefined; }, @@ -120905,7 +122599,7 @@ var ts; * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" * @param dirPath */ - function canWatchDirectory(dirPath) { + function canWatchDirectoryOrFile(dirPath) { var rootLength = ts.getRootLength(dirPath); if (dirPath.length === rootLength) { // Ignore "/", "c:/" @@ -120942,15 +122636,19 @@ var ts; } return true; } - ts.canWatchDirectory = canWatchDirectory; + ts.canWatchDirectoryOrFile = canWatchDirectoryOrFile; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var resolutionsWithFailedLookups = []; + var resolutionsWithOnlyAffectingLocations = []; var resolvedFileToResolution = ts.createMultiMap(); + var impliedFormatPackageJsons = new ts.Map(); var hasChangedAutomaticTypeDirectiveNames = false; + var affectingPathChecksForFile; + var affectingPathChecks; var failedLookupChecks; var startsWithPathChecks; var isInDirectoryChecks; @@ -120977,6 +122675,7 @@ var ts; var failedLookupDefaultExtensions = [".ts" /* Extension.Ts */, ".tsx" /* Extension.Tsx */, ".js" /* Extension.Js */, ".jsx" /* Extension.Jsx */, ".json" /* Extension.Json */]; var customFailedLookupPaths = new ts.Map(); var directoryWatchesOfFailedLookups = new ts.Map(); + var fileWatchesOfAffectingLocations = new ts.Map(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0; @@ -120988,7 +122687,7 @@ var ts; finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + startCachingPerDirectoryResolution: startCachingPerDirectoryResolution, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -121019,6 +122718,7 @@ var ts; } function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + ts.clearMap(fileWatchesOfAffectingLocations, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); @@ -121026,12 +122726,15 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; + resolutionsWithOnlyAffectingLocations.length = 0; failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; - // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update - // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) - clearPerDirectoryResolutions(); + affectingPathChecks = undefined; + affectingPathChecksForFile = undefined; + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); + impliedFormatPackageJsons.clear(); hasChangedAutomaticTypeDirectiveNames = false; } function startRecordingFilesWithChangedResolutions() { @@ -121063,25 +122766,60 @@ var ts; return function (path) { return (!!collected && collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } - function clearPerDirectoryResolutions() { - moduleResolutionCache.clear(); - typeReferenceDirectiveResolutionCache.clear(); + function startCachingPerDirectoryResolution() { + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } - function finishCachingPerDirectoryResolution() { + function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = undefined; - clearPerDirectoryResolutions(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); + // Update file watches + if (newProgram !== oldProgram) { + newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFiles().forEach(function (newFile) { + var _a, _b, _c; + var expected = ts.isExternalOrCommonJsModule(newFile) ? (_b = (_a = newFile.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0 : 0; + var existing = (_c = impliedFormatPackageJsons.get(newFile.path)) !== null && _c !== void 0 ? _c : ts.emptyArray; + for (var i = existing.length; i < expected; i++) { + createFileWatcherOfAffectingLocation(newFile.packageJsonLocations[i], /*forResolution*/ false); + } + if (existing.length > expected) { + for (var i = expected; i < existing.length; i++) { + fileWatchesOfAffectingLocations.get(existing[i]).files--; + } + } + if (expected) + impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations); + else + impliedFormatPackageJsons.delete(newFile.path); + }); + impliedFormatPackageJsons.forEach(function (existing, path) { + if (!(newProgram === null || newProgram === void 0 ? void 0 : newProgram.getSourceFileByPath(path))) { + existing.forEach(function (location) { return fileWatchesOfAffectingLocations.get(location).files--; }); + impliedFormatPackageJsons.delete(path); + } + }); + } directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); + fileWatchesOfAffectingLocations.forEach(function (watcher, path) { + if (watcher.files === 0 && watcher.resolutions === 0) { + fileWatchesOfAffectingLocations.delete(path); + watcher.watcher.close(); + } + }); hasChangedAutomaticTypeDirectiveNames = false; } function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference, _containingSourceFile, mode) { - var _a; + var _a, _b; var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { @@ -121092,11 +122830,12 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _c = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _c.resolvedModule, failedLookupLocations = _c.failedLookupLocations, affectingLocations = _c.affectingLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations); + (_b = primaryResult.affectingLocations).push.apply(_b, affectingLocations); return primaryResult; } } @@ -121301,7 +123040,7 @@ var ts; } // If the directory is node_modules use it to watch, always watch it recursively if (ts.isNodeModulesDirectory(dirPath)) { - return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; + return canWatchDirectoryOrFile(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; // Use some ancestor of the root directory @@ -121319,7 +123058,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; + return canWatchDirectoryOrFile(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -121347,10 +123086,11 @@ var ts; } function watchFailedLookupLocationOfResolution(resolution) { ts.Debug.assert(!!resolution.refCount); - var failedLookupLocations = resolution.failedLookupLocations; - if (!failedLookupLocations.length) + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (!failedLookupLocations.length && !affectingLocations.length) return; - resolutionsWithFailedLookups.push(resolution); + if (failedLookupLocations.length) + resolutionsWithFailedLookups.push(resolution); var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; @@ -121377,12 +123117,87 @@ var ts; // This is always non recursive setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } + watchAffectingLocationsOfResolution(resolution, !failedLookupLocations.length); + } + function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { + ts.Debug.assert(!!resolution.refCount); + var affectingLocations = resolution.affectingLocations; + if (!affectingLocations.length) + return; + if (addToResolutionsWithOnlyAffectingLocations) + resolutionsWithOnlyAffectingLocations.push(resolution); + // Watch package json + for (var _i = 0, affectingLocations_1 = affectingLocations; _i < affectingLocations_1.length; _i++) { + var affectingLocation = affectingLocations_1[_i]; + createFileWatcherOfAffectingLocation(affectingLocation, /*forResolution*/ true); + } + } + function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) { + var fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation); + if (fileWatcher) { + if (forResolution) + fileWatcher.resolutions++; + else + fileWatcher.files++; + return; + } + var locationToWatch = affectingLocation; + if (resolutionHost.realpath) { + locationToWatch = resolutionHost.realpath(affectingLocation); + if (affectingLocation !== locationToWatch) { + var fileWatcher_1 = fileWatchesOfAffectingLocations.get(locationToWatch); + if (fileWatcher_1) { + if (forResolution) + fileWatcher_1.resolutions++; + else + fileWatcher_1.files++; + fileWatcher_1.paths.add(affectingLocation); + fileWatchesOfAffectingLocations.set(affectingLocation, fileWatcher_1); + return; + } + } + } + var paths = new ts.Set(); + paths.add(locationToWatch); + var actualWatcher = canWatchDirectoryOrFile(resolutionHost.toPath(locationToWatch)) ? + resolutionHost.watchAffectingFileLocation(locationToWatch, function (fileName, eventKind) { + cachedDirectoryStructureHost === null || cachedDirectoryStructureHost === void 0 ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind); + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + paths.forEach(function (path) { + if (watcher.resolutions) + (affectingPathChecks !== null && affectingPathChecks !== void 0 ? affectingPathChecks : (affectingPathChecks = new ts.Set())).add(path); + if (watcher.files) + (affectingPathChecksForFile !== null && affectingPathChecksForFile !== void 0 ? affectingPathChecksForFile : (affectingPathChecksForFile = new ts.Set())).add(path); + packageJsonMap === null || packageJsonMap === void 0 ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); + }); + resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); + }) : ts.noopFileWatcher; + var watcher = { + watcher: actualWatcher !== ts.noopFileWatcher ? { + close: function () { + actualWatcher.close(); + // Ensure when watching symlinked package.json, we can close the actual file watcher only once + actualWatcher = ts.noopFileWatcher; + } + } : actualWatcher, + resolutions: forResolution ? 1 : 0, + files: forResolution ? 0 : 1, + paths: paths, + }; + fileWatchesOfAffectingLocations.set(locationToWatch, watcher); + if (affectingLocation !== locationToWatch) { + fileWatchesOfAffectingLocations.set(affectingLocation, watcher); + paths.add(affectingLocation); + } } function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { var program = resolutionHost.getCurrentProgram(); if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) { resolutions.forEach(watchFailedLookupLocationOfResolution); } + else { + resolutions.forEach(function (resolution) { return watchAffectingLocationsOfResolution(resolution, /*addToResolutionWithOnlyAffectingLocations*/ true); }); + } } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); @@ -121404,38 +123219,44 @@ var ts; if (resolved && resolved.resolvedFileName) { resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution); } - if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { - // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups - return; - } - var failedLookupLocations = resolution.failedLookupLocations; - var removeAtRoot = false; - for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { - var failedLookupLocation = failedLookupLocations_2[_i]; - var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (toWatch) { - var dirPath = toWatch.dirPath; - var refCount = customFailedLookupPaths.get(failedLookupLocationPath); - if (refCount) { - if (refCount === 1) { - customFailedLookupPaths.delete(failedLookupLocationPath); + var failedLookupLocations = resolution.failedLookupLocations, affectingLocations = resolution.affectingLocations; + if (ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { + var removeAtRoot = false; + for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { + var failedLookupLocation = failedLookupLocations_2[_i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + var dirPath = toWatch.dirPath; + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + if (dirPath === rootPath) { + removeAtRoot = true; } else { - ts.Debug.assert(refCount > 1); - customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + removeDirectoryWatcher(dirPath); } } - if (dirPath === rootPath) { - removeAtRoot = true; - } - else { - removeDirectoryWatcher(dirPath); - } } + if (removeAtRoot) { + removeDirectoryWatcher(rootPath); + } + } + else if (affectingLocations.length) { + ts.unorderedRemoveItem(resolutionsWithOnlyAffectingLocations, resolution); } - if (removeAtRoot) { - removeDirectoryWatcher(rootPath); + for (var _a = 0, affectingLocations_2 = affectingLocations; _a < affectingLocations_2.length; _a++) { + var affectingLocation = affectingLocations_2[_a]; + var watcher = fileWatchesOfAffectingLocations.get(affectingLocation); + watcher.resolutions--; } } function removeDirectoryWatcher(dirPath) { @@ -121489,7 +123310,7 @@ var ts; resolution.isInvalidated = invalidated = true; for (var _a = 0, _b = ts.Debug.checkDefined(resolution.files); _a < _b.length; _a++) { var containingFilePath = _b[_a]; - (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); // When its a file with inferred types resolution, invalidate type reference directive resolution hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile); } @@ -121514,7 +123335,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = new ts.Set())).add(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -121532,7 +123353,7 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { @@ -121544,7 +123365,7 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = new ts.Set())).add(fileOrDirectoryPath); // If the invalidated file is from a node_modules package, invalidate everything else // in the package since we might not get notifications for other files in the package. // This hardens our logic against unreliable file watchers. @@ -121556,22 +123377,46 @@ var ts; resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { - return false; + var _a; + var invalidated = false; + if (affectingPathChecksForFile) { + (_a = resolutionHost.getCurrentProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFiles().forEach(function (f) { + if (ts.some(f.packageJsonLocations, function (location) { return affectingPathChecksForFile.has(location); })) { + (filesWithInvalidatedResolutions !== null && filesWithInvalidatedResolutions !== void 0 ? filesWithInvalidatedResolutions : (filesWithInvalidatedResolutions = new ts.Set())).add(f.path); + invalidated = true; + } + }); + affectingPathChecksForFile = undefined; + } + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks && !affectingPathChecks) { + return invalidated; + } + invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; + var packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach(function (_value, path) { return isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : undefined; }); } - var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); failedLookupChecks = undefined; startsWithPathChecks = undefined; isInDirectoryChecks = undefined; + invalidated = invalidateResolutions(resolutionsWithOnlyAffectingLocations, canInvalidatedFailedLookupResolutionWithAffectingLocation) || invalidated; + affectingPathChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { - return resolution.failedLookupLocations.some(function (location) { - var locationPath = resolutionHost.toPath(location); - return ts.contains(failedLookupChecks, locationPath) || - ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || - (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); - }); + if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) + return true; + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) + return false; + return resolution.failedLookupLocations.some(function (location) { return isInvalidatedFailedLookup(resolutionHost.toPath(location)); }); + } + function isInvalidatedFailedLookup(locationPath) { + return (failedLookupChecks === null || failedLookupChecks === void 0 ? void 0 : failedLookupChecks.has(locationPath)) || + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + ts.firstDefinedIterator((isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath) ? true : undefined; }); + } + function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) { + return !!affectingPathChecks && resolution.affectingLocations.some(function (location) { return affectingPathChecks.has(location); }); } function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); @@ -121637,7 +123482,7 @@ var ts; function directoryExistsForTypeRootWatch(nodeTypesDirectory) { var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); var dirPath = resolutionHost.toPath(dir); - return dirPath === rootPath || canWatchDirectory(dirPath); + return dirPath === rootPath || canWatchDirectoryOrFile(dirPath); } } ts.createResolutionCache = createResolutionCache; @@ -121748,7 +123593,7 @@ var ts; var info = getInfo(importingSourceFileName, host); var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences, options); return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode); }) || - getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences); + getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences, options) { if (options === void 0) { options = {}; } @@ -121831,7 +123676,7 @@ var ts; return nodeModulesSpecifiers; } if (!specifier && !modulePath.isRedirect) { - var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences); + var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); if (ts.pathIsBareSpecifier(local)) { pathsSpecifiers = ts.append(pathsSpecifiers, local); } @@ -121859,7 +123704,7 @@ var ts; var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); return { getCanonicalFileName: getCanonicalFileName, importingSourceFileName: importingSourceFileName, sourceDirectory: sourceDirectory }; } - function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, _a) { + function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, _a) { var ending = _a.ending, relativePreference = _a.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var sourceDirectory = info.sourceDirectory, getCanonicalFileName = info.getCanonicalFileName; @@ -121873,9 +123718,8 @@ var ts; if (!relativeToBaseUrl) { return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); - var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths; + var fromPaths = paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, getAllowedEndings(ending, compilerOptions, importMode), host, compilerOptions); + var nonRelative = fromPaths === undefined && baseUrl !== undefined ? removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) : fromPaths; if (!nonRelative) { return relativePath; } @@ -121961,9 +123805,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -121983,10 +123827,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_17 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_17) + return result_17; } }); }); @@ -122028,7 +123872,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_32 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -122052,9 +123896,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_10 = _loop_32(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_10 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -122110,28 +123954,102 @@ var ts; return ambientModuleDeclare.name.text; } } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + function getAllowedEndings(preferredEnding, compilerOptions, importMode) { + if (ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && importMode === ts.ModuleKind.ESNext) { + return [2 /* Ending.JsExtension */]; + } + switch (preferredEnding) { + case 2 /* Ending.JsExtension */: return [2 /* Ending.JsExtension */, 0 /* Ending.Minimal */, 1 /* Ending.Index */]; + case 1 /* Ending.Index */: return [1 /* Ending.Index */, 0 /* Ending.Minimal */, 2 /* Ending.JsExtension */]; + case 0 /* Ending.Minimal */: return [0 /* Ending.Minimal */, 1 /* Ending.Index */, 2 /* Ending.JsExtension */]; + default: ts.Debug.assertNever(preferredEnding); + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(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, + // meaning a '.ts' or '.d.ts' extension is allowed to resolve. This is distinct from the case where a '*' substitution + // causes a module specifier to have an extension, i.e. the extension comes from the module specifier in a JS/TS file + // and matches the '*'. For example: + // + // Module Specifier | Path Mapping (key: [pattern]) | Interpolation | Resolution Action + // ---------------------->------------------------------->--------------------->--------------------------------------------------------------- + // import "@app/foo" -> "@app/*": ["./src/app/*.ts"] -> "./src/app/foo.ts" -> tryFile("./src/app/foo.ts") || [continue resolution algorithm] + // import "@app/foo.ts" -> "@app/*": ["./src/app/*"] -> "./src/app/foo.ts" -> [continue resolution algorithm] + // + // (https://github.com/microsoft/TypeScript/blob/ad4ded80e1d58f0bf36ac16bea71bc10d9f09895/src/compiler/moduleNameResolver.ts#L2509-L2516) + // + // The interpolation produced by both scenarios is identical, but only in the former, where the extension is encoded in + // the path mapping rather than in the module specifier, will we prioritize a file lookup on the interpolation result. + // (In fact, currently, the latter scenario will necessarily fail since no resolution mode recognizes '.ts' as a valid + // extension for a module specifier.) + // + // Here, this means we need to be careful about whether we generate a match from the target filename (typically with a + // .ts extension) or the possible relative module specifiers representing that file: + // + // Filename | Relative Module Specifier Candidates | Path Mapping | Filename Result | Module Specifier Results + // --------------------<----------------------------------------------<------------------------------<-------------------||---------------------------- + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*.d.ts"] <- @app/haha || (none) + // dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*"] <- (none) || @app/haha, @app/haha.js + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*.d.ts"] <- @app/foo/index || (none) + // dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*"] <- (none) || @app/foo, @app/foo/index, @app/foo/index.js + // dist/wow.js.js <- dist/wow.js, dist/wow.js.js <- "@app/*": ["./dist/*.js"] <- @app/wow.js || @app/wow, @app/wow.js + // + // The "Filename Result" can be generated only if `pattern` has an extension. Care must be taken that the list of + // relative module specifiers to run the interpolation (a) is actually valid for the module resolution mode, (b) takes + // into account the existence of other files (e.g. 'dist/wow.js' cannot refer to 'dist/wow.js.js' if 'dist/wow.js' + // exists) and (c) that they are ordered by preference. The last row shows that the filename result and module + // specifier results are not mutually exclusive. Note that the filename result is a higher priority in module + // resolution, but as long criteria (b) above is met, I don't think its result needs to be the highest priority result + // in module specifier generation. I have included it last, as it's difficult to tell exactly where it should be + // sorted among the others for a particular value of `importModuleSpecifierEnding`. + var candidates = allowedEndings.map(function (ending) { return ({ + ending: ending, + value: removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) + }); }); + if (ts.tryGetExtensionFromPath(pattern)) { + candidates.push({ ending: undefined, value: relativeToBaseUrl }); + } if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix) || - !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); - return key.replace("*", matchedStar); + var prefix = pattern.substring(0, indexOfStar); + var suffix = pattern.substring(indexOfStar + 1); + for (var _b = 0, candidates_3 = candidates; _b < candidates_3.length; _b++) { + var _c = candidates_3[_b], ending = _c.ending, value = _c.value; + if (value.length >= prefix.length + suffix.length && + ts.startsWith(value, prefix) && + ts.endsWith(value, suffix) && + validateEnding({ ending: ending, value: value })) { + var matchedStar = value.substring(prefix.length, value.length - suffix.length); + return { value: key.replace("*", matchedStar) }; + } } } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; + else if (ts.some(candidates, function (c) { return c.ending !== 0 /* Ending.Minimal */ && pattern === c.value; }) || + ts.some(candidates, function (c) { return c.ending === 0 /* Ending.Minimal */ && pattern === c.value && validateEnding(c); })) { + return { value: key }; } + }; + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } + function validateEnding(_a) { + var ending = _a.ending, value = _a.value; + // Optimization: `removeExtensionAndIndexPostFix` can query the file system (a good bit) if `ending` is `Minimal`, the basename + // is 'index', and a `host` is provided. To avoid that until it's unavoidable, we ran the function with no `host` above. Only + // here, after we've checked that the minimal ending is indeed a match (via the length and prefix/suffix checks / `some` calls), + // do we check that the host-validated result is consistent with the answer we got before. If it's not, it falls back to the + // `Ending.Index` result, which should already be in the list of candidates if `Minimal` was. (Note: the assumption here is + // that every module resolution mode that supports dropping extensions also supports dropping `/index`. Like literally + // everything else in this file, this logic needs to be updated if that's not true in some future module resolution mode.) + return ending !== 0 /* Ending.Minimal */ || value === removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions, host); + } } var MatchingMode; (function (MatchingMode) { @@ -122227,10 +124145,10 @@ var ts; return undefined; } // Simplify the full file path to something that can be resolved by Node. + var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var moduleSpecifier = path; var isPackageRootPath = false; if (!packageNameOnly) { - var preferences = getPreferences(host, userPreferences, options, importingSourceFile); var packageRootIndex = parts.packageRootIndex; var moduleFileName = void 0; while (true) { @@ -122279,15 +124197,13 @@ var ts; var packageRootPath = path.substring(0, packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); var moduleFileToTry = path; + var maybeBlockedByTypesVersions = false; var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) { var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); + var importMode = overrideMode || importingSourceFile.impliedNodeFormat; if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { - // `conditions` *could* be made to go against `importingSourceFile.impliedNodeFormat` if something wanted to generate - // an ImportEqualsDeclaration in an ESM-implied file or an ImportCall in a CJS-implied file. But since this function is - // usually called to conjure an import out of thin air, we don't have an existing usage to call `getModeForUsageAtIndex` - // with, so for now we just stick with the mode of the file. - var conditions = ["node", overrideMode || importingSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext ? "import" : "require", "types"]; + var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"]; var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, ts.getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions) : undefined; @@ -122306,16 +124222,26 @@ var ts; : undefined; if (versionPaths) { var subModuleName = path.slice(packageRootPath.length + 1); - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Ending.Minimal */, options), versionPaths.paths); - if (fromPaths !== undefined) { + var fromPaths = tryGetModuleNameFromPaths(subModuleName, versionPaths.paths, getAllowedEndings(preferences.ending, options, importMode), host, options); + if (fromPaths === undefined) { + maybeBlockedByTypesVersions = true; + } + else { moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths); } } // If the file is the main module, it can be imported by the package name var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; - if (ts.isString(mainFileRelative)) { + if (ts.isString(mainFileRelative) && !(maybeBlockedByTypesVersions && ts.matchPatternOrExact(ts.tryParsePatterns(versionPaths.paths), mainFileRelative))) { + // The 'main' file is also subject to mapping through typesVersions, and we couldn't come up with a path + // explicitly through typesVersions, so if it matches a key in typesVersions now, it's not reachable. + // (The only way this can happen is if some file in a package that's not resolvable from outside the + // package got pulled into the program anyway, e.g. transitively through a file that *is* reachable. It + // happens very easily in fourslash tests though, since every test file listed gets included. See + // importNameCodeFix_typesVersions.ts for an example.) var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + // ^ An arbitrary removal of file extension for this comparison is almost certainly wrong return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry }; } } @@ -122610,23 +124536,46 @@ var ts; var file = _c[_i]; write("".concat(toFileName(file, relativeFileName))); (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write(" ".concat(fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText)); }); - (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); + (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); } } ts.explainFiles = explainFiles; - function explainIfFileIsRedirect(file, fileNameConvertor) { + function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { + var _a; var result; if (file.path !== file.resolvedPath) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); } if (file.redirectInfo) { - (result || (result = [])).push(ts.chainDiagnosticMessages( + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); } + if (ts.isExternalOrCommonJsModule(file)) { + switch (file.impliedNodeFormat) { + case ts.ModuleKind.ESNext: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + break; + case ts.ModuleKind.CommonJS: + if (file.packageJsonScope) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, file.packageJsonScope.packageJsonContent.type ? + ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : + ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor))); + } + else if ((_a = file.packageJsonLocations) === null || _a === void 0 ? void 0 : _a.length) { + (result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found)); + } + break; + } + } return result; } - ts.explainIfFileIsRedirect = explainIfFileIsRedirect; + ts.explainIfFileIsRedirectAndImpliedFormat = explainIfFileIsRedirectAndImpliedFormat; function getMatchedFileSpec(program, fileName) { var _a; var configFile = program.getCompilerOptions().configFile; @@ -122643,6 +124592,9 @@ var ts; var configFile = program.getCompilerOptions().configFile; if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedIncludeSpecs)) return undefined; + // Return true if its default include spec + if (configFile.configFileSpecs.isDefaultIncludeSpec) + return true; var isJsonFile = ts.fileExtensionIs(fileName, ".json" /* Extension.Json */); var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); var useCaseSensitiveFileNames = program.useCaseSensitiveFileNames(); @@ -122708,11 +124660,13 @@ var ts; if (matchedByFiles) return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Part_of_files_list_in_tsconfig_json); var matchedByInclude = getMatchedIncludeSpec(program, fileName); - return matchedByInclude ? + return ts.isString(matchedByInclude) ? ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) : - // Could be additional files specified as roots - ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation); + // Could be additional files specified as roots or matched by default include + ts.chainDiagnosticMessages(/*details*/ undefined, matchedByInclude ? + ts.Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : + ts.Diagnostics.Root_file_specified_for_compilation); case ts.FileIncludeKind.SourceFromProjectReference: case ts.FileIncludeKind.OutputFromProjectReference: var isOutput = reason.kind === ts.FileIncludeKind.OutputFromProjectReference; @@ -122831,11 +124785,19 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", + AffectingFileLocation: "File location affecting resolution", TypeRoots: "Type roots", ConfigFileOfReferencedProject: "Config file of referened project", ExtendedConfigOfReferencedProject: "Extended config file of referenced project", WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", PackageJson: "package.json file", + ClosedScriptInfo: "Closed Script info", + ConfigFileForInferredRoot: "Config file for the inferred project root", + NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache", + MissingSourceMapFile: "Missing source map file", + NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root", + MissingGeneratedFile: "Missing generated file", + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -122944,6 +124906,7 @@ var ts; createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, storeFilesChangingSignatureDuringEmit: system.storeFilesChangingSignatureDuringEmit, + now: ts.maybeBind(system, system.now), }; } ts.createProgramHost = createProgramHost; @@ -123011,20 +124974,27 @@ var ts; var ts; (function (ts) { function readBuilderProgram(compilerOptions, host) { - if (ts.outFile(compilerOptions)) - return undefined; var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions); if (!buildInfoPath) return undefined; - var content = host.readFile(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); + var buildInfo; + if (host.getBuildInfo) { + // host provides buildinfo, get it from there. This allows host to cache it + buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); + if (!buildInfo) + return undefined; + } + else { + var content = host.readFile(buildInfoPath); + if (!content) + return undefined; + buildInfo = ts.getBuildInfo(content); + } if (buildInfo.version !== ts.version) return undefined; if (!buildInfo.program) return undefined; - return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); + return ts.createBuilderProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host); } ts.readBuilderProgram = readBuilderProgram; function createIncrementalCompilerHost(options, system) { @@ -123077,14 +125047,12 @@ var ts; var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc var missingFilesMap; // Map of file watchers for the missing files - var packageJsonMap; // map of watchers for package json files used in module resolution var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations var parsedConfigs; // Parsed commandline and watching cached for referenced projects var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation - var changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution var reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files @@ -123141,6 +125109,7 @@ var ts; compilerHost.getCompilationSettings = function () { return compilerOptions; }; compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect); compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); }; + compilerHost.watchAffectingFileLocation = function (file, cb) { return watchFile(file, cb, ts.PollingInterval.High, watchOptions, ts.WatchType.AffectingFileLocation); }; compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); }; compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations; @@ -123174,6 +125143,9 @@ var ts; return host.resolveTypeReferenceDirectives.apply(host, args); }) : (function (typeDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference, containingFileMode); }); + compilerHost.getModuleResolutionCache = host.resolveModuleNames ? + ts.maybeBind(host, host.getModuleResolutionCache) : + (function () { return resolutionCache.getModuleResolutionCache(); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); @@ -123223,10 +125195,6 @@ var ts; }); parsedConfigs = undefined; } - if (packageJsonMap) { - ts.clearMap(packageJsonMap, ts.closeFileWatcher); - packageJsonMap = undefined; - } } function getCurrentBuilderProgram() { return builderProgram; @@ -123240,12 +125208,12 @@ var ts; var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); - if (program && (changesAffectResolution || ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions))) { + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { resolutionCache.clear(); } } // All resolutions are invalid if user provided resolutions - var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution); + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { @@ -123261,7 +125229,6 @@ var ts; } createNewProgram(hasInvalidatedResolution); } - changesAffectResolution = false; // reset for next sync reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); @@ -123281,16 +125248,11 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + var oldProgram = getCurrentProgram(); builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); - // map package json cache entries to their realpaths so we don't try to watch across symlinks - var packageCacheEntries = ts.map(resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [compilerHost.realpath ? toPath(compilerHost.realpath(path)) : path, data]; - }); - resolutionCache.finishCachingPerDirectoryResolution(); + resolutionCache.finishCachingPerDirectoryResolution(builderProgram.getProgram(), oldProgram); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath); - ts.updatePackageJsonWatch(packageCacheEntries, packageJsonMap || (packageJsonMap = new ts.Map()), watchPackageJsonLookupPath); if (needsUpdateInTypeRootWatch) { resolutionCache.updateTypeRootsWatch(); } @@ -123370,9 +125332,6 @@ var ts; sourceFilesCache.set(path, false); } } - if (sourceFile) { - sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); - } return sourceFile; } return hostSourceFile.sourceFile; @@ -123487,6 +125446,7 @@ var ts; } function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; rootFileNames = ts.getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions); if (ts.updateErrorForNoInputFiles(rootFileNames, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; @@ -123595,21 +125555,6 @@ var ts; ts.noopFileWatcher : watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } - function watchPackageJsonLookupPath(packageJsonPath) { - // If the package.json is pulled into the compilation itself (eg, via json imports), don't add a second watcher here - return sourceFilesCache.has(packageJsonPath) ? - ts.noopFileWatcher : - watchFilePath(packageJsonPath, packageJsonPath, onPackageJsonChange, ts.PollingInterval.High, watchOptions, ts.WatchType.PackageJson); - } - function onPackageJsonChange(fileName, eventKind, path) { - updateCachedSystemWithFile(fileName, path, eventKind); - // package.json changes invalidate module resolution and can change the set of loaded files - // so if we witness a change to one, we have to do a full reload - reloadLevel = ts.ConfigFileProgramReloadLevel.Full; - changesAffectResolution = true; - // Update the program - scheduleProgramUpdate(); - } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { @@ -123767,14 +125712,17 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf"; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream"; - UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate"; - UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream"; - UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["OutOfDateBuildInfo"] = 7] = "OutOfDateBuildInfo"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 8] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 9] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 10] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 11] = "TsVersionOutputOfDate"; + UpToDateStatusType[UpToDateStatusType["UpToDateWithInputFileText"] = 12] = "UpToDateWithInputFileText"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 13] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ForceBuild"] = 14] = "ForceBuild"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); function resolveConfigFileProjectName(project) { if (ts.fileExtensionIs(project, ".json" /* Extension.Json */)) { @@ -123819,9 +125767,12 @@ var ts; function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); }); } - function newer(date1, date2) { - return date2 > date1 ? date2 : date1; + /*@internal*/ + /** Helper to use now method instead of current date for testing purposes to get consistent baselines */ + function getCurrentTime(host) { + return host.now ? host.now() : new Date(); } + ts.getCurrentTime = getCurrentTime; /*@internal*/ function isCircularBuildOrder(buildOrder) { return !!buildOrder && !!buildOrder.buildOrder; @@ -123896,6 +125847,7 @@ var ts; compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); }; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); + compilerHost.getModuleResolutionCache = ts.maybeBind(host, host.getModuleResolutionCache); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { @@ -123911,6 +125863,7 @@ var ts; return ts.loadWithTypeDirectiveCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader_4); }; } + compilerHost.getBuildInfo = function (fileName, configFilePath) { return getBuildInfo(state, fileName, toResolvedConfigFilePath(state, configFilePath), /*modifiedTime*/ undefined); }; var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -123927,8 +125880,9 @@ var ts; resolvedConfigFilePaths: new ts.Map(), configFileCache: new ts.Map(), projectStatus: new ts.Map(), - buildInfoChecked: new ts.Map(), extendedConfigCache: new ts.Map(), + buildInfoCache: new ts.Map(), + outputTimeStamps: new ts.Map(), builderPrograms: new ts.Map(), diagnostics: new ts.Map(), projectPendingBuild: new ts.Map(), @@ -123944,7 +125898,6 @@ var ts; allProjectBuildPending: true, needsSummary: true, watchAllProjectsPending: watch, - currentInvalidatedProject: undefined, // Watch state watch: watch, allWatchedWildcardDirectories: new ts.Map(), @@ -123952,6 +125905,7 @@ var ts; allWatchedConfigFiles: new ts.Map(), allWatchedExtendedConfigFiles: new ts.Map(), allWatchedPackageJsonFiles: new ts.Map(), + filesWatched: new ts.Map(), lastCachedPackageJsonLookups: new ts.Map(), timerToBuildInvalidatedProject: undefined, reportFileChangeDetected: false, @@ -124058,11 +126012,12 @@ var ts; // Config file cache ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete); - ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete); ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.buildInfoCache, currentProjects, noopOnDelete); + ts.mutateMapSkippingNewValues(state.outputTimeStamps, currentProjects, noopOnDelete); // Remove watches for the program no longer in the solution if (state.watch) { ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher }); @@ -124177,7 +126132,6 @@ var ts; })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {})); function doneInvalidatedProject(state, projectPath) { state.projectPendingBuild.delete(projectPath); - state.currentInvalidatedProject = undefined; return state.diagnostics.has(projectPath) ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; @@ -124353,21 +126307,21 @@ var ts; } function emit(writeFileCallback, cancellationToken, customTransformers) { var _a; - var _b, _c; + var _b, _c, _d; ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.Emit); // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly - program.backupState(); + var saved = program.saveEmitState(); var declDiagnostics; var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; var outputFiles = []; var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, /*write*/ undefined, - /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, + /*reportSummary*/ undefined, function (name, text, writeByteOrderMark, _onError, _sourceFiles, data) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark, buildInfo: data === null || data === void 0 ? void 0 : data.buildInfo }); }, cancellationToken, /*emitOnlyDts*/ false, customTransformers || ((_c = (_b = state.host).getCustomTransformers) === null || _c === void 0 ? void 0 : _c.call(_b, project))).emitResult; // Don't emit .d.ts if there are decl file errors if (declDiagnostics) { - program.restoreState(); + program.restoreEmitState(saved); (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step); return { emitSkipped: true, @@ -124376,38 +126330,38 @@ var ts; } // Actual Emit var host = state.host, compilerHost = state.compilerHost; - var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; - var newestDeclarationFileContentChangedTime = minimumDate; - var anyDtsChanged = false; + var resultFlags = ((_d = program.hasChangedEmitSignature) === null || _d === void 0 ? void 0 : _d.call(program)) ? BuildResultFlags.None : BuildResultFlags.DeclarationOutputUnchanged; var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var options = program.getCompilerOptions(); + var isIncremental = ts.isIncrementalCompilation(options); + var outputTimeStampMap; + var now; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; - var priorChangeTime; - if (!anyDtsChanged && ts.isDeclarationFileName(name)) { - // Check for unchanged .d.ts files - if (host.fileExists(name) && state.readFileWithCache(name) === text) { - priorChangeTime = host.getModifiedTime(name); - } - else { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - anyDtsChanged = true; - } - } + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; + var path = toPath(state, name); emittedOutputs.set(toPath(state, name), name); + if (buildInfo) + setBuildInfo(state, buildInfo, projectPath, options, resultFlags); ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); - if (priorChangeTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + if (!isIncremental && state.watch) { + (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); } }); - finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); + finishEmit(emitterDiagnostics, emittedOutputs, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); return emitResult; } function emitBuildInfo(writeFileCallback, cancellationToken) { ts.Debug.assertIsDefined(program); ts.Debug.assert(step === BuildStep.EmitBuildInfo); - var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken); + var emitResult = program.emitBuildInfo(function (name, text, writeByteOrderMark, onError, sourceFiles, data) { + if (data === null || data === void 0 ? void 0 : data.buildInfo) + setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), BuildResultFlags.DeclarationOutputUnchanged); + if (writeFileCallback) + writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); + else + state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); + }, cancellationToken); if (emitResult.diagnostics.length) { reportErrors(state, emitResult.diagnostics); state.diagnostics.set(projectPath, __spreadArray(__spreadArray([], state.diagnostics.get(projectPath), true), emitResult.diagnostics, true)); @@ -124420,7 +126374,7 @@ var ts; step = BuildStep.QueueReferencingProjects; return emitResult; } - function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) { + function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) { var _a; var emitDiagnostics = emitterDiagnostics.getDiagnostics(); if (emitDiagnostics.length) { @@ -124431,13 +126385,10 @@ var ts; emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); }); } // Update time stamps for rest of the outputs - var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); + updateOutputTimestampsWorker(state, config, projectPath, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); state.diagnostics.delete(projectPath); state.projectStatus.set(projectPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ? - maximumDate : - newestDeclarationFileContentChangedTime, oldestOutputFileName: oldestOutputFileName }); afterProgramDone(state, program, config); @@ -124472,13 +126423,21 @@ var ts; ts.Debug.assert(!!outputFiles.length); var emitterDiagnostics = ts.createDiagnosticCollection(); var emittedOutputs = new ts.Map(); + var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; + var existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo; outputFiles.forEach(function (_a) { - var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + var _b, _c; + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark, buildInfo = _a.buildInfo; emittedOutputs.set(toPath(state, name), name); + if (buildInfo) { + if (((_b = buildInfo.program) === null || _b === void 0 ? void 0 : _b.outSignature) !== ((_c = existingBuildInfo.program) === null || _c === void 0 ? void 0 : _c.outSignature)) { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + } + setBuildInfo(state, buildInfo, projectPath, config.options, resultFlags); + } ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); }); - var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, - /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged); + var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, outputFiles[0].name, resultFlags); return { emitSkipped: false, diagnostics: emitDiagnostics }; } function executeSteps(till, cancellationToken, writeFile, customTransformers) { @@ -124528,17 +126487,11 @@ var ts; !!ts.getConfigFileParsingDiagnostics(config).length || !ts.isIncrementalCompilation(config.options); } - function getNextInvalidatedProject(state, buildOrder, reportQueue) { + function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { if (!state.projectPendingBuild.size) return undefined; if (isCircularBuildOrder(buildOrder)) return undefined; - if (state.currentInvalidatedProject) { - // Only if same buildOrder the currentInvalidated project can be sent again - return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ? - state.currentInvalidatedProject : - undefined; - } var options = state.options, projectPendingBuild = state.projectPendingBuild; for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { var project = buildOrder[projectIndex]; @@ -124571,9 +126524,9 @@ var ts; watchPackageJsonFiles(state, project, projectPath, config); } var status = getUpToDateStatus(state, config, projectPath); - verboseReportProjectStatus(state, project, status); if (!options.force) { if (status.type === ts.UpToDateStatusType.UpToDate) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Up to date, skip @@ -124583,12 +126536,20 @@ var ts; } continue; } - if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) { + if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes || status.type === ts.UpToDateStatusType.UpToDateWithInputFileText) { reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); - return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder); + return { + kind: InvalidatedProjectKind.UpdateOutputFileStamps, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config + }; } } if (status.type === ts.UpToDateStatusType.UpstreamBlocked) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); if (options.verbose) { @@ -124599,17 +126560,37 @@ var ts; continue; } if (status.type === ts.UpToDateStatusType.ContainerOnly) { + verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); // Do nothing continue; } - return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ? - InvalidatedProjectKind.Build : - InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder); + return { + kind: needsBuild(state, status, config) ? + InvalidatedProjectKind.Build : + InvalidatedProjectKind.UpdateBundle, + status: status, + project: project, + projectPath: projectPath, + projectIndex: projectIndex, + config: config, + }; } return undefined; } + function createInvalidatedProjectWithInfo(state, info, buildOrder) { + verboseReportProjectStatus(state, info.project, info.status); + return info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps ? + createBuildOrUpdateInvalidedProject(info.kind, state, info.project, info.projectPath, info.projectIndex, info.config, buildOrder) : + createUpdateOutputFileStampsProject(state, info.project, info.projectPath, info.config, buildOrder); + } + function getNextInvalidatedProject(state, buildOrder, reportQueue) { + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); + if (!info) + return info; + return createInvalidatedProjectWithInfo(state, info, buildOrder); + } function listEmittedFile(_a, proj, file) { var write = _a.write; if (write && proj.options.listEmittedFiles) { @@ -124627,7 +126608,7 @@ var ts; } function afterProgramDone(state, program, config) { if (program) { - if (program && state.write) + if (state.write) ts.listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); @@ -124640,7 +126621,8 @@ var ts; state.projectCompilerOptions = state.baseCompilerOptions; } function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) { - var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions()); + // Since buildinfo has changeset and diagnostics when doing multi file emit, only --out cannot emit buildinfo if it has errors + var canEmitBuildInfo = program && !ts.outFile(program.getCompilerOptions()); reportAndStoreErrors(state, resolvedPath, diagnostics); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: "".concat(errorType, " errors") }); if (canEmitBuildInfo) @@ -124648,9 +126630,107 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } + function isFileWatcherWithModifiedTime(value) { + return !!value.watcher; + } + function getModifiedTime(state, fileName) { + var path = toPath(state, fileName); + var existing = state.filesWatched.get(path); + if (state.watch && !!existing) { + if (!isFileWatcherWithModifiedTime(existing)) + return existing; + if (existing.modifiedTime) + return existing.modifiedTime; + } + // In watch mode we store the modified times in the cache + // This is either Date | FileWatcherWithModifiedTime because we query modified times first and + // then after complete compilation of the project, watch the files so we dont want to loose these modified times. + var result = ts.getModifiedTime(state.host, fileName); + if (state.watch) { + if (existing) + existing.modifiedTime = result; + else + state.filesWatched.set(path, result); + } + return result; + } + function watchFile(state, file, callback, pollingInterval, options, watchType, project) { + var path = toPath(state, file); + var existing = state.filesWatched.get(path); + if (existing && isFileWatcherWithModifiedTime(existing)) { + existing.callbacks.push(callback); + } + else { + var watcher = state.watchFile(file, function (fileName, eventKind, modifiedTime) { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + existing.modifiedTime = modifiedTime; + existing.callbacks.forEach(function (cb) { return cb(fileName, eventKind, modifiedTime); }); + }, pollingInterval, options, watchType, project); + state.filesWatched.set(path, { callbacks: [callback], watcher: watcher, modifiedTime: existing }); + } + return { + close: function () { + var existing = ts.Debug.checkDefined(state.filesWatched.get(path)); + ts.Debug.assert(isFileWatcherWithModifiedTime(existing)); + if (existing.callbacks.length === 1) { + state.filesWatched.delete(path); + ts.closeFileWatcherOf(existing); + } + else { + ts.unorderedRemoveItem(existing.callbacks, callback); + } + } + }; + } + function getOutputTimeStampMap(state, resolvedConfigFilePath) { + // Output timestamps are stored only in watch mode + if (!state.watch) + return undefined; + var result = state.outputTimeStamps.get(resolvedConfigFilePath); + if (!result) + state.outputTimeStamps.set(resolvedConfigFilePath, result = new ts.Map()); + return result; + } + function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) { + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(options); + var existing = getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath); + var modifiedTime = getCurrentTime(state.host); + if (existing) { + existing.buildInfo = buildInfo; + existing.modifiedTime = modifiedTime; + if (!(resultFlags & BuildResultFlags.DeclarationOutputUnchanged)) + existing.latestChangedDtsTime = modifiedTime; + } + else { + state.buildInfoCache.set(resolvedConfigPath, { + path: toPath(state, buildInfoPath), + buildInfo: buildInfo, + modifiedTime: modifiedTime, + latestChangedDtsTime: resultFlags & BuildResultFlags.DeclarationOutputUnchanged ? undefined : modifiedTime, + }); + } + } + function getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + return (existing === null || existing === void 0 ? void 0 : existing.path) === path ? existing : undefined; + } + function getBuildInfo(state, buildInfoPath, resolvedConfigPath, modifiedTime) { + var path = toPath(state, buildInfoPath); + var existing = state.buildInfoCache.get(resolvedConfigPath); + if (existing !== undefined && existing.path === path) { + return existing.buildInfo || undefined; + } + var value = state.readFileWithCache(buildInfoPath); + var buildInfo = value ? ts.getBuildInfo(value) : undefined; + ts.Debug.assert(modifiedTime || !buildInfo); + state.buildInfoCache.set(resolvedConfigPath, { path: path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || ts.missingFileModifiedTime }); + return buildInfo; + } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = ts.getModifiedTime(state.host, configFile); + var tsconfigTime = getModifiedTime(state, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -124660,88 +126740,24 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { - var force = !!state.options.force; - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - var host = state.host; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: ts.UpToDateStatusType.Unbuildable, - reason: "".concat(inputFile, " does not exist") - }; - } - if (!force) { - var inputTime = ts.getModifiedTime(host, inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - } + var _a, _b; // Container if no files are specified in the project if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) { return { type: ts.UpToDateStatusType.ContainerOnly }; } - // Collect the expected outputs of this project - var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - if (!force) { - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = ts.getModifiedTime(host, output); - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (ts.isDeclarationFileName(output)) { - var outputModifiedTime = ts.getModifiedTime(host, output); - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; + // Fast check to see if reference projects are upto date and error free + var referenceStatuses; + var force = !!state.options.force; if (project.projectReferences) { state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream }); - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); + for (var _i = 0, _c = project.projectReferences; _i < _c.length; _i++) { + var ref = _c[_i]; var resolvedRef = ts.resolveProjectReferencePath(ref); var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef); - var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath); + var resolvedConfig = parseConfigFile(state, resolvedRef, resolvedRefPath); + var refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath); // Its a circular reference ignore the status of this project if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream || refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project @@ -124763,75 +126779,192 @@ var ts; upstreamProjectName: ref.path }; } - // Check oldest output file name only if there is no missing output file name - // (a check we will have skipped if this is a forced build) - if (!force && !missingOutputFileName) { - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + if (!force) + (referenceStatuses || (referenceStatuses = [])).push({ ref: ref, refStatus: refStatus, resolvedRefPath: resolvedRefPath, resolvedConfig: resolvedConfig }); + } + } + if (force) + return { type: ts.UpToDateStatusType.ForceBuild }; + // Check buildinfo first + var host = state.host; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); + var oldestOutputFileName; + var oldestOutputFileTime = maximumDate; + var buildInfoTime; + var buildInfoProgram; + var buildInfoVersionMap; + if (buildInfoPath) { + var buildInfoCacheEntry_1 = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath); + buildInfoTime = (buildInfoCacheEntry_1 === null || buildInfoCacheEntry_1 === void 0 ? void 0 : buildInfoCacheEntry_1.modifiedTime) || ts.getModifiedTime(host, buildInfoPath); + if (buildInfoTime === ts.missingFileModifiedTime) { + if (!buildInfoCacheEntry_1) { + state.buildInfoCache.set(resolvedPath, { + path: toPath(state, buildInfoPath), + buildInfo: false, + modifiedTime: buildInfoTime + }); + } + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: buildInfoPath + }; + } + var buildInfo = ts.Debug.checkDefined(getBuildInfo(state, buildInfoPath, resolvedPath, buildInfoTime)); + if ((buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + return { + type: ts.UpToDateStatusType.TsVersionOutputOfDate, + version: buildInfo.version + }; + } + if (buildInfo.program) { + // If there are pending changes that are not emitted, project is out of date + 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))) { return { - type: ts.UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path + type: ts.UpToDateStatusType.OutOfDateBuildInfo, + buildInfoFile: buildInfoPath }; } + buildInfoProgram = buildInfo.program; } + oldestOutputFileTime = buildInfoTime; + oldestOutputFileName = buildInfoPath; } - if (missingOutputFileName !== undefined) { - return { - type: ts.UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; + // Check input files + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + /** True if input file has changed timestamp but text is not changed, we can then do only timestamp updates on output to make it look up-to-date later */ + var pseudoInputUpToDate = false; + // Get timestamps of input files + for (var _d = 0, _e = project.fileNames; _d < _e.length; _d++) { + var inputFile = _e[_d]; + var inputTime = getModifiedTime(state, inputFile); + if (inputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.Unbuildable, + reason: "".concat(inputFile, " does not exist") + }; + } + // If an buildInfo is older than the newest input, we can stop checking + if (buildInfoTime && buildInfoTime < inputTime) { + var version_3 = void 0; + var currentVersion = void 0; + if (buildInfoProgram) { + // Read files and see if they are same, read is anyways cached + if (!buildInfoVersionMap) + buildInfoVersionMap = ts.getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + version_3 = buildInfoVersionMap.get(toPath(state, inputFile)); + var text = version_3 ? state.readFileWithCache(inputFile) : undefined; + currentVersion = text && (host.createHash || ts.generateDjb2Hash)(text); + if (version_3 && version_3 === currentVersion) + pseudoInputUpToDate = true; + } + if (!version_3 || version_3 !== currentVersion) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: buildInfoPath, + newerInputFileName: inputFile + }; + } + } + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - if (isOutOfDateWithInputs) { - return { - type: ts.UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; + // Now see if all outputs are newer than the newest input + // Dont check output timestamps if we have buildinfo telling us output is uptodate + if (!buildInfoPath) { + // Collect the expected outputs of this project + var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, resolvedPath); + for (var _f = 0, outputs_1 = outputs; _f < outputs_1.length; _f++) { + var output = outputs_1[_f]; + var path = toPath(state, output); + // Output is missing; can stop checking + var outputTime = outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.get(path); + if (!outputTime) { + outputTime = ts.getModifiedTime(state.host, output); + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.set(path, outputTime); + } + if (outputTime === ts.missingFileModifiedTime) { + return { + type: ts.UpToDateStatusType.OutputMissing, + missingOutputFileName: output + }; + } + // If an output is older than the newest input, we can stop checking + if (outputTime < newestInputFileTime) { + return { + type: ts.UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: output, + newerInputFileName: newestInputFileName + }; + } + // No need to get newestDeclarationFileContentChangedTime since thats needed only for composite projects + // And composite projects are the only ones that can be referenced + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + } } - else { - // Check tsconfig time - var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); - if (configStatus) - return configStatus; - // Check extended config time - var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); - if (extendedConfigStatus) - return extendedConfigStatus; - // Check package file time - var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { - var path = _a[0]; - return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); - }); - if (dependentPackageFileStatus) - return dependentPackageFileStatus; - } - if (!force && !state.buildInfoChecked.has(resolvedPath)) { - state.buildInfoChecked.set(resolvedPath, true); - var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); - if (buildInfoPath) { - var value = state.readFileWithCache(buildInfoPath); - var buildInfo = value && ts.getBuildInfo(value); - if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) { + var seenRefs = buildInfoPath ? new ts.Set() : undefined; + var buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath); + seenRefs === null || seenRefs === void 0 ? void 0 : seenRefs.add(resolvedPath); + /** Inputs are up-to-date, just need either timestamp update or bundle prepend manipulation to make it look up-to-date */ + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (referenceStatuses) { + for (var _g = 0, referenceStatuses_1 = referenceStatuses; _g < referenceStatuses_1.length; _g++) { + var _h = referenceStatuses_1[_g], ref = _h.ref, refStatus = _h.refStatus, resolvedConfig = _h.resolvedConfig, resolvedRefPath = _h.resolvedRefPath; + usesPrepend = usesPrepend || !!(ref.prepend); + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // Check if tsbuildinfo path is shared, then we need to rebuild + if (buildInfoCacheEntry && hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath)) { return { - type: ts.UpToDateStatusType.TsVersionOutputOfDate, - version: buildInfo.version + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: buildInfoPath, + newerProjectName: ref.path }; } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + var newestDeclarationFileContentChangedTime = getLatestChangedDtsTime(state, resolvedConfig.options, resolvedRefPath); + if (newestDeclarationFileContentChangedTime && newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: ts.UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } } + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + // Check package file time + var dependentPackageFileStatus = ts.forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || ts.emptyArray, function (_a) { + var path = _a[0]; + return checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName); + }); + if (dependentPackageFileStatus) + return dependentPackageFileStatus; if (usesPrepend && pseudoUpToDate) { return { type: ts.UpToDateStatusType.OutOfDateWithPrepend, @@ -124841,15 +126974,36 @@ var ts; } // Up to date return { - type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + type: pseudoUpToDate ? + ts.UpToDateStatusType.UpToDateWithUpstreamTypes : + pseudoInputUpToDate ? + ts.UpToDateStatusType.UpToDateWithInputFileText : + ts.UpToDateStatusType.UpToDate, newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, oldestOutputFileName: oldestOutputFileName }; } + function hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig, resolvedRefPath) { + if (seenRefs.has(resolvedRefPath)) + return false; + seenRefs.add(resolvedRefPath); + var refBuildInfo = state.buildInfoCache.get(resolvedRefPath); + if (refBuildInfo.path === buildInfoCacheEntry.path) + return true; + if (resolvedConfig.projectReferences) { + // Check references + for (var _i = 0, _a = resolvedConfig.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRef = ts.resolveProjectReferencePath(ref); + var resolvedRefPath_1 = toResolvedConfigFilePath(state, resolvedRef); + var resolvedConfig_1 = parseConfigFile(state, resolvedRef, resolvedRefPath_1); + if (hasSameBuildInfo(state, buildInfoCacheEntry, seenRefs, resolvedConfig_1, resolvedRefPath_1)) + return true; + } + } + return false; + } function getUpToDateStatus(state, project, resolvedPath) { if (project === undefined) { return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; @@ -124862,39 +127016,71 @@ var ts; state.projectStatus.set(resolvedPath, actual); return actual; } - function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) { if (proj.options.noEmit) - return priorNewestUpdateTime; + return; + var now; + var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(proj.options); + if (buildInfoPath) { + // For incremental projects, only buildinfo needs to be upto date with timestamp check + // as we dont check output files for up-to-date ness + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(toPath(state, buildInfoPath)))) { + if (!!state.options.verbose) + reportStatus(state, verboseMessage, proj.options.configFilePath); + state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); + getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; + } + state.outputTimeStamps.delete(projectPath); + return; + } var host = state.host; var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); + var outputTimeStampMap = getOutputTimeStampMap(state, projectPath); + var modifiedOutputs = outputTimeStampMap ? new ts.Set() : undefined; if (!skipOutputs || outputs.length !== skipOutputs.size) { var reportVerbose = !!state.options.verbose; - var now = host.now ? host.now() : new Date(); for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { var file = outputs_2[_i]; - if (skipOutputs && skipOutputs.has(toPath(state, file))) { + var path = toPath(state, file); + if (skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(path)) continue; - } if (reportVerbose) { reportVerbose = false; reportStatus(state, verboseMessage, proj.options.configFilePath); } - if (ts.isDeclarationFileName(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); + host.setModifiedTime(file, now || (now = getCurrentTime(state.host))); + // Store output timestamps in a map because non incremental build will need to check them to determine up-to-dateness + if (outputTimeStampMap) { + outputTimeStampMap.set(path, now); + modifiedOutputs.add(path); } - host.setModifiedTime(file, now); } } - return priorNewestUpdateTime; + // Clear out timestamps not in output list any more + outputTimeStampMap === null || outputTimeStampMap === void 0 ? void 0 : outputTimeStampMap.forEach(function (_value, key) { + if (!(skipOutputs === null || skipOutputs === void 0 ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) + outputTimeStampMap.delete(key); + }); + } + function getLatestChangedDtsTime(state, options, resolvedConfigPath) { + if (!options.composite) + return undefined; + var entry = ts.Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); + if (entry.latestChangedDtsTime !== undefined) + return entry.latestChangedDtsTime || undefined; + var latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? + state.host.getModifiedTime(ts.getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, ts.getDirectoryPath(entry.path))) : + undefined; + entry.latestChangedDtsTime = latestChangedDtsTime || false; + return latestChangedDtsTime; } function updateOutputTimestamps(state, proj, resolvedPath) { if (state.options.dry) { return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath); } - var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); + updateOutputTimestampsWorker(state, proj, resolvedPath, ts.Diagnostics.Updating_output_timestamps_of_project_0); state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: priorNewestUpdateTime, oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames()) }); } @@ -124940,6 +127126,7 @@ var ts; break; } // falls through + case ts.UpToDateStatusType.UpToDateWithInputFileText: case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: case ts.UpToDateStatusType.OutOfDateWithPrepend: if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { @@ -125050,9 +127237,9 @@ var ts; function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) { state.reportFileChangeDetected = true; invalidateProject(state, resolvedPath, reloadLevel); - scheduleBuildInvalidatedProject(state); + scheduleBuildInvalidatedProject(state, 250, /*changeDetected*/ true); } - function scheduleBuildInvalidatedProject(state) { + function scheduleBuildInvalidatedProject(state, time, changeDetected) { var hostWithWatch = state.hostWithWatch; if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; @@ -125060,25 +127247,38 @@ var ts; if (state.timerToBuildInvalidatedProject) { hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject); } - state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state); + state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, state, changeDetected); } - function buildNextInvalidatedProject(state) { + function buildNextInvalidatedProject(state, changeDetected) { state.timerToBuildInvalidatedProject = undefined; if (state.reportFileChangeDetected) { state.reportFileChangeDetected = false; state.projectErrorsReported.clear(); reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation); } + var projectsBuilt = 0; var buildOrder = getBuildOrder(state); var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false); if (invalidatedProject) { invalidatedProject.done(); - if (state.projectPendingBuild.size) { - // Schedule next project for build - if (state.watch && !state.timerToBuildInvalidatedProject) { - scheduleBuildInvalidatedProject(state); + projectsBuilt++; + while (state.projectPendingBuild.size) { + // If already scheduled, skip + if (state.timerToBuildInvalidatedProject) + return; + // Before scheduling check if the next project needs build + var info = getNextInvalidatedProjectCreateInfo(state, buildOrder, /*reportQueue*/ false); + if (!info) + break; // Nothing to build any more + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps && (changeDetected || projectsBuilt === 5)) { + // Schedule next project for build + scheduleBuildInvalidatedProject(state, 100, /*changeDetected*/ false); + return; } - return; + var project = createInvalidatedProjectWithInfo(state, info, buildOrder); + project.done(); + if (info.kind !== InvalidatedProjectKind.UpdateOutputFileStamps) + projectsBuilt++; } } disableCache(state); @@ -125087,12 +127287,10 @@ var ts; function watchConfigFile(state, resolved, resolvedPath, parsed) { if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; - state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(resolved, function () { - invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); - }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); + state.allWatchedConfigFiles.set(resolvedPath, watchFile(state, resolved, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(state, extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -125124,7 +127322,7 @@ var ts; if (!state.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), { - createNewValue: function (_path, input) { return state.watchFile(input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, + createNewValue: function (_path, input) { return watchFile(state, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.SourceFile, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -125132,7 +127330,7 @@ var ts; if (!state.watch || !state.lastCachedPackageJsonLookups) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), new ts.Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), { - createNewValue: function (path, _input) { return state.watchFile(path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, + createNewValue: function (path, _input) { return watchFile(state, path, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.PackageJson, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -125182,8 +127380,6 @@ var ts; return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath); }, invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); }, - buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); }, - getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); }, close: function () { return stopWatching(state); }, }; } @@ -125264,19 +127460,18 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { - if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { - return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); - } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); case ts.UpToDateStatusType.OutOfDateWithUpstream: - return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.OutputMissing: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName)); + case ts.UpToDateStatusType.OutOfDateBuildInfo: + return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), relName(state, status.buildInfoFile)); case ts.UpToDateStatusType.UpToDate: if (status.newestInputFileTime !== undefined) { - return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); } // Don't report anything for "up to date because it was already built" -- too verbose break; @@ -125284,6 +127479,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName)); case ts.UpToDateStatusType.UpToDateWithUpstreamTypes: return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName)); + case ts.UpToDateStatusType.UpToDateWithInputFileText: + return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, relName(state, configFileName)); case ts.UpToDateStatusType.UpstreamOutOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName)); case ts.UpToDateStatusType.UpstreamBlocked: @@ -125294,6 +127491,8 @@ var ts; return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason); case ts.UpToDateStatusType.TsVersionOutputOfDate: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, ts.version); + case ts.UpToDateStatusType.ForceBuild: + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); case ts.UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects // falls through @@ -125460,7 +127659,7 @@ var ts; * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ - function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry, compilerOptions) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } @@ -125478,12 +127677,14 @@ var ts; addInferredTypings(typeAcquisition.include, "Explicitly included types"); var exclude = typeAcquisition.exclude || []; // Directories to search for package.json, bower.json and other typing information - var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); - possibleSearchDirs.add(projectRootPath); - possibleSearchDirs.forEach(function (searchDir) { - getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); - getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); - }); + if (!compilerOptions.types) { + var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); + possibleSearchDirs.add(projectRootPath); + possibleSearchDirs.forEach(function (searchDir) { + getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); + getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); + }); + } if (!typeAcquisition.disableFilenameBasedTypeAcquisition) { getTypingNamesFromSourceFileNames(fileNames); } @@ -125859,7 +128060,7 @@ var ts; if (this.safeList === undefined) { this.initializeSafeList(); } - var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, this.log.isEnabled() ? (function (s) { return _this.log.writeLine(s); }) : undefined, req.fileNames, req.projectRootPath, this.safeList, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports, this.typesRegistry); + var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, this.log.isEnabled() ? (function (s) { return _this.log.writeLine(s); }) : undefined, req.fileNames, req.projectRootPath, this.safeList, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports, this.typesRegistry, req.compilerOptions); if (this.log.isEnabled()) { this.log.writeLine("Finished typings discovery: ".concat(JSON.stringify(discoverTypingsResult))); } diff --git a/tsserver/zh-cn/diagnosticMessages.generated.json b/tsserver/zh-cn/diagnosticMessages.generated.json index c842e78c..bc09e0e3 100644 --- a/tsserver/zh-cn/diagnosticMessages.generated.json +++ b/tsserver/zh-cn/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "\"this\" 类型仅在类或接口的非静态成员中可用。", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "已在“{0}”中定义了 \"tsconfig.json\" 文件。", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "元组成员不能既是可选的又是 rest。", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "不能使用负值为元组类型编制索引。", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "乘方表达式的左侧不允许出现类型断言表达式。请考虑用括号将表达式括起。", "A_type_literal_property_cannot_have_an_initializer_1247": "类型文字数据不可具有初始化表达式。", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "仅类型导入可以指定默认导入或命名绑定,但不能同时指定这两者。", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "向属性“{0}”添加明确的赋值断言", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "将明确赋值断言添加到未初始化的所有属性", "Add_export_to_make_this_file_into_a_module_95097": "添加 \"export {}\",将此文件变为模块", + "Add_extends_constraint_2211": "添加 `extends` 约束。", + "Add_extends_constraint_to_all_type_parameters_2212": "将 `extends` 约束添加到所有类型参数", "Add_import_from_0_90057": "从“{0}”添加导入", "Add_index_signature_for_property_0_90017": "为属性“{0}”添加索引签名", "Add_initializer_to_property_0_95019": "向属性“{0}”添加初始值设定项", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引签名参数必须具有类型批注。", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "索引签名参数类型不能为文本类型或泛型类型。请考虑改用映射的对象类型。", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "索引签名参数类型必须是 “string”、“number”、“symbol”或模板文本类型。", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "实例化表达式不能后跟属性访问。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "接口只能扩展具有可选类型参数的标识符/限定名称。", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "接口只能扩展使用静态已知成员的对象类型或对象类型的交集。", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "接口无法扩展基元类型,如“{0}”;接口只能扩展命名类型和类", "An_interface_property_cannot_have_an_initializer_1246": "接口函数不能具有初始化表达式。", "An_iterator_must_have_a_next_method_2489": "迭代器必须具有 \"next()\" 方法。", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "将 @jsx 杂注与 JSX 片段一起使用时,需要使用 @jsxFrag 杂注。", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "类“{0}”错误实现类“{1}”。你是想扩展“{1}”并将其成员作为子类继承吗?", "Class_0_incorrectly_implements_interface_1_2420": "类“{0}”错误实现接口“{1}”。", "Class_0_used_before_its_declaration_2449": "类“{0}”用于其声明前。", + "Class_constructor_may_not_be_a_generator_1360": "类构造函数可能不是生成器。", + "Class_constructor_may_not_be_an_accessor_1341": "类构造函数可能不是访问器。", "Class_declaration_cannot_implement_overload_list_for_0_2813": "类声明无法实现“{0}”的重载列表。", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "类声明不能有多个 “@augments” 或 “@extends” 标记。", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "类修饰器不能与静态专用标识符一起使用。请考虑删除实验性修饰器。", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "找不到文件“{0}”。", "File_Management_6245": "文件管理", "File_change_detected_Starting_incremental_compilation_6032": "检测到文件更改。正在启动增量编译...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "文件是 CommonJS 模块,因为“{0}”没有字段 “type”", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "文件是 CommonJS 模块,因为“{0}”具有值不是 “module” 的字段 “type”", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "文件是 CommonJS 模块,因为找不到 “package.json”", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "文件是 ECMAScript 模块,因为“{0}”具有值为 “module” 的字段 “type”", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "文件是 CommonJS 模块; 它可能会转换为 ES 模块。", "File_is_default_library_for_target_specified_here_1426": "文件是此处指定的目标的默认库。", "File_is_entry_point_of_type_library_specified_here_1419": "文件是此处指定的类型库的入口点。", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "应为标识符。\"{0}\" 是保留字,不能在此处使用。", "Identifier_expected_1003": "应为标识符。", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "应为标识符。转换 ECMAScript 模块时,\"__esModule\" 保留为导出标记。", + "Identifier_or_string_literal_expected_1478": "应为标识符或字符串字面量。", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "如果“{0}”包实际上公开此模块,请考虑发送拉取请求以修正“https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}”", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "如果“{0}”包实际公开了此模块,请尝试添加包含 `declare module‘{1}';` 的新声明(.d.ts)文件", "Ignore_this_error_message_90019": "忽略此错误信息", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "无效的导入说明符 '{0}' 没有可行的解决方法。", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "扩大中的模块名称无效。模块“{0}”解析到位于“{1}”处的非类型化模块,其无法扩大。", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "扩大中的模块名无效,找不到模块“{0}”。", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "新表达式中的可选链无效。是否要调用“{0}()”?", "Invalid_reference_directive_syntax_1084": "\"reference\" 指令语法无效。", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "“{0}”的使用无效。它不能在类静态块内使用。", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "“{0}”的使用无效。模块自动处于严格模式。", @@ -893,6 +906,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_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}”。", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "成员 \"{0}\" 隐式具有 \"{1}\" 类型,但可以从用法中推断出更好的类型。", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "无法生成项目“{0}”,因为其依赖项“{1}”有错误", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "无法生成项目 \"{0}\" ,因为未生成其依赖项 \"{1}\"", "Project_0_is_being_forcibly_rebuilt_6388": "正在强制重新生成项目“{0}”", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "项目“{0}”已过期,因为 buildinfo 文件“{1}”指示某些更改未发出", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "项目“{0}”已过期,因为其依赖项“{1}”已过期", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "项目“{0}”已过期,因为最早的输出“{1}”早于最新的输入“{2}”", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "项目“{0}”已过期,因为输出“{1}”早于输入“{2}”", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "项目“{0}”已过期,因为输出文件“{1}”不存在", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "项目 \"{0}\" 已过期,因为其输出是使用与当前版本 \"{2}\" 不同的版本 \"{1}\" 生成的", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "项目 \"{0}\" 已过期,因为其依赖项 \"{1}\" 的输出已更改", "Project_0_is_up_to_date_6361": "“{0}”项目已是最新", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "项目“{0}”已是最新,因为最新的输入“{1}”早于最早的输出“{2}”", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "项目“{0}”是最新的,因为最新的输入“{1}”早于输出“{2}”", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "项目“{0}”是最新的,但需要更新早于输入文件的输出文件的时间戳", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "项目“{0}”已是最新,拥有来自其依赖项的 .d.ts 文件", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "项目引用不能形成环形图。检测到循环: {0}", "Projects_6255": "项目", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "所需的类型参数可能不遵循可选类型参数。", "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}”的解析。", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "仅当 `moduleResolution` 为 `node16` 或 `nodenext` 时才支持解析模式。", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "只将 \"keyof\" 解析为字符串值的属性名称(不含数字或符号)。", "Resolving_module_0_from_1_6086": "======== 正在从“{1}”解析模块“{0}”。========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "正在相对于基 URL“{1}”-“{2}”解析模块名“{0}”。", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "在将 “export type” 用在其导出语句上时,不能在已命名导出上使用 “type” 修饰符。", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "在将 “import type” 用在其导入语句上时,不能在已命名导入上使用 “type” 修饰符。。", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "函数声明的类型必须与函数的签名匹配。", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "如果没有“resolution-mode”断言(这是不稳定的功能),则无法命名此表达式的类型。请使用夜间 TypeScript 来消除此错误。请尝试使用“npm install -D typescript@next”进行更新。", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "无法序列化此节点的类型,因为无法序列化其属性“{0}”。", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "异步迭代器的 \"{0}()\" 方法返回的类型必须是具有 \"value\" 属性的类型的承诺。", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "迭代器的 \"{0}()\" 方法返回的类型必须具有 \"value\" 属性。", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "不支持 \"with\" 语句。\"with\" 程序块中的所有符号都将具有类型 \"any\"。", "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_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "此条件将始终返回“{0}”,因为 JavaScript 按引用而不是值比较对象。", "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367": "此条件将始终返回 \"{0}\",因为类型 \"{1}\" 和 \"{2}\" 没有重叠。", "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,因为始终定义了函数。你是想改为调用它吗?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "此语法需要一个导入的帮助程序,但找不到模块“{0}”。", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "此语法需要名为 \"{1}\" 的导入帮助器,\"{0}\" 中不存在该帮助器。请考虑升级 \"{0}\" 的版本。", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "此语法需要一个名为 \"{1}\" 且包含 {2} 参数的导入帮助程序,该帮助程序与 \"{0}\" 中的相应帮助程序不兼容。请考虑升级 \"{0}\" 的版本。", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "此类型参数可能需要 `extends {0}` 约束。", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "“import” 的这种用法无效。可以写入 “import()” 调用,但它们必须具有括号,并且不能带有类型参数。", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "仅当 “module” 选项设置为 “es2022”、“esnext”、“system”、“node16” 或 “nodenext”,且 “target” 选项设置为 “es2017” 或更高版本时,才允许使用顶级 “await” 表达式。", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": ".d.ts 文件中的顶级声明必须以 \"declare\" 或 \"export\" 修饰符开头。", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "通过 \"{0}\" 从具有 packageId \"{2}\" 的文件 \"{1}\" 引用了库类型", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "\"await\" 操作数的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "计算属性类型的值为 \"{0}\",该值不能赋给 \"{1}\" 类型。", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "实例成员变量“{0}”的类型不能引用构造函数中声明的标识符“{1}”。", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "\"yield*\" 操作数的迭代元素的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "属性“{0}”的类型在已映射的类型“{1}”中循环引用其自身。", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "异步生成器中 \"yield\" 操作数的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== 未解析类型引用指令“{0}”。========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 类型引用指令“{0}”已成功解析为“{1}”,主要: {2}。========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== 类型引用指令 \"{0}\" 已成功解析为 \"{1}\" ,包 ID 为 \"{2}\",主要: {3}。========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "类型不能出现在 JavaScript 文件的导出声明中。", "Types_have_separate_declarations_of_a_private_property_0_2442": "类型具有私有属性“{0}”的单独声明。", "Types_of_construct_signatures_are_incompatible_2419": "构造签名的类型不兼容。", "Types_of_parameters_0_and_1_are_incompatible_2328": "参数“{0}”和“{1}” 的类型不兼容。", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "观看和生成模式", "Watch_input_files_6005": "监视输入文件。", "Watch_option_0_requires_a_value_of_type_1_5080": "观察选项 \"{0}\" 需要 {1} 类型的值。", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "我们只能通过在此处为整个参数添加类型来写入“{0}”的类型。", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "分配函数时,请检查以确保参数和返回值与子类型兼容。", "When_type_checking_take_into_account_null_and_undefined_6699": "进行类型检查时,请考虑 “null” 和 “undefined”。", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "是否在监视模式下保留过时的控制台输出,而不是清除屏幕。", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "用括号将以下应为对象文字的正文括起来", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "你可以在 {0} 了解编译器选项的所有内容", "You_cannot_rename_a_module_via_a_global_import_8031": "不能通过全局导入对模块进行重命名。", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "不能重命名已在 “node_modules” 文件夹中定义的元素。", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "不能重命名已在另一个 “node_modules” 文件夹中定义的元素。", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "不能重命名标准 TypeScript 库中定义的元素。", "You_cannot_rename_this_element_8000": "无法重命名此元素。", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "“{0}”收到的参数过少,无法在此处充当修饰器。你是要先调用它,然后再写入 \"@{0}()\" 吗?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "“{0}”索引签名不兼容。", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "“{0}”索引类型“{1}”不能分配给“{2}”索引类型“{3}”。", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "“{0}”是基元,但“{1}”是包装器对象。如可能首选使用“{0}”。", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "“{0}”是一种类型,无法在 JavaScript 文件中导入。请在 JSDoc 类型批注中使用“{1}”。", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "\"{0}\" 是一种类型,在同时启用了 \"preserveValueImports\" 和 \"isolatedModules\" 时,必须使用仅类型导入进行导入。", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "“{0}”是“{1}”的未使用重命名。是否打算将其用作类型批注?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "\"{0}\" 可赋给 \"{1}\" 类型的约束,但可以使用约束 \"{2}\" 的其他子类型实例化 \"{1}\"。", + "_0_is_automatically_exported_here_18044": "“{0}”自动导出到此处。", "_0_is_declared_but_its_value_is_never_read_6133": "已声明“{0}”,但从未读取其值。", "_0_is_declared_but_never_used_6196": "“{0}”已声明,但从未使用过。", "_0_is_declared_here_2728": "在此处声明了 \"{0}\"。", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "以下其中一个:", "one_or_more_Colon_6901": "一个或更多:", "options_6024": "选项", + "or_JSX_element_expected_1145": "应为 “{” 或 JSX 元素。", "or_expected_1144": "应为 \"{\" 或 \";\"。", "package_json_does_not_have_a_0_field_6100": "\"package.json\" 没有“{0}”字段。", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "\"package. json\" 没有与版本 \"{0}\" 匹配的 \"typesVersions\" 项。", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "\"readonly\" 修饰符仅可出现在属性声明或索引签名中。", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "仅允许对数组和元组文本类型使用 \"readonly\" 类型修饰符。", "require_call_may_be_converted_to_an_import_80005": "可将“要求”调用转换为导入。", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "仅当“moduleResolution”为“node16”或“nodenext”时才支持“resolution-mode”断言。", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "“resolution-mode”断言不稳定。请使用夜间 TypeScript 消除此错误。请尝试使用“npm install -D typescript@next”进行更新。", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "只能为仅类型导入设置 \"resolution-mode\"。", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "\"resolution-mode\" 是类型导入断言的唯一有效密钥。", "resolution_mode_should_be_either_require_or_import_1453": "“resolution-mode”应为“require”或“import”。", diff --git a/tsserver/zh-tw/diagnosticMessages.generated.json b/tsserver/zh-tw/diagnosticMessages.generated.json index 591800c8..eed2d3e6 100644 --- a/tsserver/zh-tw/diagnosticMessages.generated.json +++ b/tsserver/zh-tw/diagnosticMessages.generated.json @@ -94,6 +94,7 @@ "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526": "'this' 類型只適用於類別或介面的非靜態成員。", "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054": "'tsconfig.json' 檔案已定義於: '{0}'。", "A_tuple_member_cannot_be_both_optional_and_rest_5085": "元組成員不能同時為選用及待用。", + "A_tuple_type_cannot_be_indexed_with_a_negative_value_2514": "元組類型無法以負值編製索引。", "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007": "乘冪運算式左邊不允許類型宣告運算式。請考慮以括弧括住運算式。", "A_type_literal_property_cannot_have_an_initializer_1247": "類型常值屬性不得有初始設定式。", "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363": "僅限類型的匯入可以指定預設匯入或具名繫結,但不能同時指定兩者。", @@ -132,6 +133,8 @@ "Add_definite_assignment_assertion_to_property_0_95020": "將明確指派判斷提示新增至屬性 '{0}'", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "為所有未初始化的屬性新增明確的指派判斷提示", "Add_export_to_make_this_file_into_a_module_95097": "新增 'export {}' 以將此檔案轉為模組", + "Add_extends_constraint_2211": "新增 'extends' 限制式。", + "Add_extends_constraint_to_all_type_parameters_2212": "將 'extends' 限制式新增至所有類型參數", "Add_import_from_0_90057": "從 \"{0}\" 新增匯入", "Add_index_signature_for_property_0_90017": "為屬性 '{0}' 新增索引簽章", "Add_initializer_to_property_0_95019": "將初始設定式新增至屬性 '{0}'", @@ -224,8 +227,10 @@ "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引簽章參數必須有類型註釋。", "An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_o_1337": "索引簽章參數類型不能是常值型別或泛型型別。請考慮改用對應的物件類型。", "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268": "索引簽章參數類型必須是 'string'、'number'、'symbol' 或範本文字類型。", + "An_instantiation_expression_cannot_be_followed_by_a_property_access_1477": "具現化運算式後面不能接著屬性存取。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "介面只能擴充具有選擇性型別引數的識別碼/限定名稱。", "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312": "介面只能延伸物件類型或具有靜態已知成員的物件類型交集。", + "An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_clas_2840": "介面無法延伸基本類型,例如 '{0}';介面只能延伸命名類型和類別", "An_interface_property_cannot_have_an_initializer_1246": "介面屬性不得有初始設定式。", "An_iterator_must_have_a_next_method_2489": "迭代器必須要有 'next()' 方法。", "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017": "在 JSX 片段使用 @jsx pragma 時,必須有 @jsxFrag pragma。", @@ -377,6 +382,8 @@ "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "類別 '{0}' 不當實作類別 '{1}'。您是否要擴充 '{1}',並繼承其成員以成為子類別?", "Class_0_incorrectly_implements_interface_1_2420": "類別 '{0}' 不正確地實作介面 '{1}'。", "Class_0_used_before_its_declaration_2449": "類別 '{0}' 的位置在其宣告之前。", + "Class_constructor_may_not_be_a_generator_1360": "類別建構函式可能不是產生器。", + "Class_constructor_may_not_be_an_accessor_1341": "類別建構函式可能不是存取子。", "Class_declaration_cannot_implement_overload_list_for_0_2813": "類別宣告無法為 '{0}' 實作多載清單。", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "類別宣告不能有一個以上的 `@augments` 或 `@extends` 標籤。", "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036": "類別裝飾項目無法與靜態私人識別碼一起使用。請考慮移除實驗性裝飾項目。", @@ -695,6 +702,10 @@ "File_0_not_found_6053": "找不到檔案 '{0}'。", "File_Management_6245": "檔案管理", "File_change_detected_Starting_incremental_compilation_6032": "偵測到檔案變更。正在啟動累加編譯...", + "File_is_CommonJS_module_because_0_does_not_have_field_type_1460": "檔案是 CommonJS 模組,因為 '{0}' 沒有 \"type\" 欄位", + "File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module_1459": "檔案是 CommonJS 模組,因為 '{0}' 具有值不是 \"module\" 的 \"type\" 欄位", + "File_is_CommonJS_module_because_package_json_was_not_found_1461": "檔案是 CommonJS 模組,因為找不到 'package.json'", + "File_is_ECMAScript_module_because_0_has_field_type_with_value_module_1458": "檔案是 ECMAScript 模組,因為 '{0}' 具有值不是 \"module\" 的 \"type\" 欄位", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "檔案為 CommonJS 模組; 其可轉換為 ES 模組。", "File_is_default_library_for_target_specified_here_1426": "檔案是此處指定目標的預設程式庫。", "File_is_entry_point_of_type_library_specified_here_1419": "檔案是此處指定型別程式庫的進入點。", @@ -769,6 +780,7 @@ "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359": "必須為識別碼。'{0}' 為保留字,此處不可使用。", "Identifier_expected_1003": "必須是識別碼。", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "必須有識別碼。'__esModule' 已保留為轉換 ECMAScript 模組時匯出的標記。", + "Identifier_or_string_literal_expected_1478": "需要識別碼或字串常值。", "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040": "如果「{0}」套件實際上公開了此模組,請考慮傳送提取要求以修改 「https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}」", "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058": "如果 '{0}' 套件的確公開了此模組,請嘗試新增包含 `declare module '{1}';` 的宣告 (.d.ts) 檔案。", "Ignore_this_error_message_90019": "略過此錯誤訊息", @@ -837,6 +849,7 @@ "Invalid_import_specifier_0_has_no_possible_resolutions_6272": "無效的匯入指定名稱 '{0}' 沒有可能的解決方法。", "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665": "增強中的模組名稱無效。模組 '{0}' 於 '{1}' 解析至不具類型的模組,其無法擴增。", "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664": "增強指定中的模組名稱無效,找不到模組 '{0}'。", + "Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0_1209": "新運算式的選擇性鏈結無效。您想要呼叫 '{0}()' 嗎?", "Invalid_reference_directive_syntax_1084": "無效的 'reference' 指示詞語法。", "Invalid_use_of_0_It_cannot_be_used_inside_a_class_static_block_18039": "'{0}' 的使用無效。不能在類別靜態區塊內使用。", "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215": "'{0}' 的用法無效。模組會自動採用 strict 模式。", @@ -893,6 +906,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_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}' 類型。", "Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045": "成員 '{0}' 隱含 '{1}' 類型,但可從使用方式推斷更適合的類型。", @@ -1083,13 +1097,15 @@ "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "因為專案 '{0}' 的相依性 '{1}' 發生錯誤,所以無法建置該專案", "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383": "因為未建置專案 '{0}' 的相依性 '{1}',所以無法建置該專案", "Project_0_is_being_forcibly_rebuilt_6388": "正在強制重建專案 '{0}'", + "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399": "因為 buildinfo 檔案 '{1}' 指出某些變更並未發出,所以專案 '{0}' 已過期", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "因為專案 '{0}' 的相依性 '{1}' 已過期,所以該專案已過期", - "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "因為最舊的輸出 '{1}' 早於最新的輸入 '{2}',所以專案 '{0}' 已過期", + "Project_0_is_out_of_date_because_output_1_is_older_than_input_2_6350": "因為輸出 '{1}' 早於輸入 '{2}',所以專案 '{0}' 已過期", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "因為輸出檔案 '{1}' 不存在,所以專案 '{0}' 已過期", "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381": "因為專案 '{0}' 的輸出使用版本 '{1}' 產生而成,與目前的版本 '{2}' 不同,所以該專案已過期", "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372": "因為專案 '{0}' 的相依性 '{1}' 輸出已變更,所以該專案已過期", "Project_0_is_up_to_date_6361": "專案 '{0}' 為最新狀態", - "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "因為最新的輸入 '{1}' 早於最舊的輸出 '{2}',所以專案 '{0}' 為最新狀態", + "Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2_6351": "因為最新的輸入 '{1}' 早於最舊的輸出 '{2}',所以專案 '{0}' 為最新狀態", + "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400": "專案 '{0}' 為最新狀態,但需要更新比輸入檔案還舊的輸出檔案時間戳記", "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "專案 '{0}' 為最新狀態,且有來自其相依性的 .d.ts 檔案", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "專案參考不會形成循環圖。但偵測到循環: {0}", "Projects_6255": "專案", @@ -1199,7 +1215,6 @@ "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必要型別參數可能未遵循選擇性型別參數。", "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}'。", - "Resolution_modes_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "只有當 'moduleResolution' 為 'node16' 或 'nodenext' 時,才支援解析模式。", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "只將 'keyof' 解析為字串值的屬性名稱 (無任何數字或符號)。", "Resolving_module_0_from_1_6086": "======== 正在從 '{1}' 解析模組 '{0}'。========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "正在解析與基底 URL '{1}' 相對的模組名稱 '{0}' - '{2}'。", @@ -1443,6 +1458,7 @@ "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207": "[類型修飾元] 無法在 [匯出類型]5D; 於其匯出陳述式上使用時,在命名的匯出上使用。", "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206": "[類型修飾元] 無法在 [匯入類型]5D; 於其匯入陳述式上使用時,在命名的匯入上使用。", "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030": "函式宣告的類型必須與函式的簽章相符。", + "The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_2841": "沒有 'resolution-mode' 判斷提示,就無法命名此運算式的類型,這是不穩定的功能。請使用夜間 TypeScript 將此錯誤設為靜音。請嘗試使用 'npm install -D typescript@next' 更新。", "The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized_4118": "無法將此節點的類型序列化,因為無法將其屬性 '{0}' 序列化。", "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547": "非同步迭代器 '{0}()' 方法所傳回的類型,對具有 'value' 屬性的類型必須為 Promise。", "The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property_2490": "迭代器 '{0}()' 方法所傳回的類型必須具有 'value' 屬性。", @@ -1453,6 +1469,7 @@ "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "不支援 'with' 陳述式。'with' 區塊中的所有符號都會有類型 'any'。", "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_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "此條件一律會傳回 '{0}',因為 JavaScript 會依參照而非值比較物件。", "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367": "因為類型 '{1}' 與 '{2}' 未重疊,所以此條件永遠會傳回 '{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。您是要改為呼叫該條件嗎?", @@ -1485,6 +1502,7 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "此語法需要已匯入的協助程式,但找不到模組 '{0}'。", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "此語法需要名為 '{1}' 的已匯入協助程式,但其不存在於 '{0}' 中。請考慮升級您的 '{0}' 版本。", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "此語法需要名為 '{1}' 且具有 {2} 參數的匯入協助程式,其與 '{0}' 中的參數不相容。請考慮升級 '{0}' 的版本。", + "This_type_parameter_might_need_an_extends_0_constraint_2208": "此類型參數可能需要 'extends {0}' 限制式。", "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326": "此 'import' 的使用方式無效。'import()' 呼叫可以寫入,但必須有括弧,而且不能有類型引數。", "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_n_1378": "只有在 'module' 選項設定為 'es2022'、'esnext'、'system'、'node16' 或 'nodenext',而且 'target' 選項設定為 'es2017' 或更高版本時,才允許最上層的 'await' 運算式。", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": ".d.ts 檔案中的最上層宣告必須以 'declare' 或 'export' 修飾元開頭。", @@ -1550,6 +1568,7 @@ "Type_library_referenced_via_0_from_file_1_with_packageId_2_1403": "透過 '{0}' 從檔案 '{1}' (packageId 為 '{2}') 參考的型別程式庫", "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320": "'await' 運算元類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418": "已計算屬性值的類型為 '{0}',其無法指派給類型 '{1}'。", + "Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2844": "執行個體成員變數 '{0}' 的類型不得參考建構函式中所宣告的識別碼 '{1}'。", "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' 運算元的反覆項目類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "屬性 '{0}' 的類型在對應的類型 '{1}' 中會循環參考自己。", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同步產生器中的 'yield' 運算元類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", @@ -1577,6 +1596,7 @@ "Type_reference_directive_0_was_not_resolved_6120": "======== 類型參考指示詞 '{0}' 未解析。========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 類型參考指示詞 '{0}' 已成功解析為 '{1}',主要: {2}。========", "Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3_6219": "======== 類型參考指示詞 '{0}' 已成功解析為 '{1}',套件識別碼為 '{2}',主要: {3}。========", + "Types_cannot_appear_in_export_declarations_in_JavaScript_files_18043": "類型不能出現在 JavaScript 檔案的匯出宣告中。", "Types_have_separate_declarations_of_a_private_property_0_2442": "類型具有私用屬性 '{0}' 的個別宣告。", "Types_of_construct_signatures_are_incompatible_2419": "建構簽章的類型不相容。", "Types_of_parameters_0_and_1_are_incompatible_2328": "參數 '{0}' 和 '{1}' 的類型不相容。", @@ -1642,6 +1662,7 @@ "Watch_and_Build_Modes_6250": "觀看及建置模式", "Watch_input_files_6005": "監看輸入檔。", "Watch_option_0_requires_a_value_of_type_1_5080": "監看選項 '{0}' 需要 {1} 類型的值。", + "We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here_2843": "我們只能在此新增整個參數的類型,來寫入 '{0}' 的類型。", "When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible_6698": "指派函式時,請檢查以確認參數,而且傳回值是子類型相容的。", "When_type_checking_take_into_account_null_and_undefined_6699": "當型別檢查時,請將 'null' 和 'undefined' 納入考慮。", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "是否要將已過期的主控台輸出,維持在監看模式下,而非清除螢幕。", @@ -1653,6 +1674,8 @@ "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "使用括弧括住下列必須是物件常值的主體", "You_can_learn_about_all_of_the_compiler_options_at_0_6913": "您可以在以下位置了解所有編譯器選項: {0}", "You_cannot_rename_a_module_via_a_global_import_8031": "您無法透過全域匯入重新命名模組。", + "You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder_8035": "您無法重新命名 'node_modules' 資料夾中定義的元素。", + "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036": "您無法重新命名其他 'node_modules' 資料夾中定義的元素。", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "您無法重新命名標準 TypeScript 程式庫中所定義的項目。", "You_cannot_rename_this_element_8000": "您無法重新命名這個項目。", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' 在此只接受極少數的引數用為裝飾項目。要先呼叫此項目,然後再寫入 '@{0}()' 嗎?", @@ -1680,8 +1703,11 @@ "_0_index_signatures_are_incompatible_2634": "'{0}' 索引簽章不相容。", "_0_index_type_1_is_not_assignable_to_2_index_type_3_2413": "'{0}' 索引類型 '{1}' 無法指派給 '{2}' 索引類型 '{3}'。", "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' 為基元,但 '{1}' 為包裝函式物件。建議盡可能使用 '{0}'。", + "_0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation_18042": "'{0}' 為類型,無法匯入 JavaScript 檔案。在 JSDoc 類型註釋中使用 '{1}'。", "_0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedMod_1444": "'{0}' 是類型,而且當 'preserveValueImports' 和 'isolatedModules' 都啟用時,必須使用僅類型匯入來匯入。", + "_0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation_2842": "'{0}' 是未使用的 '{1}' 重新命名。您是否想要使用它作為類型註釋?", "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075": "'{0}' 可指派給 '{1}' 類型的條件約束,但可能會將 '{1}' 以不同的條件約束 '{2}' 子類型來具現化。", + "_0_is_automatically_exported_here_18044": "'{0}' 會自動匯出到此處。", "_0_is_declared_but_its_value_is_never_read_6133": "'{0}' 已宣告但從未讀取其值。", "_0_is_declared_but_never_used_6196": "宣告了 '{0}',但從未使用過。", "_0_is_declared_here_2728": "'{0}' 宣告於此處。", @@ -1775,6 +1801,7 @@ "one_of_Colon_6900": "以下其中一個:", "one_or_more_Colon_6901": "以下一或多個:", "options_6024": "選項", + "or_JSX_element_expected_1145": "必須是 '{' 或 JSX 元素。", "or_expected_1144": "必須是 '{' 或 ';'。", "package_json_does_not_have_a_0_field_6100": "'package.json' 沒有 '{0}' 欄位。", "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207": "'package.json' 沒有任何符合 '{0}' 版本的 'typesVersions' 項目。", @@ -1790,6 +1817,8 @@ "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾元只能出現在屬性宣告或索引簽章。", "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354": "'readonly' 類型修飾元只可用於陣列與元組常值類型。", "require_call_may_be_converted_to_an_import_80005": "'require' 呼叫可能會轉換為匯入。", + "resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext_1452": "只有當 'moduleResolution' 為 'node16' 或 'nodenext' 時,才支援 'resolution-mode' 判斷提示。", + "resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_wi_4125": "'resolution-mode' 判斷提示不穩定。使用夜間 TypeScript 將此錯誤設為靜音。請嘗試使用 'npm install -D typescript@next' 更新。", "resolution_mode_can_only_be_set_for_type_only_imports_1454": "只能針對僅限輸入的匯入設定 'resolution-mode'。", "resolution_mode_is_the_only_valid_key_for_type_import_assertions_1455": "'resolution-mode' 是輸入匯入判斷提示唯一有效的索引鍵。", "resolution_mode_should_be_either_require_or_import_1453": "`resolution-mode` 應該是 `require` 或 `import`。",